@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
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { getTracer, noopSpan } from './chunk-K2BQQ445.js';
|
|
2
|
-
import { createSemaphore } from './chunk-
|
|
3
|
-
import { InMemoryTaskStore, getTaskStoreFor, isValidTaskId } from './chunk-
|
|
4
|
-
import { InvalidTaskIdError, TaskNotFoundError } from './chunk-
|
|
5
|
-
import { diag } from './chunk-
|
|
2
|
+
import { createSemaphore } from './chunk-OC4NTGMN.js';
|
|
3
|
+
import { InMemoryTaskStore, getTaskStoreFor, isValidTaskId } from './chunk-RUDY2GTT.js';
|
|
4
|
+
import { InvalidTaskIdError, TaskNotFoundError } from './chunk-IDCKSLYH.js';
|
|
5
|
+
import { diag } from './chunk-T7O6K6PX.js';
|
|
6
6
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
7
7
|
import { randomUUID } from 'crypto';
|
|
8
8
|
|
|
@@ -483,5 +483,5 @@ var subscribe = buildSubscribe({
|
|
|
483
483
|
});
|
|
484
484
|
|
|
485
485
|
export { __getSubscribersCountForTests, __resetTaskRegistryForTests, cancel, configure, emitRunEvent, get, list, submit, subscribe };
|
|
486
|
-
//# sourceMappingURL=chunk-
|
|
487
|
-
//# sourceMappingURL=chunk-
|
|
486
|
+
//# sourceMappingURL=chunk-SUKXXLWD.js.map
|
|
487
|
+
//# sourceMappingURL=chunk-SUKXXLWD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/run-events.ts","../src/internal/task/ring-buffer.ts","../src/internal/task/subscribe.ts","../src/internal/task/task-run-event-bridge.ts","../src/internal/task/telemetry.ts","../src/internal/task/registry.ts"],"names":["subscribe"],"mappings":";;;;;;;;;AAmMO,SAAS,YAAA,CAAa,MAAgC,KAAA,EAAuB;AAClF,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,KAAK,CAAA;AAAA,EACZ,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;AChMO,IAAM,aAAN,MAAoB;AAAA,EAIzB,YAA6B,GAAA,EAAa;AAAb,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,GAAG,CAAA,IAAK,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AI,EAAE,CAAA;AACnC,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,IAAA,uBAAW,GAAA,EAAI;AACf,MAAA,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAA,EAAI,IAAI,CAAA;AAAA,IAChC;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAAA,EACA,gBAAA,EAAkB,CAAC,EAAA,EAAI,EAAA,KAAO;AAC5B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAE,CAAA;AACpC,IAAA,GAAA,EAAK,OAAO,EAAE,CAAA;AACd,IAAA,IAAI,GAAA,KAAQ,UAAa,GAAA,CAAI,IAAA,KAAS,GAAG,KAAA,CAAM,WAAA,CAAY,OAAO,EAAE,CAAA;AAAA,EACtE;AACF,CAAC","file":"chunk-SUKXXLWD.js","sourcesContent":["/**\n * SE2 — typed runtime EVENT stream, ADDITIVE to the `SDKMessage` content stream.\n *\n * `Run.stream()` yields `SDKMessage`s (the conversation content). `RunEvent`s are\n * out-of-band runtime-OBSERVABILITY signals — the model's content is unaffected —\n * delivered opt-in via `SendOptions.onRunEvent`. Discriminate on `type`. Mirrors\n * the Anthropic `SDKMessage`-union approach (rate-limit, permission-denied, task\n * lifecycle, compaction boundary).\n *\n * The union is the forward-compatible CONTRACT (discriminate exhaustively). The\n * runtime EMITS every variant end-to-end: `tool_progress` + `permission_denied`\n * (agent-loop tool-dispatch seam), `rate_limit` (pool-aware LLM client 429 retry),\n * `compact_boundary` (session auto-compaction), and `task_*` (opt-in bridge from a\n * `Task.submit({ onRunEvent })` task's lifecycle). A consumer switching on `type`\n * sees the real signal.\n *\n * @public\n */\nexport type RunEvent =\n | RunToolProgressEvent\n | RunRateLimitEvent\n | RunPermissionDeniedEvent\n | RunTaskStartedEvent\n | RunTaskUpdatedEvent\n | RunTaskCompletedEvent\n | RunCompactBoundaryEvent\n | RunCompactionFallbackEvent\n | RunTripwireEvent\n | RunCompletionCheckEvent\n | RunMcpServerFailedEvent\n | RunMcpServerReadyEvent;\n\n/**\n * theokit#188 — an MCP server was configured but its tools could not be listed, so NONE of its\n * tools exist for this run.\n *\n * The failure was always caught (`safeListTools` returns `[]` so one broken server cannot take the\n * turn down) and always DIAGNOSED — to `diag()`, i.e. the SDK's stderr. Nothing reached the\n * consumer, so a UI listing configured servers could show one as present while every tool it\n * provides had silently vanished. Degrading gracefully is right; degrading INVISIBLY is not.\n *\n * Emitted once per failing server per run, on the same catch path that already had both the name\n * and the reason.\n */\nexport interface RunMcpServerFailedEvent {\n readonly type: \"mcp_server_failed\";\n /** The server as named in the MCP configuration, so the consumer can match it to what it lists. */\n readonly serverName: string;\n /** Why listing failed — a spawn error, a handshake timeout, a protocol error. */\n readonly message: string;\n}\n\n/**\n * usetheokit/theokit#426 — an MCP server came up, and these are the tools it delivered.\n *\n * The sibling of {@link RunMcpServerFailedEvent}, emitted from the same function, on the other\n * branch. Without it a consumer could see what was CONFIGURED and what BROKE, and could not tell a\n * server that came up with twelve tools from one that came up with none — which is exactly the case\n * an operator opens a server-status panel to find. `tools: []` on a healthy server is a real and\n * previously unreportable state.\n *\n * An EVENT rather than a getter, because the state is scoped to the run: with\n * `mcpLifecycle: \"run\"` a server may not exist by the time anyone asks, so a getter would have to\n * answer about something already gone. This says what was true when the run started.\n *\n * Emitted once per successfully-listed server per run.\n */\nexport interface RunMcpServerReadyEvent {\n readonly type: \"mcp_server_ready\";\n /** The server as named in the MCP configuration — the key a consumer already lists it under. */\n readonly serverName: string;\n /**\n * The tool names the server reported, as IT names them.\n *\n * Not the `mcp_<server>_<tool>` form the model sees: that spelling is sanitized for the provider,\n * and a consumer matching it back to a server's own documentation would have to undo the mangling.\n */\n readonly tools: readonly string[];\n}\n\n/**\n * SE24 — a guardrail processor called `abort()`; the run stops with a tripwire.\n * Delivered via {@link SendOptions.onRunEvent} (mirrors the `RunResult.tripwire`\n * surfaced on `wait()`).\n */\nexport interface RunTripwireEvent {\n readonly type: \"tripwire\";\n readonly reason: string;\n readonly processorId: string;\n}\n\n/** A tool call is being dispatched (before its result). */\nexport interface RunToolProgressEvent {\n readonly type: \"tool_progress\";\n readonly toolName: string;\n readonly toolCallId: string;\n}\n\n/** The provider returned a rate-limit (HTTP 429); the loop will back off + retry. */\nexport interface RunRateLimitEvent {\n readonly type: \"rate_limit\";\n /** Retry attempt number (1-based) about to be delayed. */\n readonly attempt: number;\n /** Delay in ms before the retry, when the provider/policy supplied one. */\n readonly retryAfterMs?: number;\n}\n\n/**\n * A tool call was DENIED before dispatch — by the permission gate/plugin (SE1),\n * an operator file-hook `preToolUse`, or the fork tool-whitelist. `source`\n * discriminates which. `toolCallId` joins the event to the tool-call log.\n */\nexport interface RunPermissionDeniedEvent {\n readonly type: \"permission_denied\";\n readonly toolName: string;\n readonly toolCallId: string;\n /** Which layer blocked the call. */\n readonly source: \"plugin\" | \"file_hook\" | \"fork_whitelist\";\n /** The rejection message surfaced to the model. */\n readonly message: string;\n}\n\n/** A background task/subagent started. */\nexport interface RunTaskStartedEvent {\n readonly type: \"task_started\";\n readonly taskId: string;\n readonly description?: string;\n}\n\n/** A background task/subagent changed state. */\nexport interface RunTaskUpdatedEvent {\n readonly type: \"task_updated\";\n readonly taskId: string;\n readonly status: string;\n}\n\n/** A background task/subagent finished. */\nexport interface RunTaskCompletedEvent {\n readonly type: \"task_completed\";\n readonly taskId: string;\n readonly status: \"completed\" | \"failed\" | \"stopped\";\n}\n\n/**\n * SE34 — the per-send completion check (`isTaskComplete`) produced a verdict.\n * Emitted once, after a finished run's reply is judged against\n * {@link SendOptions.completionCheck}. Distinct from `task_completed` (which is\n * background-task/subagent lifecycle). Mirrors {@link RunResult.completionCheck}.\n */\nexport interface RunCompletionCheckEvent {\n readonly type: \"completion_check\";\n readonly complete: boolean;\n readonly reason: string;\n}\n\n/** The conversation crossed a compaction boundary (history was summarized). */\nexport interface RunCompactBoundaryEvent {\n readonly type: \"compact_boundary\";\n readonly trigger: \"manual\" | \"auto\";\n /** Token count before compaction, when known. */\n readonly preTokens?: number;\n}\n\n/**\n * M77 — auto-compaction is budgeting against a FLOOR, because neither the catalog nor the caller\n * supplied a context window for this model.\n *\n * The prior behaviour was to disable auto-compaction entirely and write one line to stderr per\n * process. That is fail-OPEN: the conversation grows until the provider rejects it. This event exists\n * so a surface can say \"I am running without a real budget\" instead of the user discovering it at the\n * moment of failure.\n *\n * Not emitted when the window came from the catalog (the normal path) or from an explicit caller\n * override (the caller already knows).\n */\nexport interface RunCompactionFallbackEvent {\n readonly type: \"compaction_fallback\";\n /** The model whose window is unknown — what the user needs to fix in configuration. */\n readonly model: string;\n /** The floor being budgeted against, after the safety margin. */\n readonly window: number;\n}\n\n/**\n * SE2 — the opt-in sink for {@link RunEvent}s. Supplied via `SendOptions.onRunEvent`.\n * Synchronous + best-effort: a throwing sink must never break the run (the emitter\n * try-catches it), so keep it fast (push to a queue, don't await).\n */\nexport type RunEventSink = (event: RunEvent) => void;\n\n/**\n * SE2 — emit a {@link RunEvent} to an optional sink, swallowing any sink error so\n * observability can never break the run (fail-safe, mirrors the EventBus EC-2\n * contract). No-op when the sink is absent.\n */\nexport function emitRunEvent(sink: RunEventSink | undefined, event: RunEvent): void {\n if (sink === undefined) return;\n try {\n sink(event);\n } catch {\n // best-effort: an observability sink must never break the run.\n }\n}\n","/**\n * Bounded FIFO ring buffer for late-attach replay (ADR D372).\n *\n * Push always succeeds; when the buffer is at capacity the oldest\n * entry is dropped and the `truncated` flag flips to `true`. Drain\n * returns a snapshot + the current truncated flag.\n *\n * @internal\n */\n\nexport class RingBuffer<T> {\n private readonly buf: T[] = [];\n private truncated = false;\n\n constructor(private readonly cap: number) {\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);\n }\n }\n\n push(item: T): void {\n if (this.buf.length >= this.cap) {\n this.buf.shift();\n this.truncated = true;\n }\n this.buf.push(item);\n }\n\n drain(): { readonly items: readonly T[]; readonly truncated: boolean } {\n return { items: this.buf.slice(), truncated: this.truncated };\n }\n\n size(): number {\n return this.buf.length;\n }\n\n wasTruncated(): boolean {\n return this.truncated;\n }\n}\n","/**\n * `subscribe(id)` — emits the per-task event stream (D372 ring buffer\n * + live tail). The returned AsyncIterable implements `return()` for\n * leak-free cleanup (EC-10).\n *\n * @internal\n */\n\nimport { TaskNotFoundError } from \"../../errors.js\";\nimport { isValidTaskId, type TaskEvent } from \"../../types/task.js\";\nimport type { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface SubscribeDeps {\n getBuffer(id: string): RingBuffer<TaskEvent> | undefined;\n getOrCreateSubscriberSet(id: string): Set<(e: TaskEvent) => void>;\n removeSubscriber(id: string, cb: (e: TaskEvent) => void): void;\n}\n\nfunction isTerminalEvent(event: TaskEvent): boolean {\n return event.type === \"finished\" || event.type === \"errored\" || event.type === \"cancelled\";\n}\n\nfunction drainBuffered(buffer: RingBuffer<TaskEvent>): TaskEvent[] {\n const { items, truncated } = buffer.drain();\n const queue = items.slice();\n if (truncated && queue.length > 0) {\n const first = queue[0];\n if (first !== undefined && first.type === \"submitted\") {\n queue[0] = { ...first, truncated: true } satisfies TaskEvent;\n }\n }\n return queue;\n}\n\nclass TaskIterator implements AsyncIterator<TaskEvent> {\n private readonly queue: TaskEvent[];\n private pendingResolve?: (v: IteratorResult<TaskEvent>) => void;\n private done = false;\n private readonly callback: (e: TaskEvent) => void;\n\n constructor(\n buffer: RingBuffer<TaskEvent>,\n private readonly id: string,\n private readonly deps: SubscribeDeps,\n ) {\n this.queue = drainBuffered(buffer);\n this.callback = (e) => this.deliver(e);\n deps.getOrCreateSubscriberSet(id).add(this.callback);\n }\n\n private deliver(e: TaskEvent): void {\n if (this.done) return;\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: e, done: false });\n } else {\n this.queue.push(e);\n }\n }\n\n private cleanup(): void {\n if (this.done) return;\n this.done = true;\n this.deps.removeSubscriber(this.id, this.callback);\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: undefined, done: true });\n }\n }\n\n private dequeue(): IteratorResult<TaskEvent> | undefined {\n const event = this.queue.shift();\n if (event === undefined) return undefined;\n if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());\n return { value: event, done: false };\n }\n\n next(): Promise<IteratorResult<TaskEvent>> {\n if (this.done) return Promise.resolve({ value: undefined, done: true });\n const queued = this.dequeue();\n if (queued !== undefined) return Promise.resolve(queued);\n return new Promise((resolve) => {\n this.pendingResolve = resolve;\n });\n }\n\n return(): Promise<IteratorResult<TaskEvent>> {\n this.cleanup();\n return Promise.resolve({ value: undefined, done: true });\n }\n}\n\nexport function buildSubscribe(deps: SubscribeDeps) {\n return function subscribe(id: string): AsyncIterable<TaskEvent> {\n if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);\n const buffer = deps.getBuffer(id);\n if (buffer === undefined) throw new TaskNotFoundError(id);\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TaskEvent> {\n return new TaskIterator(buffer, id, deps);\n },\n };\n };\n}\n","/**\n * SE2 — the `TaskEvent` → `task_*` RunEvent bridge for the opt-in `onRunEvent`\n * sink. Extracted from `registry.ts` (a pure, self-contained mapping) to keep\n * the registry within the G8 LoC budget and give the bridge one home.\n *\n * @internal\n */\n\nimport type { RunEvent } from \"../../types/run-events.js\";\nimport type { TaskEvent, TaskKind } from \"../../types/task.js\";\n\n/** Map a `TaskEvent` to a `task_*` RunEvent, or `undefined` when it has no counterpart. */\nexport function taskEventToRunEvent(\n event: TaskEvent,\n taskId: string,\n kind: TaskKind,\n): RunEvent | undefined {\n switch (event.type) {\n case \"started\":\n return { type: \"task_started\", taskId, description: kind };\n case \"progress\":\n return { type: \"task_updated\", taskId, status: \"progress\" };\n case \"finished\":\n return { type: \"task_completed\", taskId, status: \"completed\" };\n case \"errored\":\n return { type: \"task_completed\", taskId, status: \"failed\" };\n case \"cancelled\":\n return { type: \"task_completed\", taskId, status: \"stopped\" };\n default:\n return undefined; // `submitted` (queued) has no RunEvent counterpart\n }\n}\n","/**\n * OTel telemetry for the Task registry (ADR D371).\n *\n * Spans:\n * - `task.submit` — short-lived span around the submit + insert.\n * - `task.transition` — per state transition (attrs: from / to).\n * - `task.cancel` — invoked from `Task.cancel` or via cancelRequested honor.\n *\n * Uses the existing tracer seam (D34); when OTel is absent, every helper\n * returns the shared no-op span. No new peer deps.\n *\n * @internal\n */\n\nimport { getTracer, noopSpan, type SpanLike } from \"../telemetry/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/task\";\n\nexport function startTaskSubmitSpan(info: { taskId: string; kind: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.submit\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.kind\": info.kind,\n },\n });\n}\n\nexport function startTaskTransitionSpan(info: {\n taskId: string;\n from: string;\n to: string;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.transition\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.state.from\": info.from,\n \"task.state.to\": info.to,\n },\n });\n}\n\nexport function startTaskCancelSpan(info: {\n taskId: string;\n reason?: string;\n via: \"api\" | \"cancelRequested\";\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.cancel\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.cancel.via\": info.via,\n ...(info.reason !== undefined ? { \"task.cancel.reason\": info.reason } : {}),\n },\n });\n}\n","/**\n * `TaskRegistry` — the singleton coordinating Task submit/list/get/cancel/\n * subscribe. Wraps the pluggable `TaskStore` (D364), the `AsyncSemaphore`\n * (D135 / D369) and a per-task `RingBuffer<TaskEvent>` (D372) for\n * late-attach replay.\n *\n * Edge cases absorbed:\n * - EC-3: work-fn invocation goes through `Promise.resolve().then(...)`\n * so synchronous throws become rejected promises.\n * - EC-4: pre-aborted signal short-circuits to `cancelled` without\n * acquiring a semaphore slot.\n * - EC-7: cross-process cancel via the `cancelRequested` flag on\n * `TaskHandle`. Registry polls at start + each progress event.\n * - EC-9: store-update failures are caught + logged; the event is\n * still emitted so subscribers always observe a terminal event.\n * - EC-10: subscribe iterator implements `return()` for leak-free\n * cleanup.\n * - EC-11: reentrant submit (work-fn calling `Task.submit`) uses an\n * ALS marker to bypass the semaphore queue, avoiding deadlock under\n * low concurrency caps.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport {\n isValidTaskId,\n type TaskCancelResult,\n type TaskEvent,\n type TaskFilter,\n type TaskHandle,\n type TaskKind,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type AsyncSemaphore, createSemaphore } from \"../runtime/concurrency/async-semaphore.js\";\nimport { RingBuffer } from \"./ring-buffer.js\";\nimport { getTaskStoreFor, InMemoryTaskStore, type TaskStore } from \"./store.js\";\nimport { buildSubscribe } from \"./subscribe.js\";\nimport { taskEventToRunEvent } from \"./task-run-event-bridge.js\";\nimport { startTaskCancelSpan, startTaskSubmitSpan, startTaskTransitionSpan } from \"./telemetry.js\";\n\nconst DEFAULT_CONCURRENCY = 8;\nconst DEFAULT_RETENTION_MS = 60 * 60 * 1000;\nconst EVICTION_INTERVAL_MS = 5 * 60 * 1000;\nconst RING_CAP = 64;\n\n/** EC-11 — ALS flag indicating we are inside a task work-fn. Reentrant submits bypass the semaphore. */\nconst reentryAls = new AsyncLocalStorage<boolean>();\n\nexport interface TaskRegistryOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\ntype WorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\ninterface InternalState {\n readonly store: TaskStore;\n readonly semaphore: AsyncSemaphore;\n readonly aborters: Map<string, AbortController>;\n readonly buffers: Map<string, RingBuffer<TaskEvent>>;\n readonly subscribers: Map<string, Set<(e: TaskEvent) => void>>;\n retentionMs: number;\n evictTimer?: NodeJS.Timeout;\n firstSubmitSeen: boolean;\n}\n\nfunction buildState(opts: TaskRegistryOptions): InternalState {\n const store = opts.store === undefined ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);\n return {\n store,\n semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),\n aborters: new Map(),\n buffers: new Map(),\n subscribers: new Map(),\n retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,\n firstSubmitSeen: false,\n };\n}\n\nlet state: InternalState = buildState({});\n\nexport function __resetTaskRegistryForTests(): void {\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState({});\n}\n\nexport function __getSubscribersCountForTests(taskId: string): number {\n return state.subscribers.get(taskId)?.size ?? 0;\n}\n\nexport function configure(opts: TaskRegistryOptions): void {\n if (state.firstSubmitSeen) {\n diag(\n \"[task] configure() ignored — registry already in use; reset via __resetTaskRegistryForTests()\\n\",\n );\n return;\n }\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState(opts);\n}\n\nfunction emitToSubscribers(taskId: string, event: TaskEvent): void {\n const buffer = state.buffers.get(taskId);\n if (buffer !== undefined) buffer.push(event);\n const subs = state.subscribers.get(taskId);\n if (subs === undefined) return;\n for (const cb of subs) {\n try {\n cb(event);\n } catch (err) {\n diag(`[task] subscriber threw: ${(err as Error).message}\\n`);\n }\n }\n}\n\nasync function safeUpdate(\n taskId: string,\n mutate: (h: TaskHandle) => TaskHandle,\n): Promise<TaskHandle | undefined> {\n try {\n return await state.store.update(taskId, mutate);\n } catch (err) {\n // EC-9: store failure should not swallow the event.\n diag(`[task] store.update failed for ${taskId}: ${(err as Error).message}\\n`);\n return undefined;\n }\n}\n\nfunction startEvictTimerIfNeeded(): void {\n if (state.evictTimer !== undefined) return;\n state.evictTimer = setInterval(() => {\n const cutoff = Date.now() - state.retentionMs;\n void state.store\n .evictTerminalOlderThan(cutoff)\n .then((count) => {\n if (count === 0) return;\n // Also drop buffers + subscribers for evicted tasks. We don't\n // know which ones were dropped — clean up any task whose store\n // entry is gone.\n for (const id of state.buffers.keys()) {\n void state.store.get(id).then((h) => {\n if (h === undefined) {\n state.buffers.delete(id);\n state.subscribers.delete(id);\n state.aborters.delete(id);\n }\n });\n }\n })\n .catch(() => {\n /* swallow timer errors */\n });\n }, EVICTION_INTERVAL_MS).unref();\n}\n\nfunction buildSubmittedEvent(handle: TaskHandle): TaskEvent {\n return {\n type: \"submitted\",\n taskId: handle.id,\n kind: handle.kind,\n submittedAt: handle.submittedAt,\n ...(handle.meta !== undefined ? { meta: handle.meta } : {}),\n };\n}\n\nasync function shortCircuitAborted(handle: TaskHandle, signal: AbortSignal): Promise<TaskHandle> {\n // EC-4: pre-aborted signal — skip queue/semaphore.\n const cancelled: TaskHandle = {\n ...handle,\n state: \"cancelled\",\n cancelledAt: Date.now(),\n };\n await state.store.insert(cancelled);\n state.buffers.set(handle.id, new RingBuffer(RING_CAP));\n emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));\n emitToSubscribers(handle.id, {\n type: \"cancelled\",\n taskId: handle.id,\n cancelledAt: cancelled.cancelledAt ?? Date.now(),\n reason: signal.reason instanceof Error ? signal.reason.message : \"pre-aborted\",\n });\n return cancelled;\n}\n\nasync function transition<T extends TaskState>(\n taskId: string,\n next: T,\n patch: Partial<TaskHandle>,\n): Promise<void> {\n const before = await state.store.get(taskId);\n const span = startTaskTransitionSpan({\n taskId,\n from: before?.state ?? \"unknown\",\n to: next,\n });\n try {\n await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));\n } finally {\n span.end();\n }\n}\n\ninterface SubmitInternal<T> {\n readonly kind: TaskKind;\n readonly work: WorkFn<T>;\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n readonly signal?: AbortSignal;\n /** When true (adapter-internal), the validator allows reserved prefixes. */\n readonly allowReservedPrefix?: boolean;\n /** SE2 — forward this task's lifecycle to the run-event sink as `task_*` RunEvents. */\n readonly onRunEvent?: import(\"../../types/run-events.js\").RunEventSink;\n}\n\nasync function buildAndInsertQueued(\n internal: SubmitInternal<unknown>,\n resolvedId: string,\n): Promise<TaskHandle> {\n const submittedAt = Date.now();\n const handle: TaskHandle = {\n id: resolvedId,\n kind: internal.kind,\n state: \"queued\",\n submittedAt,\n ...(internal.meta !== undefined ? { meta: internal.meta } : {}),\n };\n await state.store.insert(handle);\n state.buffers.set(resolvedId, new RingBuffer(RING_CAP));\n emitToSubscribers(resolvedId, buildSubmittedEvent(handle));\n return handle;\n}\n\nfunction resolveIdInternal(internal: SubmitInternal<unknown>): string {\n if (internal.id === undefined) return randomUUID();\n if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {\n throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);\n }\n return internal.id;\n}\n\nasync function runWorkAndFinalize<T>(\n taskId: string,\n aborter: AbortController,\n work: WorkFn<T>,\n): Promise<void> {\n const ctx: TaskWorkContext = {\n signal: aborter.signal,\n emit(payload) {\n // EC-7: check cancelRequested at every progress checkpoint.\n void checkCancelRequestedAt(taskId, aborter);\n emitToSubscribers(taskId, {\n type: \"progress\",\n taskId,\n at: Date.now(),\n payload,\n });\n },\n };\n\n try {\n const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const finishedAt = Date.now();\n await transition(taskId, \"finished\", { finishedAt, result });\n emitToSubscribers(taskId, { type: \"finished\", taskId, finishedAt, result });\n } catch (err) {\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const erroredAt = Date.now();\n const error =\n err instanceof Error\n ? { code: (err as { code?: string }).code ?? \"work_threw\", message: err.message }\n : { code: \"work_threw\", message: String(err) };\n await transition(taskId, \"error\", { erroredAt, error });\n emitToSubscribers(taskId, { type: \"errored\", taskId, erroredAt, error });\n }\n}\n\nasync function checkCancelRequestedAt(taskId: string, aborter: AbortController): Promise<void> {\n if (aborter.signal.aborted) return;\n try {\n const handle = await state.store.get(taskId);\n if (handle?.cancelRequested === true) {\n aborter.abort(\"cancelRequested\");\n }\n } catch {\n /* ignore — best-effort poll */\n }\n}\n\nasync function acquireSlot(): Promise<() => void> {\n if (reentryAls.getStore() === true) {\n // EC-11: reentrant submit bypasses the queue.\n return () => {\n /* no-op */\n };\n }\n return state.semaphore.acquire();\n}\n\n/**\n * Submit a task. Validates id (D368, EC-5 via allowReservedPrefix),\n * handles pre-aborted signals (EC-4), enforces single-flight by id\n * (D367), runs work under semaphore (D369/EC-11 reentrant bypass),\n * and produces the canonical event stream (D366).\n */\nexport async function submit<T>(internal: SubmitInternal<T>): Promise<TaskHandle> {\n state.firstSubmitSeen = true;\n startEvictTimerIfNeeded();\n\n const resolvedId = resolveIdInternal(internal);\n // SE2 — bridge the task lifecycle to the caller's run-event sink (opt-in).\n if (internal.onRunEvent !== undefined) {\n const sink = internal.onRunEvent;\n const kind = internal.kind;\n const subs = state.subscribers.get(resolvedId) ?? new Set();\n subs.add((e: TaskEvent) => {\n const runEvent = taskEventToRunEvent(e, resolvedId, kind);\n if (runEvent !== undefined) emitRunEvent(sink, runEvent);\n });\n state.subscribers.set(resolvedId, subs);\n }\n const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });\n\n // D367 single-flight.\n const existing = await state.store.get(resolvedId);\n if (existing !== undefined) {\n submitSpan.end();\n return existing;\n }\n\n const queuedHandle = await buildAndInsertQueued(internal, resolvedId);\n submitSpan.end();\n\n // EC-4: pre-aborted signal — short-circuit.\n if (internal.signal?.aborted === true) {\n return shortCircuitAborted(queuedHandle, internal.signal);\n }\n\n const aborter = new AbortController();\n state.aborters.set(resolvedId, aborter);\n if (internal.signal !== undefined) {\n internal.signal.addEventListener(\"abort\", () => aborter.abort(internal.signal?.reason), {\n once: true,\n });\n }\n\n // Fire and forget the actual run; the returned handle is the queued one.\n const release = await acquireSlot();\n void (async () => {\n try {\n // Check cancelRequested before starting (EC-7).\n await checkCancelRequestedAt(resolvedId, aborter);\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(resolvedId, \"cancelled\", { cancelledAt });\n emitToSubscribers(resolvedId, { type: \"cancelled\", taskId: resolvedId, cancelledAt });\n return;\n }\n const startedAt = Date.now();\n await transition(resolvedId, \"running\", { startedAt });\n emitToSubscribers(resolvedId, { type: \"started\", taskId: resolvedId, startedAt });\n await runWorkAndFinalize(resolvedId, aborter, internal.work as WorkFn<unknown>);\n } finally {\n release();\n state.aborters.delete(resolvedId);\n }\n })();\n\n return queuedHandle;\n}\n\nexport async function list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return state.store.list(filter);\n}\n\nexport async function get(id: string): Promise<TaskHandle | undefined> {\n if (!isValidTaskId(id, true)) return undefined;\n return state.store.get(id);\n}\n\nexport async function cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };\n const handle = await state.store.get(id);\n if (handle === undefined) return { cancelled: false, alreadyTerminal: false };\n if (handle.state === \"finished\" || handle.state === \"error\" || handle.state === \"cancelled\") {\n return { cancelled: false, alreadyTerminal: true };\n }\n const span = startTaskCancelSpan({\n taskId: id,\n ...(reason !== undefined ? { reason } : {}),\n via: \"api\",\n });\n try {\n return await cancelInternal(id, handle.state, reason);\n } finally {\n span.end();\n }\n}\n\nasync function cancelInternal(\n id: string,\n currentState: TaskState,\n reason?: string,\n): Promise<TaskCancelResult> {\n if (currentState === \"queued\") {\n const cancelledAt = Date.now();\n await transition(id, \"cancelled\", { cancelledAt });\n emitToSubscribers(id, {\n type: \"cancelled\",\n taskId: id,\n cancelledAt,\n ...(reason !== undefined ? { reason } : {}),\n });\n state.aborters.delete(id);\n return { cancelled: true, alreadyTerminal: false };\n }\n // running: trigger AbortController; runWorkAndFinalize handles the transition.\n const aborter = state.aborters.get(id);\n if (aborter !== undefined) aborter.abort(reason ?? \"cancelled\");\n return { cancelled: true, alreadyTerminal: false };\n}\n\nexport const subscribe = buildSubscribe({\n getBuffer: (id) => state.buffers.get(id),\n getOrCreateSubscriberSet: (id) => {\n let subs = state.subscribers.get(id);\n if (subs === undefined) {\n subs = new Set();\n state.subscribers.set(id, subs);\n }\n return subs;\n },\n removeSubscriber: (id, cb) => {\n const set = state.subscribers.get(id);\n set?.delete(cb);\n if (set !== undefined && set.size === 0) state.subscribers.delete(id);\n },\n});\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TheokitAgentError } from './chunk-
|
|
1
|
+
import { TheokitAgentError } from './chunk-IDCKSLYH.js';
|
|
2
2
|
|
|
3
3
|
// src/internal/judge/parse-verdict.ts
|
|
4
4
|
var DONE_PREFIX = "DONE:";
|
|
@@ -121,5 +121,5 @@ Be strict. If unclear, prefer CONTINUE.`;
|
|
|
121
121
|
}
|
|
122
122
|
|
|
123
123
|
export { JudgeCredentialError, composeJudgePrompt, judgeCallImpl };
|
|
124
|
-
//# sourceMappingURL=chunk-
|
|
125
|
-
//# sourceMappingURL=chunk-
|
|
124
|
+
//# sourceMappingURL=chunk-T73NA43R.js.map
|
|
125
|
+
//# sourceMappingURL=chunk-T73NA43R.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/judge/parse-verdict.ts","../src/internal/judge/judge-call.ts"],"names":[],"mappings":";;;AAaA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,e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EACF;AACF;AAOO,SAAS,mBAAmB,GAAA,EAA2B;AAC5D,EAAA,MAAM,QAAA,GACJ,GAAA,CAAI,QAAA,KAAa,MAAA,IAAa,GAAA,CAAI,QAAA,CAAS,MAAA,GAAS,CAAA,GAAI,GAAA,CAAI,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,GAAI,QAAA;AACpF,EAAA,OAAO,CAAA;;AAAA,MAAA,EAED,IAAI,IAAI;AAAA,UAAA,EACJ,QAAQ;AAAA,qBAAA,EACG,IAAI,YAAY;;AAAA;AAAA;AAAA;AAAA;;AAAA,uCAAA,CAAA;AAQvC","file":"chunk-LTSTGCL6.js","sourcesContent":["/**\n * Pure verdict parser (T2.1, ADRs D120-D121).\n *\n * Strict prefix matching against `DONE:`, `CONTINUE:`, `SKIPPED:`. Reason\n * is the suffix, trimmed. Anything else is fail-safe: verdict = `continue`,\n * `parseFailed: true` — caller's max-consecutive-failure cap stops the\n * loop after N flakes.\n *\n * @internal\n */\n\nimport type { JudgeResult } from \"../../types/goal-events.js\";\n\nconst DONE_PREFIX = \"DONE:\";\nconst CONTINUE_PREFIX = \"CONTINUE:\";\nconst SKIPPED_PREFIX = \"SKIPPED:\";\n/** M80 — the judge can now declare impossibility, not just \"continue\". */\nconst BLOCKED_PREFIX = \"BLOCKED:\";\n\nexport function parseVerdict(text: string): JudgeResult {\n const trimmed = text.trim();\n\n if (trimmed.startsWith(DONE_PREFIX)) {\n return {\n verdict: \"done\",\n reason: trimmed.slice(DONE_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(CONTINUE_PREFIX)) {\n return {\n verdict: \"continue\",\n reason: trimmed.slice(CONTINUE_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(BLOCKED_PREFIX)) {\n return {\n verdict: \"blocked\",\n reason: trimmed.slice(BLOCKED_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(SKIPPED_PREFIX)) {\n return {\n verdict: \"skipped\",\n reason: trimmed.slice(SKIPPED_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n\n // Fail-safe: ADR D121 — prefer \"continue\" so we don't stop prematurely.\n // The runUntil loop counts consecutive parseFailed responses and bails\n // after `maxConsecutiveJudgeFailures` (default 3).\n return {\n verdict: \"continue\",\n reason: `judge response malformed: \"${trimmed.slice(0, 100)}\"`,\n parseFailed: true,\n };\n}\n","import { TheokitAgentError } from \"../../errors.js\";\n/**\n * Judge call primitive (T2.2, ADRs D119-D121).\n *\n * Instantiates a short-lived auxiliary agent that evaluates whether a\n * goal is satisfied. The auxiliary judge runs with `tools: []` and a\n * cheap model (default `openai/gpt-4o-mini`) — see ADR D119. The judge\n * model needs only API access; we read `OPENROUTER_API_KEY` directly\n * from the environment (EC-A — single source of truth) and let the\n * caller override via {@link JudgeOptions.apiKey} for Anthropic or\n * direct-OpenAI environments.\n *\n * NOTE: judge aux agents created from inside a `forkAgent` context will\n * inherit the parent fork's whitelist via AsyncLocalStorage (EC-J).\n * `tools: []` keeps this benign today; future callers that add tools to\n * a judge should be aware.\n *\n * @internal\n */\n\nimport type { AgentOptions, SDKAgent } from \"../../types/agent.js\";\nimport type { JudgeResult } from \"../../types/goal-events.js\";\nimport { parseVerdict } from \"./parse-verdict.js\";\n\n/** Inputs to the judge — pure data. */\nexport interface JudgeContext {\n goal: string;\n lastResponse: string;\n subgoals?: string[];\n}\n\n/** Caller-supplied tuning knobs for the judge call. */\nexport interface JudgeOptions {\n /**\n * Judge model identifier. When absent, it DERIVES from {@link agentModel} — and only falls back to the literal\n * `\"openai/gpt-4o-mini\"` when neither is provided.\n *\n * M80 — the fixed default was provider-blind: it only resolves on OpenRouter. With an Anthropic key it gives\n * 404, with an OAuth bearer it gives 401, and in both the goal burned 3 whole turns before failing with\n * a misleading reason. The agent-builder already worked around this by deriving on its own; the knowledge\n * belongs here.\n */\n judgeModel?: string;\n /**\n * M80 — the DRIVEN agent's model. It is the basis of the derivation: a judge running on the same model as the\n * chat works wherever chat works.\n */\n agentModel?: string;\n /** Override env. Default `process.env.OPENROUTER_API_KEY` (EC-A). */\n apiKey?: string;\n}\n\n/**\n * M80 — the judge's credential or model does not work: 401/404.\n *\n * Fails FAST by design. `rules/error-handling.md` § 2 separates recoverable from unrecoverable, and a\n * nonexistent model does not start existing on retry — folding that into `{parseFailed: true}` made the loop\n * try three times and report \"failed\" on a consecutive-failure limit, hiding that the cause was the\n * credential. A slow, opaque failure traded for a fast, clear one.\n *\n * PARSE failures and network errors stay folded: they are recoverable, and the loop already decides on\n * in a row.\n */\nexport class JudgeCredentialError extends TheokitAgentError {\n override readonly name = \"JudgeCredentialError\";\n\n constructor(\n readonly httpStatus: number,\n readonly judgeModel: string,\n cause: unknown,\n ) {\n super(\n `judge unavailable: model \"${judgeModel}\" returned ${String(httpStatus)}. ` +\n \"Pass `judgeModel`/`apiKey` that resolve for this provider, or omit `judgeModel` to derive \" +\n \"it from the agent being driven.\",\n { code: \"judge_credential\", cause, isRetryable: false },\n );\n }\n}\n\n/** Extracts the HTTP status from a provider error, when it carries one. */\nfunction statusHttpDe(err: unknown): number | undefined {\n const s =\n (err as { status?: unknown; statusCode?: unknown }).status ??\n (err as { statusCode?: unknown }).statusCode;\n if (typeof s === \"number\") return s;\n const m = /\\b(401|403|404)\\b/.exec(err instanceof Error ? err.message : String(err));\n return m?.[1] !== undefined ? Number(m[1]) : undefined;\n}\n\n/** Dependencies injected so `judge-call.ts` stays free of `Agent` import. */\nexport interface JudgeDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n}\n\n/**\n * Run the judge auxiliary agent and parse the verdict. Always returns a\n * `JudgeResult` — failures are folded into `{ parseFailed: true,\n * verdict: \"continue\" }` so the loop can decide based on consecutive\n * failures (ADR D121).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: judge call must (1) check env or override, (2) catch errors as fail-safe, (3) ensure aux dispose runs once regardless of outcome — three concerns linearly arranged, harm clarity to extract.\nexport async function judgeCallImpl(\n ctx: JudgeContext,\n options: JudgeOptions | undefined,\n deps: JudgeDeps,\n): Promise<JudgeResult> {\n const prompt = composeJudgePrompt(ctx);\n // EC-A: single env source — OpenRouter only. No multi-provider fallback.\n const apiKey = options?.apiKey ?? process.env.OPENROUTER_API_KEY;\n if (apiKey === undefined) {\n return {\n verdict: \"continue\",\n reason:\n \"judge unavailable: OPENROUTER_API_KEY missing and no override passed via options.apiKey\",\n parseFailed: true,\n };\n }\n\n // M80 — precedence: explicit > driven agent's model > the historical literal. The literal only\n // survives as a last resort, so as not to break callers who never passed either.\n const judgeModel = options?.judgeModel ?? options?.agentModel ?? \"openai/gpt-4o-mini\";\n let auxAgent: SDKAgent | undefined;\n try {\n auxAgent = await deps.create({\n apiKey,\n model: { id: judgeModel },\n tools: [],\n local: {},\n metadata: { forkOrigin: \"judge\" },\n } as AgentOptions);\n const run = await auxAgent.send(prompt);\n const result = await run.wait();\n return parseVerdict(result.result ?? \"\");\n } catch (err) {\n // M80 — 401/403/404 are credential/model errors: unrecoverable, failing fast and typed. Everything\n // else (network, timeout, 5xx) stays folded, because it IS recoverable and the loop already decides on\n // in a row.\n const status = statusHttpDe(err);\n if (status === 401 || status === 403 || status === 404) {\n throw new JudgeCredentialError(status, judgeModel, err);\n }\n return {\n verdict: \"continue\",\n reason: `judge call failed: ${err instanceof Error ? err.message : String(err)}`,\n parseFailed: true,\n };\n } finally {\n if (auxAgent !== undefined) {\n try {\n await auxAgent.dispose();\n } catch {\n // dispose errors are non-fatal; judge result is already prepared\n }\n }\n }\n}\n\n/**\n * Build the strict-format prompt the judge expects.\n *\n * @internal\n */\nexport function composeJudgePrompt(ctx: JudgeContext): string {\n const subgoals =\n ctx.subgoals !== undefined && ctx.subgoals.length > 0 ? ctx.subgoals.join(\", \") : \"(none)\";\n return `You are a goal judge. Determine if this goal is satisfied.\n\nGoal: ${ctx.goal}\nSubgoals: ${subgoals}\nLast agent response: ${ctx.lastResponse}\n\nRespond with EXACTLY one of:\n- DONE: <reason>\n- CONTINUE: <what's left>\n- SKIPPED: <why not applicable>\n\nBe strict. If unclear, prefer CONTINUE.`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/judge/parse-verdict.ts","../src/internal/judge/judge-call.ts"],"names":[],"mappings":";;;AAaA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,eAAA,GAAkB,WAAA;AACxB,IAAM,cAAA,GAAiB,UAAA;AAEvB,IAAM,cAAA,GAAiB,UAAA;AAEhB,SAAS,aAAa,IAAA,EAA2B;AACtD,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAE1B,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,WAAW,CAAA,EAAG;AACnC,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,MAAA;AAAA,MACT,QAAQ,OAAA,CAAQ,KAAA,CAAM,WAAA,CAAY,MAAM,EAAE,IAAA,EAAK;AAAA,MAC/C,WAAA,EAAa;AAAA,KACf;AAAA,EACF;AACA,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,eAAe,CAAA,EAAG;AACvC,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,UAAA;AAAA,MACT,QAAQ,OAAA,CAAQ,KAAA,CAAM,eAAA,CAAgB,MAAM,EAAE,IAAA,EAAK;AAAA,MACnD,WAAA,EAAa;AAAA,KACf;AAAA,EACF;AACA,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,cAAc,CAAA,EAAG;AACtC,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,SAAA;AAAA,MACT,QAAQ,OAAA,CAAQ,KAAA,CAAM,cAAA,CAAe,MAAM,EAAE,IAAA,EAAK;AAAA,MAClD,WAAA,EAAa;AAAA,KACf;AAAA,EACF;AACA,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,cAAc,CAAA,EAAG;AACtC,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,SAAA;AAAA,MACT,QAAQ,OAAA,CAAQ,KAAA,CAAM,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AA,CAAA;AAAA,MAC9E,WAAA,EAAa;AAAA,KACf;AAAA,EACF,CAAA,SAAE;AACA,IAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,MAAA,IAAI;AACF,QAAA,MAAM,SAAS,OAAA,EAAQ;AAAA,MACzB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAOO,SAAS,mBAAmB,GAAA,EAA2B;AAC5D,EAAA,MAAM,QAAA,GACJ,GAAA,CAAI,QAAA,KAAa,MAAA,IAAa,GAAA,CAAI,QAAA,CAAS,MAAA,GAAS,CAAA,GAAI,GAAA,CAAI,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,GAAI,QAAA;AACpF,EAAA,OAAO,CAAA;;AAAA,MAAA,EAED,IAAI,IAAI;AAAA,UAAA,EACJ,QAAQ;AAAA,qBAAA,EACG,IAAI,YAAY;;AAAA;AAAA;AAAA;AAAA;;AAAA,uCAAA,CAAA;AAQvC","file":"chunk-T73NA43R.js","sourcesContent":["/**\n * Pure verdict parser (T2.1, ADRs D120-D121).\n *\n * Strict prefix matching against `DONE:`, `CONTINUE:`, `SKIPPED:`. Reason\n * is the suffix, trimmed. Anything else is fail-safe: verdict = `continue`,\n * `parseFailed: true` — caller's max-consecutive-failure cap stops the\n * loop after N flakes.\n *\n * @internal\n */\n\nimport type { JudgeResult } from \"../../types/goal-events.js\";\n\nconst DONE_PREFIX = \"DONE:\";\nconst CONTINUE_PREFIX = \"CONTINUE:\";\nconst SKIPPED_PREFIX = \"SKIPPED:\";\n/** M80 — the judge can now declare impossibility, not just \"continue\". */\nconst BLOCKED_PREFIX = \"BLOCKED:\";\n\nexport function parseVerdict(text: string): JudgeResult {\n const trimmed = text.trim();\n\n if (trimmed.startsWith(DONE_PREFIX)) {\n return {\n verdict: \"done\",\n reason: trimmed.slice(DONE_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(CONTINUE_PREFIX)) {\n return {\n verdict: \"continue\",\n reason: trimmed.slice(CONTINUE_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(BLOCKED_PREFIX)) {\n return {\n verdict: \"blocked\",\n reason: trimmed.slice(BLOCKED_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n if (trimmed.startsWith(SKIPPED_PREFIX)) {\n return {\n verdict: \"skipped\",\n reason: trimmed.slice(SKIPPED_PREFIX.length).trim(),\n parseFailed: false,\n };\n }\n\n // Fail-safe: ADR D121 — prefer \"continue\" so we don't stop prematurely.\n // The runUntil loop counts consecutive parseFailed responses and bails\n // after `maxConsecutiveJudgeFailures` (default 3).\n return {\n verdict: \"continue\",\n reason: `judge response malformed: \"${trimmed.slice(0, 100)}\"`,\n parseFailed: true,\n };\n}\n","import { TheokitAgentError } from \"../../errors.js\";\n/**\n * Judge call primitive (T2.2, ADRs D119-D121).\n *\n * Instantiates a short-lived auxiliary agent that evaluates whether a\n * goal is satisfied. The auxiliary judge runs with `tools: []` and a\n * cheap model (default `openai/gpt-4o-mini`) — see ADR D119. The judge\n * model needs only API access; we read `OPENROUTER_API_KEY` directly\n * from the environment (EC-A — single source of truth) and let the\n * caller override via {@link JudgeOptions.apiKey} for Anthropic or\n * direct-OpenAI environments.\n *\n * NOTE: judge aux agents created from inside a `forkAgent` context will\n * inherit the parent fork's whitelist via AsyncLocalStorage (EC-J).\n * `tools: []` keeps this benign today; future callers that add tools to\n * a judge should be aware.\n *\n * @internal\n */\n\nimport type { AgentOptions, SDKAgent } from \"../../types/agent.js\";\nimport type { JudgeResult } from \"../../types/goal-events.js\";\nimport { parseVerdict } from \"./parse-verdict.js\";\n\n/** Inputs to the judge — pure data. */\nexport interface JudgeContext {\n goal: string;\n lastResponse: string;\n subgoals?: string[];\n}\n\n/** Caller-supplied tuning knobs for the judge call. */\nexport interface JudgeOptions {\n /**\n * Judge model identifier. When absent, it DERIVES from {@link agentModel} — and only falls back to the literal\n * `\"openai/gpt-4o-mini\"` when neither is provided.\n *\n * M80 — the fixed default was provider-blind: it only resolves on OpenRouter. With an Anthropic key it gives\n * 404, with an OAuth bearer it gives 401, and in both the goal burned 3 whole turns before failing with\n * a misleading reason. The agent-builder already worked around this by deriving on its own; the knowledge\n * belongs here.\n */\n judgeModel?: string;\n /**\n * M80 — the DRIVEN agent's model. It is the basis of the derivation: a judge running on the same model as the\n * chat works wherever chat works.\n */\n agentModel?: string;\n /** Override env. Default `process.env.OPENROUTER_API_KEY` (EC-A). */\n apiKey?: string;\n}\n\n/**\n * M80 — the judge's credential or model does not work: 401/404.\n *\n * Fails FAST by design. `rules/error-handling.md` § 2 separates recoverable from unrecoverable, and a\n * nonexistent model does not start existing on retry — folding that into `{parseFailed: true}` made the loop\n * try three times and report \"failed\" on a consecutive-failure limit, hiding that the cause was the\n * credential. A slow, opaque failure traded for a fast, clear one.\n *\n * PARSE failures and network errors stay folded: they are recoverable, and the loop already decides on\n * in a row.\n */\nexport class JudgeCredentialError extends TheokitAgentError {\n override readonly name = \"JudgeCredentialError\";\n\n constructor(\n readonly httpStatus: number,\n readonly judgeModel: string,\n cause: unknown,\n ) {\n super(\n `judge unavailable: model \"${judgeModel}\" returned ${String(httpStatus)}. ` +\n \"Pass `judgeModel`/`apiKey` that resolve for this provider, or omit `judgeModel` to derive \" +\n \"it from the agent being driven.\",\n { code: \"judge_credential\", cause, isRetryable: false },\n );\n }\n}\n\n/** Extracts the HTTP status from a provider error, when it carries one. */\nfunction statusHttpDe(err: unknown): number | undefined {\n const s =\n (err as { status?: unknown; statusCode?: unknown }).status ??\n (err as { statusCode?: unknown }).statusCode;\n if (typeof s === \"number\") return s;\n const m = /\\b(401|403|404)\\b/.exec(err instanceof Error ? err.message : String(err));\n return m?.[1] !== undefined ? Number(m[1]) : undefined;\n}\n\n/** Dependencies injected so `judge-call.ts` stays free of `Agent` import. */\nexport interface JudgeDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n}\n\n/**\n * Run the judge auxiliary agent and parse the verdict. Always returns a\n * `JudgeResult` — failures are folded into `{ parseFailed: true,\n * verdict: \"continue\" }` so the loop can decide based on consecutive\n * failures (ADR D121).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: judge call must (1) check env or override, (2) catch errors as fail-safe, (3) ensure aux dispose runs once regardless of outcome — three concerns linearly arranged, harm clarity to extract.\nexport async function judgeCallImpl(\n ctx: JudgeContext,\n options: JudgeOptions | undefined,\n deps: JudgeDeps,\n): Promise<JudgeResult> {\n const prompt = composeJudgePrompt(ctx);\n // EC-A: single env source — OpenRouter only. No multi-provider fallback.\n const apiKey = options?.apiKey ?? process.env.OPENROUTER_API_KEY;\n if (apiKey === undefined) {\n return {\n verdict: \"continue\",\n reason:\n \"judge unavailable: OPENROUTER_API_KEY missing and no override passed via options.apiKey\",\n parseFailed: true,\n };\n }\n\n // M80 — precedence: explicit > driven agent's model > the historical literal. The literal only\n // survives as a last resort, so as not to break callers who never passed either.\n const judgeModel = options?.judgeModel ?? options?.agentModel ?? \"openai/gpt-4o-mini\";\n let auxAgent: SDKAgent | undefined;\n try {\n auxAgent = await deps.create({\n apiKey,\n model: { id: judgeModel },\n tools: [],\n local: {},\n metadata: { forkOrigin: \"judge\" },\n } as AgentOptions);\n const run = await auxAgent.send(prompt);\n const result = await run.wait();\n return parseVerdict(result.result ?? \"\");\n } catch (err) {\n // M80 — 401/403/404 are credential/model errors: unrecoverable, failing fast and typed. Everything\n // else (network, timeout, 5xx) stays folded, because it IS recoverable and the loop already decides on\n // in a row.\n const status = statusHttpDe(err);\n if (status === 401 || status === 403 || status === 404) {\n throw new JudgeCredentialError(status, judgeModel, err);\n }\n return {\n verdict: \"continue\",\n reason: `judge call failed: ${err instanceof Error ? err.message : String(err)}`,\n parseFailed: true,\n };\n } finally {\n if (auxAgent !== undefined) {\n try {\n await auxAgent.dispose();\n } catch {\n // dispose errors are non-fatal; judge result is already prepared\n }\n }\n }\n}\n\n/**\n * Build the strict-format prompt the judge expects.\n *\n * @internal\n */\nexport function composeJudgePrompt(ctx: JudgeContext): string {\n const subgoals =\n ctx.subgoals !== undefined && ctx.subgoals.length > 0 ? ctx.subgoals.join(\", \") : \"(none)\";\n return `You are a goal judge. Determine if this goal is satisfied.\n\nGoal: ${ctx.goal}\nSubgoals: ${subgoals}\nLast agent response: ${ctx.lastResponse}\n\nRespond with EXACTLY one of:\n- DONE: <reason>\n- CONTINUE: <what's left>\n- SKIPPED: <why not applicable>\n\nBe strict. If unclear, prefer CONTINUE.`;\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// src/internal/diagnostics.ts
|
|
2
|
+
var SINK_SLOT = /* @__PURE__ */ Symbol.for("theokit.sdk.diagnostics.sink.v1");
|
|
3
|
+
function currentSink() {
|
|
4
|
+
return globalThis[SINK_SLOT];
|
|
5
|
+
}
|
|
6
|
+
function setDiagnosticsSink(next) {
|
|
7
|
+
globalThis[SINK_SLOT] = next;
|
|
8
|
+
}
|
|
9
|
+
function diag(message) {
|
|
10
|
+
const sink = currentSink();
|
|
11
|
+
if (sink === void 0) return;
|
|
12
|
+
try {
|
|
13
|
+
sink(message);
|
|
14
|
+
} catch {
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export { diag, setDiagnosticsSink };
|
|
19
|
+
//# sourceMappingURL=chunk-T7O6K6PX.js.map
|
|
20
|
+
//# sourceMappingURL=chunk-T7O6K6PX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/diagnostics.ts"],"names":[],"mappings":";AAoEA,IAAM,SAAA,mBAAY,MAAA,CAAO,GAAA,CAAI,iCAAiC,CAAA;AAI9D,SAAS,WAAA,GAA2C;AAClD,EAAA,OAAQ,WAAqC,SAAS,CAAA;AACxD;AASO,SAAS,mBAAmB,IAAA,EAAyC;AAC1E,EAAC,UAAA,CAAqC,SAAS,CAAA,GAAI,IAAA;AACrD;AAQO,SAAS,KAAK,OAAA,EAAuB;AAG1C,EAAA,MAAM,OAAO,WAAA,EAAY;AACzB,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,OAAO,CAAA;AAAA,EACd,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-T7O6K6PX.js","sourcesContent":["/**\n * The library's single diagnostics channel — silent by default (#147).\n *\n * ## The problem\n *\n * The SDK wrote diagnostics straight to `process.stderr` from hot paths — 92 sites across 51\n * files under `internal/`. In a TUI host (Ink, alternate screen), those writes interleave with the\n * render and **corrupt the frame**. And the host had no way to intercept them: there was no\n * injectable logger. One consumer went as far as installing `proper-lockfile` just to silence ONE\n * of them.\n *\n * A library cannot assume `stdout`/`stderr` are free sinks. The application owns the terminal, not\n * the dependency.\n *\n * ## The contract\n *\n * - **`setDiagnosticsSink(fn)`** hands the messages to the application, which decides where to put\n * them (a status line, a file, a panel). It is what was missing for a TUI to coexist with the SDK.\n * - **With no sink, nothing is emitted.** A library does not own the host's terminal.\n *\n * ## Silent by default, and how 36 suites survived the flip\n *\n * The default WAS `stderr`, and 36 test files spy on `process.stderr.write` to assert a given\n * warning is emitted. That contract is real and had to survive; migrating all 36 by hand, across\n * four different spy styles, is how you weaken 36 suites in one commit.\n *\n * So the flip happened at the default, and `vitest.setup.ts` installs a sink that FORWARDS to\n * `stderr` for the duration of every test. Those assertions still test what they always tested —\n * \"this condition emits a diagnostic\" — through the channel a host would use, while production\n * emits nothing unless asked.\n *\n * The cost is stated rather than hidden: no test observes the production default by accident, so\n * `tests/diagnostics-public-entry.test.ts` pins it explicitly by clearing the sink first.\n *\n * ## Coverage is the whole guarantee\n *\n * The first sweep migrated the 92 sites under `internal/` and left `src/`'s own modules —\n * `event-bus.ts`, `batch.ts`, `compaction.ts`, `internal/workflow/step-branch.ts`. A host could\n * therefore install a sink and still have its frame corrupted by a batch run, which is the reported\n * defect with a smaller blast radius. Those are routed here too, and\n * `tests/lint/no-direct-terminal-write.test.ts` is what keeps the next hot path from\n * reintroducing one. \"Mostly interceptable\" is not interceptable.\n *\n * The remaining direct writers are allowlisted there with a reason, and every one of them is a seam\n * whose destination the CALLER already chooses (`opts.warn`, `opts.logger`, the Workflow logger).\n *\n * ## What this is NOT\n *\n * It is not a logger with levels, formatting or multiple destinations. It is the minimum that\n * resolves the reported blocker; a full logger here would be inventing a requirement nobody asked\n * for.\n */\n\n/** Receives each diagnostic message already formatted, with the trailing `\\n`. */\nexport type DiagnosticsSink = (message: string) => void;\n\n/**\n * The registry lives on `globalThis`, not in a module-level `let` (theokit#173).\n *\n * A module-level binding is a per-INSTANCE singleton, and a package manager will install two\n * physical copies of the same version whenever two dependents resolve different peer sets. Measured:\n * `@theokit/sdk@4.39.1` existed under two pnpm store hashes in the theokit workspace, so a sink\n * installed through `@theokit/agents` landed in a different registry than the emitter writes to.\n *\n * The failure mode is the quiet one — the re-export resolves, the function is callable, nothing\n * throws, and no diagnostic ever arrives. `Symbol.for` gives every copy in the process the same\n * slot; the `v1` suffix leaves room to change the shape without colliding with an older copy.\n */\nconst SINK_SLOT = Symbol.for(\"theokit.sdk.diagnostics.sink.v1\");\n\ntype SinkHolder = Record<symbol, DiagnosticsSink | undefined>;\n\nfunction currentSink(): DiagnosticsSink | undefined {\n return (globalThis as unknown as SinkHolder)[SINK_SLOT];\n}\n\n/**\n * Installs (or removes, by passing `undefined`) the diagnostics destination.\n *\n * When a sink is present it is the ONLY destination — `stderr` gets no copy. Duplicating\n * destinations would hand the problem back to the TUI that installed the sink precisely to get the\n * messages out of the terminal.\n */\nexport function setDiagnosticsSink(next: DiagnosticsSink | undefined): void {\n (globalThis as unknown as SinkHolder)[SINK_SLOT] = next;\n}\n\n/**\n * Emits a library diagnostic message.\n *\n * Replaces `process.stderr.write` on internal paths. Never throws: a faulty sink must not\n * must not take down the run it merely observes.\n */\nexport function diag(message: string): void {\n // Silent by default (#147): with no sink installed the message is dropped. A library must not\n // assume the host's stdout/stderr are free-form log sinks — in a TUI they are the render surface.\n const sink = currentSink();\n if (sink === undefined) return;\n try {\n sink(message);\n } catch {\n // Observability never breaks the run — same principle as `emitRunEvent`.\n }\n}\n\n/**\n * Emits a diagnostic that reports a USER-VISIBLE FAILURE, and is never silently dropped.\n *\n * `diag` is silent with no sink installed, and that is right for chatter: a library must not assume\n * the host's stderr is a free-form log, because in a TUI it is the render surface. A failure is a\n * different message. `theokit-sdk#189` is the record of the difference — an MCP server failed to\n * start, the only report went to `diag()`, the embedding UI never read it, and the user saw an\n * agent with missing tools and no reason given.\n *\n * The two failure modes are not symmetric, which is the whole decision: a corrupted frame is\n * visible and recoverable, while a silently dropped failure is neither. So this falls back to\n * stderr rather than to silence.\n *\n * A sink still takes precedence — the host installed it precisely to keep these off the terminal —\n * EXCEPT when the sink throws. A broken sink swallowing the one report of a failure is the same\n * defect one layer further in.\n *\n * @internal\n */\nexport function diagFailure(message: string): void {\n const sink = currentSink();\n if (sink !== undefined) {\n try {\n sink(message);\n return;\n } catch {\n // Fall through: the sink is broken, and this message is too important to drop with it.\n }\n }\n try {\n // `globalThis.process?.stderr` rather than a bare `process`: in a browser the bare form is a\n // ReferenceError that the catch below would swallow — working by accident, on an exception used\n // as ordinary control flow. Optional chaining states the intent: write to stderr where one\n // exists, stay silent where none does.\n globalThis.process?.stderr?.write(`${message}\\n`);\n } catch {\n // Nothing left to try. Observability never breaks the run.\n }\n}\n"]}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { diag } from './chunk-T7O6K6PX.js';
|
|
2
|
+
|
|
1
3
|
// src/internal/env.ts
|
|
2
4
|
var API_KEY_ENV_VAR = "THEOKIT_API_KEY";
|
|
3
5
|
function readEnv(name) {
|
|
@@ -14,23 +16,6 @@ function resolveApiKey(explicit) {
|
|
|
14
16
|
return void 0;
|
|
15
17
|
}
|
|
16
18
|
|
|
17
|
-
// src/internal/diagnostics.ts
|
|
18
|
-
var SINK_SLOT = /* @__PURE__ */ Symbol.for("theokit.sdk.diagnostics.sink.v1");
|
|
19
|
-
function currentSink() {
|
|
20
|
-
return globalThis[SINK_SLOT];
|
|
21
|
-
}
|
|
22
|
-
function setDiagnosticsSink(next) {
|
|
23
|
-
globalThis[SINK_SLOT] = next;
|
|
24
|
-
}
|
|
25
|
-
function diag(message) {
|
|
26
|
-
const sink = currentSink();
|
|
27
|
-
if (sink === void 0) return;
|
|
28
|
-
try {
|
|
29
|
-
sink(message);
|
|
30
|
-
} catch {
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
19
|
// src/internal/security/redact.ts
|
|
35
20
|
var REDACT_ENABLED = readEnvOnce();
|
|
36
21
|
function readEnvOnce() {
|
|
@@ -163,6 +148,6 @@ function redactSecrets(text, opts) {
|
|
|
163
148
|
return s;
|
|
164
149
|
}
|
|
165
150
|
|
|
166
|
-
export {
|
|
167
|
-
//# sourceMappingURL=chunk-
|
|
168
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
export { API_KEY_ENV_VAR, addPattern, maskToken, readEnv, redactSecrets, resolveApiKey };
|
|
152
|
+
//# sourceMappingURL=chunk-T7XEKOVW.js.map
|
|
153
|
+
//# sourceMappingURL=chunk-T7XEKOVW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/env.ts","../src/internal/security/redact.ts"],"names":[],"mappings":";;;AAKO,IAAM,eAAA,GAAkB;AAoBxB,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,OAAO,UAAA,CAAW,OAAA,EAAS,GAAA,GAAM,IAAI,CAAA;AACvC;AAYO,SAAS,cAAc,QAAA,EAAuC;AACnE,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,EAAG;AACjD,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,eAAe,CAAA;AACvC,EAAA,IAAI,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AAC/C,IAAA,OAAO,OAAA;AAAA,EACT;A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AAI,CAAC,gBAAgB,OAAO,OAAA;AAE5B,EAAA,IAAI,CAAA,GAAI,OAAA;AACR,EAAA,KAAA,MAAW,MAAM,gBAAA,EAAkB;AACjC,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,EAAA,EAAI,CAAC,CAAA,KAAM,SAAA,CAAU,CAAC,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,KAAA,MAAW,MAAM,cAAA,EAAgB;AAC/B,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,EAAA,EAAI,CAAC,CAAA,KAAM,SAAA,CAAU,CAAC,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,CAAC,MAAM,QAAA,EAAU;AAInB,IAAA,CAAA,GAAI,CAAA,CAAE,QAAQ,cAAA,EAAgB,CAAC,GAAG,MAAA,KAAmB,CAAA,EAAG,MAAM,CAAA,GAAA,CAAK,CAAA;AAInE,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,aAAA,EAAe,CAAC,KAAA,EAAO,QAAgB,KAAA,KAAkB;AAOrE,MAAA,IAAI,UAAA,CAAW,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AACnC,MAAA,OAAO,GAAG,MAAM,CAAA,GAAA,CAAA;AAAA,IAClB,CAAC,CAAA;AAAA,EACH;AACA,EAAA,OAAO,CAAA;AACT","file":"chunk-T7XEKOVW.js","sourcesContent":["/**\n * Environment variable used to provide the default API key.\n *\n * @internal\n */\nexport const API_KEY_ENV_VAR = \"THEOKIT_API_KEY\";\n\n/**\n * Read an environment variable without assuming `process` exists.\n *\n * Parts of this package legitimately reach a browser: `errors.ts` is imported by the client\n * bindings that framework consumers ship to the front end, and it in turn pulls in the redaction\n * and retry modules. `process` is a Node global — a bare `process.env` in any of them throws\n * `ReferenceError: process is not defined` while the module graph is still evaluating, before a\n * single component renders. The page goes blank with one console error that names no cause.\n *\n * `globalThis.process?.env?.[name]` degrades instead: on the server it reads the variable, and in\n * a browser it yields `undefined`, which every caller here already treats as \"not set\". Bundlers\n * that inline `process.env.X` at build time keep working, because they replace the expression\n * before it ever runs.\n *\n * This is the same pattern the sibling design system uses for `NODE_ENV`, for the same reason.\n *\n * @internal\n */\nexport function readEnv(name: string): string | undefined {\n return globalThis.process?.env?.[name];\n}\n\n/**\n * Resolve the API key with the documented precedence:\n *\n * 1. Explicit `apiKey` argument.\n * 2. The `THEOKIT_API_KEY` environment variable.\n *\n * Returns `undefined` when neither is set.\n *\n * @internal\n */\nexport function resolveApiKey(explicit?: string): string | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = readEnv(API_KEY_ENV_VAR);\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return undefined;\n}\n","import { diag } from \"../diagnostics.js\";\nimport { readEnv } from \"../env.js\";\n\n/**\n * Canonical secret redaction module (ADRs D68-D73).\n *\n * Single source of truth for credential pattern masking across the SDK.\n * Wired at output boundaries: `ErrorMetadata.raw` (mappers/shared.ts),\n * telemetry span attributes (telemetry/tracer.ts), transcript JSONL\n * appends (agent-session-store.ts), migration logger output\n * (memory/migrate-sqlite-to-lance.ts).\n *\n * - D68: central module, single source of truth (replaces 2 duplicates)\n * - D69: env snapshot at module init (prompt-injection defense)\n * - D70: ON by default, warn on opt-out\n * - D71: two-bucket masking — short fully masked, long preserves prefix+suffix\n * - D72: `codeFile` opt-out for legitimate prefix-shaped content\n * - D73: redact at OUTPUT boundaries, not at storage\n *\n * @internal\n */\n\n// D69: env snapshot captured at module load. Subsequent mutations of\n// process.env.THEOKIT_REDACT_SECRETS are ignored — defends against\n// prompt injection that tries to disable redaction mid-run.\nlet REDACT_ENABLED: boolean = readEnvOnce();\n\nfunction readEnvOnce(): boolean {\n // `readEnv` rather than `process.env`: this module reaches the browser through `errors.ts`, and\n // a bare `process` there is a ReferenceError at module scope — a blank page, not a warning.\n const raw = readEnv(\"THEOKIT_REDACT_SECRETS\");\n if (raw === undefined) return true; // D70: default ON\n return [\"1\", \"true\", \"yes\", \"on\"].includes(raw.toLowerCase());\n}\n\n// D70: warn once on opt-out so the user knows they're vulnerable.\nlet warnedOptOut = false;\nif (!REDACT_ENABLED && !warnedOptOut) {\n diag(\n \"[theokit-sdk] Secret redaction is DISABLED via THEOKIT_REDACT_SECRETS. \" +\n \"Credentials may leak into errors, telemetry, logs, transcripts.\\n\",\n );\n warnedOptOut = true;\n}\n\n/**\n * Built-in credential patterns. Order matters — more specific prefixes\n * must come before generic ones (e.g., `sk-ant-` before `sk-`). Quantifiers\n * are all bounded `{n,m}` or applied to char classes — linear time, no ReDoS.\n *\n * @internal\n */\nconst BUILTIN_PATTERNS: readonly RegExp[] = [\n // T5.4: 30+ vendor prefixes (was 12 pre-T5.4). Order matters — more\n // specific prefixes precede generic ones (e.g., sk-ant-admin01 before\n // sk-ant-, sk-proj- before sk-). PEM block deliberately first so its\n // multi-line span runs before any per-line patterns can fire.\n /-----BEGIN[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----[\\s\\S]+?-----END[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----/g,\n // JWT — exact 3-segment base64url. Dotted; the body floor of 4 chars per\n // segment matches the minimum legal payload while skipping `a.b.c` noise.\n /eyJ[A-Za-z0-9_-]{4,}\\.eyJ[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]{4,}/g,\n // Azure Storage SAS — match the sig= component (URL-encoded base64).\n /(?<=[?&]sig=)[A-Za-z0-9%+/]{20,}/g,\n // Anthropic\n /sk-ant-admin01-[A-Za-z0-9_-]{10,}/g, // Anthropic admin keys (must precede sk-ant-)\n /sk-ant-[A-Za-z0-9_-]{10,}/g, // Anthropic regular\n // OpenAI family + clones (sk- generic must come AFTER all sk-foo- variants)\n /sk-proj-[A-Za-z0-9_-]{10,}/g, // OpenAI project key (must precede sk- generic)\n /sk-[A-Za-z0-9_-]{10,}/g, // OpenAI / OpenRouter / DeepInfra / Together / DeepSeek\n // Provider prefixes (alphabetized for maintainability)\n /AIza[A-Za-z0-9_-]{35}/g, // Google API key\n /AKIA[A-Z0-9]{16}/g, // AWS access key\n /fw_[A-Za-z0-9]{20,}/g, // Fireworks\n /glpat-[A-Za-z0-9_-]{20}/g, // GitLab PAT\n /ghp_[A-Za-z0-9]{36}/g, // GitHub PAT classic\n /github_pat_[A-Za-z0-9_]{82}/g, // GitHub PAT fine-grained\n /gsk_[A-Za-z0-9]{20,}/g, // Groq\n /hf_[A-Za-z0-9]{20,}/g, // HuggingFace\n /\\bpa-[A-Za-z0-9_-]{20,}/g, // Voyage AI (word-boundary to skip CSS / kebab IDs)\n /pcsk_[A-Za-z0-9_-]{20,}/g, // Pinecone\n /pplx-[A-Za-z0-9_-]{20,}/g, // Perplexity\n /r8_[A-Za-z0-9_-]{20,}/g, // Replicate\n /rk_live_[A-Za-z0-9]{20,}/g, // Stripe restricted\n /sk_live_[A-Za-z0-9]{20,}/g, // Stripe secret\n /sntrys_[A-Za-z0-9]{40,}/g, // Sentry user auth\n /xai-[A-Za-z0-9_-]{20,}/g, // xAI (Grok)\n /xox[bpasr]-[A-Za-z0-9-]{10,}/g, //Slack tokens\n // Additional unique-prefix tokens with low false-positive risk\n /npm_[A-Za-z0-9]{36}/g, // npm access token\n /SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}/g, // SendGrid\n /\\bSK[A-Za-z0-9]{32}\\b/g, // Twilio API SID (word-boundary to skip CSS class noise)\n /\\bkey-[a-f0-9]{32}\\b/g, // Mailgun (hex-only narrows false positives)\n /MT[A-Za-z0-9_-]{23}\\.[A-Za-z0-9_-]{6}\\.[A-Za-z0-9_-]{27}/g, // Discord bot\n /\\b(?:sdk|mob)-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\b/g, // LaunchDarkly\n];\n\n// `Bearer <token>` matched as its own first-class pattern so PARAM_PATTERN\n// doesn't have to handle the unusual `Authorization: Bearer xxx` shape\n// (no `:` or `=` between \"Bearer\" and the value — bare whitespace).\nconst BEARER_PATTERN = /\\b(Bearer\\s+)([A-Za-z0-9_\\-.+/=]{8,})/g;\n\n// Parametric: matches `key=value` and `key: value` (with optional quote\n// between the key and the separator, to handle JSON: `\"api_key\": \"...\"`)\n// in URLs, query strings, JSON-like bodies, HTTP headers. Captures the\n// prefix so we keep it visible while masking the value.\n//\n// `authorization` deliberately excluded — BEARER_PATTERN handles the\n// common `Authorization: Bearer xxx` shape. Including it here causes\n// double-masking (\"Authorization: *** ***\") after Bearer fires.\n// T5.4: keyword set expanded from 6 → 16 to cover the OAuth / JWT / generic\n// credential vocabulary surfaced by DR6 finding #4. `authorization`,\n// `auth`, `bearer` stay excluded — BEARER_PATTERN handles the\n// `Authorization: Bearer xxx` shape and including these here would\n// re-catch the post-BUILTIN-masked form (D71 prefix-preservation\n// contract) and double-mask to `***`.\n//\n// Value class includes `.` so JWT / `.env` / dotted base64url values\n// match; the callback skips already-masked values (containing the\n// `...` D71 separator) to preserve the BUILTIN prefix-mask result.\nconst PARAM_PATTERN =\n /(\\b(?:access_token|api_key|api-key|client_secret|credential|credentials|id_token|jwt|password|private_key|refresh_token|secret|service_account|session_token|token|x-api-key)\\b[\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_\\-.+/]+)/gi;\n\nconst _extraPatterns: RegExp[] = [];\n\n/**\n * Register an extra pattern for `redactSecrets` to mask, on top of the built-in vendor set.\n *\n * Additive and irreversible for the life of the process: patterns accumulate in module scope,\n * builtins are never replaced or reordered, and there is no way to remove one. Registering the\n * same regex twice registers it twice.\n *\n * Throws immediately when the regex has no `/g` flag. That is not pedantry — `String.replace`\n * with a non-global regex substitutes only the FIRST match, so a pattern registered without it\n * would mask the first credential in a payload and let every later one through, which reads as\n * working.\n *\n * Extras run after the builtins and before the parametric `key=value` sweep, and each whole match\n * is replaced by `maskToken` of that match. Anchor and bound the pattern with care: a regex that\n * matches more than the secret masks more than the secret, and one that backtracks badly runs on\n * every string crossing an output boundary.\n *\n * Registering a pattern does not enable redaction. When `THEOKIT_REDACT_SECRETS` was off at\n * module load, `redactSecrets` returns its input untouched and extras never run.\n *\n * Also exposed publicly, and under semver, as `Security.addPattern` in `src/security.ts`; the\n * direct export here additionally reaches the semver-exempt `@theokit/sdk/internal/security`\n * sub-path.\n */\nexport function addPattern(re: RegExp): void {\n if (!re.global) {\n throw new Error(\"Security.addPattern: regex must have /g flag for replace-all semantics\");\n }\n _extraPatterns.push(re);\n}\n\n/**\n * Mask one string, keeping enough of it to be recognizable in a log.\n *\n * Under 18 characters the whole string becomes the literal `***`; the length is not preserved and\n * nothing of the input survives. From 18 characters up, the result is the first 6 characters, the\n * literal `...`, and the last 4 — so exactly 10 characters of the input are RETAINED IN CLEAR and\n * the middle is dropped. That is the trade the threshold encodes: short strings could be brute\n * forced from a partial, long ones cannot, and the surviving prefix is usually the vendor tag\n * (`sk-ant`, `ghp_de`) that tells an operator which credential misbehaved.\n *\n * Be clear about what this is and is not. It is a readability aid for logs, not an anonymizer and\n * not a security boundary. The retained prefix and suffix identify the credential's issuer and\n * often the credential itself to anyone who has seen it before, so a masked value still belongs in\n * a trusted log and not in a bug report or a support ticket.\n *\n * It masks whatever it is handed. There is no check that the argument is a secret, so calling it\n * on ordinary text mangles the text, and calling it on something the caller merely hopes is a\n * secret proves nothing about what leaked.\n *\n * `redactSecrets` applies it to the ENTIRE match of a pattern, not to a captured group. For a\n * match like `Bearer sk-ant-...` the first 6 characters retained are `Bearer`, not the key's\n * prefix.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/security` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function maskToken(token: string): string {\n if (token.length < 18) return \"***\";\n return `${token.slice(0, 6)}...${token.slice(-4)}`;\n}\n\n// issue #117 — the EXACT shape of a `maskToken` output (`slice(0,6)+\"...\"+slice(-4)`\n// = 6 chars, literal `...`, 4 chars). Used to detect a value PARAM_PATTERN would\n// otherwise re-mask, WITHOUT skipping a raw secret that merely contains `...`.\nconst MASK_SHAPE = /^.{6}\\.\\.\\..{4}$/s;\n\n// Coerce arbitrary input to a string for redaction. Returns `null`\n// sentinel when the value is null/undefined/non-stringifiable, so the\n// caller can short-circuit with `\"\"`. EC-7 fix: circular refs go through\n// the try/catch and produce the sentinel marker, never throwing.\nfunction coerceToString(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n if (typeof value === \"object\") {\n try {\n const s = JSON.stringify(value);\n return s === undefined ? null : s;\n } catch {\n return \"[unredactable: circular]\";\n }\n }\n return String(value);\n}\n\n/**\n * Redact known credential patterns from `text`. Default behavior masks\n * builtins + extras + parametric `key=value` sinks.\n *\n * With `{ codeFile: true }` (D72), skips PARAM_PATTERN to avoid mangling\n * `.env.example`, schema JSON, or test fixtures that legitimately contain\n * prefix-like strings.\n *\n * Returns the redacted string. Coerces non-strings via JSON.stringify;\n * EC-7 fix (edge-case review): wraps in try/catch so circular references\n * never propagate — returns sentinel `\"[unredactable: circular]\"`.\n *\n * `null` and `undefined` return `\"\"`. When redaction was switched off at module load via\n * `THEOKIT_REDACT_SECRETS`, the coerced input is returned with no masking at all — the value is\n * still stringified, but nothing is removed from it.\n *\n * Masking is best-effort against a list of known shapes. A credential in a format no pattern\n * covers passes through unchanged, so a redacted string is not a string proven free of secrets.\n */\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n const coerced = coerceToString(text);\n if (coerced === null) return \"\";\n if (!REDACT_ENABLED) return coerced;\n\n let s = coerced;\n for (const re of BUILTIN_PATTERNS) {\n s = s.replace(re, (m) => maskToken(m));\n }\n for (const re of _extraPatterns) {\n s = s.replace(re, (m) => maskToken(m));\n }\n if (!opts?.codeFile) {\n // Bearer first (preserves \"Bearer \" prefix, masks the token after).\n // Must run before PARAM_PATTERN so the bare-whitespace shape doesn't\n // get mis-handled as a value.\n s = s.replace(BEARER_PATTERN, (_, prefix: string) => `${prefix}***`);\n // T5.4: skip if value already contains the D71 bucket-mask separator\n // (`...`) — BUILTIN ran first and produced a prefix-preserved mask;\n // re-masking would lose the prefix and degrade debuggability.\n s = s.replace(PARAM_PATTERN, (whole, prefix: string, value: string) => {\n // issue #117 — skip ONLY when the value is already a mask that a BUILTIN\n // pattern produced (maskToken's exact `6chars...4chars` shape), so we don't\n // re-mask and lose the prefix. The old `value.includes(\"...\")` was too broad:\n // a REAL secret that happens to contain `...` (e.g. `L_-cxw-.2UI_..._`) was\n // skipped and LEAKED. The mask shape is exact (maskToken: slice(0,6)+\"...\"+\n // slice(-4)), so a raw secret with `...` elsewhere is now masked.\n if (MASK_SHAPE.test(value)) return whole;\n return `${prefix}***`;\n });\n }\n return s;\n}\n\n/**\n * Test-only helper exported for `_test-reset.ts`. NOT included in the\n * `index.ts` barrel — vitest setup imports the dedicated module via\n * explicit path to discourage production callers.\n *\n * @internal\n */\nexport function _resetForTests(opts: { enabled?: boolean; clearExtras?: boolean }): void {\n if (opts.enabled !== undefined) REDACT_ENABLED = opts.enabled;\n if (opts.clearExtras === true) _extraPatterns.length = 0;\n}\n\n/**\n * T5.4 — Test-only count of BUILTIN_PATTERNS. Exposed so the count-floor\n * assertion can run without re-deriving the array shape in test land.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__BUILTIN_PATTERN_COUNT(): number {\n return BUILTIN_PATTERNS.length;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkI6TGFUCO_cjs = require('./chunk-I6TGFUCO.cjs');
|
|
4
|
+
var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
|
|
5
5
|
var promises = require('fs/promises');
|
|
6
6
|
var os = require('os');
|
|
7
7
|
var path = require('path');
|
|
@@ -46,10 +46,10 @@ async function readVersionedJson(opts) {
|
|
|
46
46
|
const asidePath = `${path}.corrupt.${Date.now()}`;
|
|
47
47
|
try {
|
|
48
48
|
await promises.rename(path, asidePath);
|
|
49
|
-
|
|
49
|
+
chunkNUKRL3I6_cjs.diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.
|
|
50
50
|
`);
|
|
51
51
|
} catch {
|
|
52
|
-
|
|
52
|
+
chunkNUKRL3I6_cjs.diag(`[theokit-sdk] ${path} is corrupt; using default value.
|
|
53
53
|
`);
|
|
54
54
|
}
|
|
55
55
|
return defaultValue();
|
|
@@ -64,7 +64,7 @@ async function readVersionedJson(opts) {
|
|
|
64
64
|
return file.data;
|
|
65
65
|
}
|
|
66
66
|
if (stored > currentVersion) {
|
|
67
|
-
|
|
67
|
+
chunkNUKRL3I6_cjs.diag(
|
|
68
68
|
`[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; using default value (forward-only).
|
|
69
69
|
`
|
|
70
70
|
);
|
|
@@ -77,7 +77,7 @@ async function writeVersionedJson(path, data, currentVersion) {
|
|
|
77
77
|
_schemaVersion: currentVersion,
|
|
78
78
|
data
|
|
79
79
|
};
|
|
80
|
-
await
|
|
80
|
+
await chunkI6TGFUCO_cjs.atomicWriteJson(path, file);
|
|
81
81
|
}
|
|
82
82
|
var THEOKIT_DIR_NAME = ".theokit";
|
|
83
83
|
function getTheokitHome(cwd) {
|
|
@@ -106,5 +106,5 @@ exports.getTheokitHome = getTheokitHome;
|
|
|
106
106
|
exports.migrateSchema = migrateSchema;
|
|
107
107
|
exports.readVersionedJson = readVersionedJson;
|
|
108
108
|
exports.writeVersionedJson = writeVersionedJson;
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
110
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-U2AC6JUP.cjs.map
|
|
110
|
+
//# sourceMappingURL=chunk-U2AC6JUP.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/schema-version.ts","../src/internal/persistence/paths.ts"],"names":["readFile","rename","diag","atomicWriteJson","join","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AO,CAAA,CAAA,EAAI,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,MAAM,CAAC,CAAA,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-U2AC6JUP.cjs","sourcesContent":["/**\n * Schema versioning helpers (ADR D62).\n *\n * Two parallel APIs:\n * - `migrateSchema` — SQLite via `PRAGMA user_version` + ordered forward-only migrations.\n * - `readVersionedJson` / `writeVersionedJson` — JSON files with `_schemaVersion` field.\n *\n * Forward-only: never deletes data, never downgrades. Migration callbacks\n * own the transformation; this module owns the bookkeeping.\n *\n * @internal\n */\n\nimport { readFile, rename } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"./atomic-write.js\";\n\n// ────────────────────── SQLite migrations ──────────────────────\n\n/**\n * The three `better-sqlite3` methods this module actually uses, declared structurally so nothing\n * here imports the driver.\n *\n * A real `better-sqlite3` `Database` satisfies it. `pragma` is called both to read\n * (`pragma(\"user_version\", { simple: true })`, which must return the number itself rather than a\n * row array) and to write (`pragma(\"user_version = N\")`). `transaction` must return a function\n * that, when called, runs the wrapped body inside a real SQLite transaction and rolls it back if\n * the body throws — a stub that merely calls through gives `migrateSchema` no atomicity, and a\n * half-applied migration is exactly what it exists to prevent.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface SqliteLike {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n exec: (sql: string) => void;\n transaction: <Args extends unknown[], R>(fn: (...args: Args) => R) => (...args: Args) => R;\n}\n\n/**\n * One forward migration step.\n *\n * `up` runs inside the shared transaction and must be self-contained: it may not commit, and any\n * error it throws aborts the whole run and rolls back every step in it, including the ones that\n * already succeeded. `user_version` is set to `toVersion` immediately after `up` returns, inside\n * the same transaction, so version and schema move together or not at all.\n *\n * `toVersion` is the version the database reaches, not the one it starts from. Steps are ordered\n * by it, gaps are allowed, and two steps sharing a `toVersion` both run — nothing deduplicates\n * them.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface Migration {\n toVersion: number;\n up: (db: SqliteLike) => void;\n}\n\n/**\n * Arguments to `migrateSchema`.\n *\n * `currentVersion` is the version the code expects, and it is the ceiling: a migration whose\n * `toVersion` exceeds it is left unapplied for a later release. `migrations` may be given in any\n * order and may contain steps already applied — both are filtered and sorted here. `label` only\n * ever appears in the downgrade error message.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaOptions {\n db: SqliteLike;\n currentVersion: number;\n migrations: ReadonlyArray<Migration>;\n /** For log/error context (e.g., \"memory-index\", \"registry\"). */\n label?: string;\n}\n\n/**\n * What `migrateSchema` did.\n *\n * `from` is the `user_version` found on the database, `to` is the version it holds afterwards,\n * and `ran` is how many steps executed. When nothing was pending, `to === from` and `ran === 0`.\n *\n * `to` is the `toVersion` of the last step applied, NOT `currentVersion`. A database at version 3\n * against `currentVersion: 5` with no migration in that range comes back as\n * `{ from: 3, to: 3, ran: 0 }` — the gap is reported, not closed. Comparing `to` with\n * `currentVersion` is how a caller notices that the migration list is missing a step.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaResult {\n from: number;\n to: number;\n ran: number;\n}\n\n/**\n * Bring a SQLite database's `user_version` up to `currentVersion` by running the steps that sit\n * between the two.\n *\n * Steps are sorted ascending by `toVersion` and filtered to `> stored && <= currentVersion`, then\n * run in that order inside ONE transaction: each `up` is followed immediately by the matching\n * `user_version` write. Either every step in the run commits or none does — a step that throws\n * aborts the transaction, propagates the error, and leaves the database at the version it started\n * from. There is no partially-migrated state and no resume point.\n *\n * Forward-only. When the stored version is greater than `currentVersion` — an older build opening\n * a database a newer one already migrated — this throws immediately, before touching anything,\n * with a message naming both versions and `label`. Nothing downgrades, and no data is deleted on\n * any path here; what a step does is the step's own business.\n *\n * A stored version equal to `currentVersion` returns without opening a transaction. A `user_version`\n * that is absent or not a number is read as 0, so a fresh database runs every step.\n *\n * Concurrency: the SQLite transaction is the only serialization. This takes no file lock, so two\n * processes migrating the same file at once are arbitrated by SQLite's own write lock — the loser\n * gets a busy or locked error from the driver, not a queued turn. Wrap the call in `withFileLock`\n * if that matters.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function migrateSchema(opts: MigrateSchemaOptions): MigrateSchemaResult {\n const { db, currentVersion, migrations, label = \"db\" } = opts;\n const storedRaw = db.pragma(\"user_version\", { simple: true });\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored > currentVersion) {\n throw new Error(\n `[${label}] schema version ${stored} > current ${currentVersion}; ` +\n \"did you downgrade the SDK? Forward-only migrations only.\",\n );\n }\n\n if (stored === currentVersion) {\n return { from: stored, to: stored, ran: 0 };\n }\n\n const pending = [...migrations]\n .sort((a, b) => a.toVersion - b.toVersion)\n .filter((m) => m.toVersion > stored && m.toVersion <= currentVersion);\n\n let ran = 0;\n let lastApplied = stored;\n\n db.transaction(() => {\n for (const m of pending) {\n m.up(db);\n db.pragma(`user_version = ${m.toVersion}`);\n lastApplied = m.toVersion;\n ran += 1;\n }\n })();\n\n return { from: stored, to: lastApplied, ran };\n}\n\n// ────────────────────── JSON versioned files ──────────────────────\n\n/**\n * The on-disk envelope: the payload under `data`, its schema version alongside it.\n *\n * `writeVersionedJson` always produces this shape. `readVersionedJson` reads it, but tolerates a\n * file that is not in it — a legacy object with no `_schemaVersion` is treated as version 0 and\n * handed to the migrate callback whole, so this type describes what is written, not everything\n * that can be read.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface VersionedJsonFile<T> {\n _schemaVersion: number;\n data: T;\n}\n\n/**\n * Upgrade callback for `readVersionedJson`, invoked only when the stored version is BELOW the\n * current one.\n *\n * `parsed` is the whole parsed JSON value, not `parsed.data`. That is deliberate: a legacy file\n * predating the envelope has its fields at the top level, and a callback handed only `.data`\n * would receive `undefined` for exactly the files that need migrating. It is typed `unknown`\n * because nothing has validated it — narrow before reading.\n *\n * `fromVersion` is the `_schemaVersion` found on disk, or 0 when the field is missing or not a\n * number.\n *\n * The return value is used as-is and is NOT written back; the file on disk still holds the old\n * shape until someone calls `writeVersionedJson`. Throwing here propagates out of\n * `readVersionedJson`, which otherwise never throws — return the default value instead if an\n * unmigratable file should be survivable.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport type VersionedJsonMigrate<T> = (parsed: unknown, fromVersion: number) => T;\n\n/**\n * Arguments to `readVersionedJson`.\n *\n * `defaultValue` is a factory rather than a value because it is called on several paths and each\n * caller must get its own object — returning a shared mutable default would let one caller's\n * edits appear in another's. It is called for a missing file, an unreadable one, a corrupt one,\n * a non-object payload, and a file written by a newer version.\n *\n * `migrate` is called only for a stored version strictly below `currentVersion`.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface ReadVersionedJsonOptions<T> {\n path: string;\n currentVersion: number;\n migrate: VersionedJsonMigrate<T>;\n defaultValue: () => T;\n}\n\n/**\n * Read a versioned JSON file, migrating or falling back rather than failing.\n *\n * What comes back, by case:\n *\n * - version matches `currentVersion` — the file's `data` field, returned as `T` WITHOUT\n * validation. A file whose envelope is right but whose payload is not gets through.\n * - version below `currentVersion` — whatever `migrate(parsed, stored)` returns. The migrated\n * value is not persisted; the file is untouched.\n * - version above `currentVersion` — `defaultValue()`, plus a warning. Forward-only: a file\n * written by a newer build is left alone rather than downgraded.\n * - file missing, or unreadable for any other reason (permissions, a directory in its place) —\n * `defaultValue()`, silently. Absence and denial are not distinguished.\n * - file present but not valid JSON — `defaultValue()`, and the file is RENAMED to\n * `<path>.corrupt.<epoch-ms>` so the next run starts clean and the bad bytes stay available.\n * A rename that itself fails is warned about and the read still returns the default, which\n * means the same corrupt file will be met again next time.\n * - JSON that parses to a non-object (a number, a string, `null`) — `defaultValue()`, silently\n * and without moving the file aside.\n *\n * The only ways this throws are through the callbacks you supply: `migrate` or `defaultValue`\n * raising. Nothing else here rejects.\n *\n * There is no locking. A concurrent `writeVersionedJson` on the same path is atomic at the rename,\n * so a reader sees either the old file or the new one, never a half-written one — but a\n * read-modify-write built from this pair is NOT atomic across the two calls, and needs\n * `withFileLock` around both.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function readVersionedJson<T>(opts: ReadVersionedJsonOptions<T>): Promise<T> {\n const { path, currentVersion, migrate, defaultValue } = opts;\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf-8\");\n } catch {\n return defaultValue();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // T5.10 — move corrupt file aside so (a) user can investigate and\n // (b) next run starts fresh instead of hitting the same warning loop.\n const asidePath = `${path}.corrupt.${Date.now()}`;\n try {\n await rename(path, asidePath);\n diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.\\n`);\n } catch {\n diag(`[theokit-sdk] ${path} is corrupt; using default value.\\n`);\n }\n return defaultValue();\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return defaultValue();\n }\n\n const file = parsed as { _schemaVersion?: unknown; data?: unknown };\n const storedRaw = file._schemaVersion;\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored === currentVersion) {\n return file.data as T;\n }\n\n if (stored > currentVersion) {\n diag(\n `[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; ` +\n \"using default value (forward-only).\\n\",\n );\n return defaultValue();\n }\n\n // EC-2 fix: pass the FULL parsed object to migrate, not just `file.data`.\n // Legacy shapes (e.g., `{ schemaVersion: \"1.0\", agents: {...} }` without\n // a `data` field) need to inspect the whole thing.\n return migrate(parsed, stored);\n}\n\n/**\n * Write `data` wrapped in the version envelope, replacing the file atomically.\n *\n * The bytes go to a temp file in the same directory and are moved into place with `rename`, so a\n * crash or a concurrent reader never observes a partial file: the path holds either the previous\n * content or the complete new content. Parent directories are created as needed, and the file is\n * created with mode 0600 (subject to the process umask), formatted with two-space indentation and\n * a trailing newline.\n *\n * `currentVersion` is stamped verbatim as `_schemaVersion`; nothing checks it against what was\n * already on disk, so this will happily overwrite a newer file with an older version. Read first\n * if that matters.\n *\n * Rejects when `data` cannot be serialized — a circular reference, or a `toJSON` that throws.\n * Serialization happens before any filesystem call, so on that path no directory is created, no\n * temp file exists, and the file already on disk is untouched.\n *\n * Atomicity is the rename's, so it is as strong as the filesystem's: on NFS, SMB or FUSE the\n * underlying writer emits a one-shot warning that the guarantee is weaker there.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function writeVersionedJson<T>(\n path: string,\n data: T,\n currentVersion: number,\n): Promise<void> {\n const file: VersionedJsonFile<T> = {\n _schemaVersion: currentVersion,\n data,\n };\n await atomicWriteJson(path, file);\n}\n","/**\n * Path resolution for SDK state files (ADR D60).\n *\n * Theokit anchors state at `<cwd>/.theokit/` by default (per-cwd). An\n * optional `THEOKIT_HOME` environment variable overrides this, enabling\n * test isolation, profile switching, and multi-tenant deployments.\n *\n * Rules:\n * - `getTheokitHome(cwd)` is the canonical resolver **for cwd-anchored state**. Never hardcode\n * `path.join(cwd, \".theokit\")` in callers — use this function so tests\n * and overrides stay consistent.\n *\n * M94 — this comment said \"the ONLY canonical resolver\", and stopped being true: the\n * transcript gained `transcriptRoot()`, which is **home-anchored** (`~/.theokit`) with the same\n * `THEOKIT_HOME` override. The two defaults differ on purpose — unifying would move the\n * transcript of everyone who does NOT set the variable, which is a data migration and not a\n * re-export.\n *\n * A consequence worth writing down: **without `THEOKIT_HOME` the state stays split in two**\n * — registry in `<cwd>/.theokit`, transcript in `~/.theokit`. M94 unifies only for those who set\n * the variable. Unifying both defaults is another milestone's work.\n * - `getProfilesRoot()` is intentionally home-anchored (not affected by\n * `THEOKIT_HOME`) so `theokit profile list` discovers all profiles\n * regardless of which is active.\n * - `displayTheokitHome(cwd)` returns a human-readable path for logs.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst THEOKIT_DIR_NAME = \".theokit\";\n\n/**\n * Resolve the directory cwd-anchored SDK state lives in.\n *\n * `THEOKIT_HOME` wins when it is set and not blank after trimming; the trimmed value is used, and\n * it is used VERBATIM — it is not resolved against `cwd`, so a relative value stays relative and\n * `.theokit` is not appended to it. Otherwise the answer is `<cwd>/.theokit`.\n *\n * The environment is read on every call, so a change to the variable takes effect immediately\n * rather than being frozen at import.\n *\n * This creates nothing and checks nothing: the returned path may not exist, and the caller owns\n * the `mkdir`. Call it instead of writing `join(cwd, \".theokit\")` by hand, or the override stops\n * working for that one call site and tests silently touch the real home.\n *\n * Not the whole story about where state lives — the transcript is home-anchored via\n * `transcriptRoot()`, honoring the same variable but defaulting to `~/.theokit`. With\n * `THEOKIT_HOME` unset, state is genuinely split between two roots.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getTheokitHome(cwd: string): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) {\n return override;\n }\n return join(cwd, THEOKIT_DIR_NAME);\n}\n\n/**\n * The directory holding every profile: always `~/.theokit/profiles`, from `os.homedir()`.\n *\n * Deliberately NOT affected by `THEOKIT_HOME`, which is the one thing to remember about it. If it\n * followed the override, a session pointed at one profile would only be able to see that profile,\n * and `theokit profile list` could never enumerate the rest. Profiles are the thing the override\n * switches between, so their index cannot live behind it.\n *\n * Takes no `cwd` for the same reason. Creates nothing; the path may not exist.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getProfilesRoot(): string {\n return join(homedir(), THEOKIT_DIR_NAME, \"profiles\");\n}\n\n/**\n * The same path `getTheokitHome(cwd)` returns, shortened for display: the home directory prefix\n * collapses to `~`, so `/home/ada/.theokit` prints as `~/.theokit`.\n *\n * For humans only — log lines, CLI output, error messages. The result is NOT a usable path: `~`\n * is a shell convention that `fs` does not expand, so passing this to a filesystem call resolves\n * a literal directory named `~` relative to the process cwd. Use `getTheokitHome` for anything\n * that touches disk.\n *\n * Collapsing is a prefix match on the home directory followed by a literal `/`, so a sibling like\n * `/home/adalovelace` is left alone even though `/home/ada` is a string prefix of it. A path\n * outside the home directory comes back unchanged — and so does a Windows path, where the\n * separator is a backslash and the prefix test therefore never matches.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function displayTheokitHome(cwd: string): string {\n const resolved = getTheokitHome(cwd);\n const home = homedir();\n if (resolved === home) return \"~\";\n if (resolved.startsWith(`${home}/`)) {\n return `~${resolved.slice(home.length)}`;\n }\n return resolved;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createSemaphore } from './chunk-
|
|
1
|
+
import { createSemaphore } from './chunk-OC4NTGMN.js';
|
|
2
2
|
|
|
3
3
|
// src/internal/runtime/concurrency/map-with-concurrency.ts
|
|
4
4
|
var NEVER_ABORT = new AbortController().signal;
|
|
@@ -21,5 +21,5 @@ async function mapWithConcurrency(items, concurrency, fn, options) {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export { mapWithConcurrency };
|
|
24
|
-
//# sourceMappingURL=chunk-
|
|
25
|
-
//# sourceMappingURL=chunk-
|
|
24
|
+
//# sourceMappingURL=chunk-UC3HT2S4.js.map
|
|
25
|
+
//# sourceMappingURL=chunk-UC3HT2S4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-UC3HT2S4.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { atomicWriteJson } from './chunk-
|
|
2
|
-
import { diag } from './chunk-
|
|
1
|
+
import { atomicWriteJson } from './chunk-VF7EWVDG.js';
|
|
2
|
+
import { diag } from './chunk-T7O6K6PX.js';
|
|
3
3
|
import { readFile, rename } from 'fs/promises';
|
|
4
4
|
import { homedir } from 'os';
|
|
5
5
|
import { join } from 'path';
|
|
@@ -99,5 +99,5 @@ function displayTheokitHome(cwd) {
|
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
export { displayTheokitHome, getProfilesRoot, getTheokitHome, migrateSchema, readVersionedJson, writeVersionedJson };
|
|
102
|
-
//# sourceMappingURL=chunk-
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
102
|
+
//# sourceMappingURL=chunk-UPRJR6IP.js.map
|
|
103
|
+
//# sourceMappingURL=chunk-UPRJR6IP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/schema-version.ts","../src/internal/persistence/paths.ts"],"names":[],"mappings":";;;;;;AA4HO,SAAS,cAAc,IAAA,EAAiD;AAC7E,EAAA,MAAM,EAAE,EAAA,EAAI,cAAA,EAAgB,UAAA,EAAY,KAAA,GAAQ,MAAK,GAAI,IAAA;AACzD,EAAA,MAAM,YAAY,EAAA,CAAG,MAAA,CAAO,gBAAgB,EAAE,MAAA,EAAQ,MAAM,CAAA;AAC5D,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,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,QAAQ,MAAM,CAAA;AAC/B;AAyBA,eAAsB,kBAAA,CACpB,IAAA,EACA,IAAA,EACA,cAAA,EACe;AACf,EAAA,MAAM,IAAA,GAA6B;AAAA,IACjC,cAAA,EAAgB,cAAA;AAAA,IAChB;AAAA,GACF;AACA,EAAA,MAAM,eAAA,CAAgB,MAAM,IAAI,CAAA;AAClC;AC/SA,IAAM,gBAAA,GAAmB,UAAA;AAuBlB,SAAS,eAAe,GAAA,EAAqB;AAClD,EAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,YAAA,EAAc,IAAA,EAAK;AAChD,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,EAAG;AACjD,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,OAAO,IAAA,CAAK,KAAK,gBAAgB,CAAA;AACnC;AAeO,SAAS,eAAA,GAA0B;AACxC,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,gBAAA,EAAkB,UAAU,CAAA;AACrD;AAmBO,SAAS,mBAAmB,GAAA,EAAqB;AACtD,EAAA,MAAM,QAAA,GAAW,eAAe,GAAG,CAAA;AACnC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,IAAI,QAAA,KAAa,MAAM,OAAO,GAAA;AAC9B,EAAA,IAAI,QAAA,CAAS,UAAA,CAAW,CAAA,EAAG,IAAI,GAAG,CAAA,EAAG;AACnC,IAAA,OAAO,CAAA,CAAA,EAAI,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,MAAM,CAAC,CAAA,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-UPRJR6IP.js","sourcesContent":["/**\n * Schema versioning helpers (ADR D62).\n *\n * Two parallel APIs:\n * - `migrateSchema` — SQLite via `PRAGMA user_version` + ordered forward-only migrations.\n * - `readVersionedJson` / `writeVersionedJson` — JSON files with `_schemaVersion` field.\n *\n * Forward-only: never deletes data, never downgrades. Migration callbacks\n * own the transformation; this module owns the bookkeeping.\n *\n * @internal\n */\n\nimport { readFile, rename } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"./atomic-write.js\";\n\n// ────────────────────── SQLite migrations ──────────────────────\n\n/**\n * The three `better-sqlite3` methods this module actually uses, declared structurally so nothing\n * here imports the driver.\n *\n * A real `better-sqlite3` `Database` satisfies it. `pragma` is called both to read\n * (`pragma(\"user_version\", { simple: true })`, which must return the number itself rather than a\n * row array) and to write (`pragma(\"user_version = N\")`). `transaction` must return a function\n * that, when called, runs the wrapped body inside a real SQLite transaction and rolls it back if\n * the body throws — a stub that merely calls through gives `migrateSchema` no atomicity, and a\n * half-applied migration is exactly what it exists to prevent.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface SqliteLike {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n exec: (sql: string) => void;\n transaction: <Args extends unknown[], R>(fn: (...args: Args) => R) => (...args: Args) => R;\n}\n\n/**\n * One forward migration step.\n *\n * `up` runs inside the shared transaction and must be self-contained: it may not commit, and any\n * error it throws aborts the whole run and rolls back every step in it, including the ones that\n * already succeeded. `user_version` is set to `toVersion` immediately after `up` returns, inside\n * the same transaction, so version and schema move together or not at all.\n *\n * `toVersion` is the version the database reaches, not the one it starts from. Steps are ordered\n * by it, gaps are allowed, and two steps sharing a `toVersion` both run — nothing deduplicates\n * them.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface Migration {\n toVersion: number;\n up: (db: SqliteLike) => void;\n}\n\n/**\n * Arguments to `migrateSchema`.\n *\n * `currentVersion` is the version the code expects, and it is the ceiling: a migration whose\n * `toVersion` exceeds it is left unapplied for a later release. `migrations` may be given in any\n * order and may contain steps already applied — both are filtered and sorted here. `label` only\n * ever appears in the downgrade error message.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaOptions {\n db: SqliteLike;\n currentVersion: number;\n migrations: ReadonlyArray<Migration>;\n /** For log/error context (e.g., \"memory-index\", \"registry\"). */\n label?: string;\n}\n\n/**\n * What `migrateSchema` did.\n *\n * `from` is the `user_version` found on the database, `to` is the version it holds afterwards,\n * and `ran` is how many steps executed. When nothing was pending, `to === from` and `ran === 0`.\n *\n * `to` is the `toVersion` of the last step applied, NOT `currentVersion`. A database at version 3\n * against `currentVersion: 5` with no migration in that range comes back as\n * `{ from: 3, to: 3, ran: 0 }` — the gap is reported, not closed. Comparing `to` with\n * `currentVersion` is how a caller notices that the migration list is missing a step.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaResult {\n from: number;\n to: number;\n ran: number;\n}\n\n/**\n * Bring a SQLite database's `user_version` up to `currentVersion` by running the steps that sit\n * between the two.\n *\n * Steps are sorted ascending by `toVersion` and filtered to `> stored && <= currentVersion`, then\n * run in that order inside ONE transaction: each `up` is followed immediately by the matching\n * `user_version` write. Either every step in the run commits or none does — a step that throws\n * aborts the transaction, propagates the error, and leaves the database at the version it started\n * from. There is no partially-migrated state and no resume point.\n *\n * Forward-only. When the stored version is greater than `currentVersion` — an older build opening\n * a database a newer one already migrated — this throws immediately, before touching anything,\n * with a message naming both versions and `label`. Nothing downgrades, and no data is deleted on\n * any path here; what a step does is the step's own business.\n *\n * A stored version equal to `currentVersion` returns without opening a transaction. A `user_version`\n * that is absent or not a number is read as 0, so a fresh database runs every step.\n *\n * Concurrency: the SQLite transaction is the only serialization. This takes no file lock, so two\n * processes migrating the same file at once are arbitrated by SQLite's own write lock — the loser\n * gets a busy or locked error from the driver, not a queued turn. Wrap the call in `withFileLock`\n * if that matters.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function migrateSchema(opts: MigrateSchemaOptions): MigrateSchemaResult {\n const { db, currentVersion, migrations, label = \"db\" } = opts;\n const storedRaw = db.pragma(\"user_version\", { simple: true });\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored > currentVersion) {\n throw new Error(\n `[${label}] schema version ${stored} > current ${currentVersion}; ` +\n \"did you downgrade the SDK? Forward-only migrations only.\",\n );\n }\n\n if (stored === currentVersion) {\n return { from: stored, to: stored, ran: 0 };\n }\n\n const pending = [...migrations]\n .sort((a, b) => a.toVersion - b.toVersion)\n .filter((m) => m.toVersion > stored && m.toVersion <= currentVersion);\n\n let ran = 0;\n let lastApplied = stored;\n\n db.transaction(() => {\n for (const m of pending) {\n m.up(db);\n db.pragma(`user_version = ${m.toVersion}`);\n lastApplied = m.toVersion;\n ran += 1;\n }\n })();\n\n return { from: stored, to: lastApplied, ran };\n}\n\n// ────────────────────── JSON versioned files ──────────────────────\n\n/**\n * The on-disk envelope: the payload under `data`, its schema version alongside it.\n *\n * `writeVersionedJson` always produces this shape. `readVersionedJson` reads it, but tolerates a\n * file that is not in it — a legacy object with no `_schemaVersion` is treated as version 0 and\n * handed to the migrate callback whole, so this type describes what is written, not everything\n * that can be read.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface VersionedJsonFile<T> {\n _schemaVersion: number;\n data: T;\n}\n\n/**\n * Upgrade callback for `readVersionedJson`, invoked only when the stored version is BELOW the\n * current one.\n *\n * `parsed` is the whole parsed JSON value, not `parsed.data`. That is deliberate: a legacy file\n * predating the envelope has its fields at the top level, and a callback handed only `.data`\n * would receive `undefined` for exactly the files that need migrating. It is typed `unknown`\n * because nothing has validated it — narrow before reading.\n *\n * `fromVersion` is the `_schemaVersion` found on disk, or 0 when the field is missing or not a\n * number.\n *\n * The return value is used as-is and is NOT written back; the file on disk still holds the old\n * shape until someone calls `writeVersionedJson`. Throwing here propagates out of\n * `readVersionedJson`, which otherwise never throws — return the default value instead if an\n * unmigratable file should be survivable.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport type VersionedJsonMigrate<T> = (parsed: unknown, fromVersion: number) => T;\n\n/**\n * Arguments to `readVersionedJson`.\n *\n * `defaultValue` is a factory rather than a value because it is called on several paths and each\n * caller must get its own object — returning a shared mutable default would let one caller's\n * edits appear in another's. It is called for a missing file, an unreadable one, a corrupt one,\n * a non-object payload, and a file written by a newer version.\n *\n * `migrate` is called only for a stored version strictly below `currentVersion`.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface ReadVersionedJsonOptions<T> {\n path: string;\n currentVersion: number;\n migrate: VersionedJsonMigrate<T>;\n defaultValue: () => T;\n}\n\n/**\n * Read a versioned JSON file, migrating or falling back rather than failing.\n *\n * What comes back, by case:\n *\n * - version matches `currentVersion` — the file's `data` field, returned as `T` WITHOUT\n * validation. A file whose envelope is right but whose payload is not gets through.\n * - version below `currentVersion` — whatever `migrate(parsed, stored)` returns. The migrated\n * value is not persisted; the file is untouched.\n * - version above `currentVersion` — `defaultValue()`, plus a warning. Forward-only: a file\n * written by a newer build is left alone rather than downgraded.\n * - file missing, or unreadable for any other reason (permissions, a directory in its place) —\n * `defaultValue()`, silently. Absence and denial are not distinguished.\n * - file present but not valid JSON — `defaultValue()`, and the file is RENAMED to\n * `<path>.corrupt.<epoch-ms>` so the next run starts clean and the bad bytes stay available.\n * A rename that itself fails is warned about and the read still returns the default, which\n * means the same corrupt file will be met again next time.\n * - JSON that parses to a non-object (a number, a string, `null`) — `defaultValue()`, silently\n * and without moving the file aside.\n *\n * The only ways this throws are through the callbacks you supply: `migrate` or `defaultValue`\n * raising. Nothing else here rejects.\n *\n * There is no locking. A concurrent `writeVersionedJson` on the same path is atomic at the rename,\n * so a reader sees either the old file or the new one, never a half-written one — but a\n * read-modify-write built from this pair is NOT atomic across the two calls, and needs\n * `withFileLock` around both.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function readVersionedJson<T>(opts: ReadVersionedJsonOptions<T>): Promise<T> {\n const { path, currentVersion, migrate, defaultValue } = opts;\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf-8\");\n } catch {\n return defaultValue();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // T5.10 — move corrupt file aside so (a) user can investigate and\n // (b) next run starts fresh instead of hitting the same warning loop.\n const asidePath = `${path}.corrupt.${Date.now()}`;\n try {\n await rename(path, asidePath);\n diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.\\n`);\n } catch {\n diag(`[theokit-sdk] ${path} is corrupt; using default value.\\n`);\n }\n return defaultValue();\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return defaultValue();\n }\n\n const file = parsed as { _schemaVersion?: unknown; data?: unknown };\n const storedRaw = file._schemaVersion;\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored === currentVersion) {\n return file.data as T;\n }\n\n if (stored > currentVersion) {\n diag(\n `[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; ` +\n \"using default value (forward-only).\\n\",\n );\n return defaultValue();\n }\n\n // EC-2 fix: pass the FULL parsed object to migrate, not just `file.data`.\n // Legacy shapes (e.g., `{ schemaVersion: \"1.0\", agents: {...} }` without\n // a `data` field) need to inspect the whole thing.\n return migrate(parsed, stored);\n}\n\n/**\n * Write `data` wrapped in the version envelope, replacing the file atomically.\n *\n * The bytes go to a temp file in the same directory and are moved into place with `rename`, so a\n * crash or a concurrent reader never observes a partial file: the path holds either the previous\n * content or the complete new content. Parent directories are created as needed, and the file is\n * created with mode 0600 (subject to the process umask), formatted with two-space indentation and\n * a trailing newline.\n *\n * `currentVersion` is stamped verbatim as `_schemaVersion`; nothing checks it against what was\n * already on disk, so this will happily overwrite a newer file with an older version. Read first\n * if that matters.\n *\n * Rejects when `data` cannot be serialized — a circular reference, or a `toJSON` that throws.\n * Serialization happens before any filesystem call, so on that path no directory is created, no\n * temp file exists, and the file already on disk is untouched.\n *\n * Atomicity is the rename's, so it is as strong as the filesystem's: on NFS, SMB or FUSE the\n * underlying writer emits a one-shot warning that the guarantee is weaker there.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function writeVersionedJson<T>(\n path: string,\n data: T,\n currentVersion: number,\n): Promise<void> {\n const file: VersionedJsonFile<T> = {\n _schemaVersion: currentVersion,\n data,\n };\n await atomicWriteJson(path, file);\n}\n","/**\n * Path resolution for SDK state files (ADR D60).\n *\n * Theokit anchors state at `<cwd>/.theokit/` by default (per-cwd). An\n * optional `THEOKIT_HOME` environment variable overrides this, enabling\n * test isolation, profile switching, and multi-tenant deployments.\n *\n * Rules:\n * - `getTheokitHome(cwd)` is the canonical resolver **for cwd-anchored state**. Never hardcode\n * `path.join(cwd, \".theokit\")` in callers — use this function so tests\n * and overrides stay consistent.\n *\n * M94 — this comment said \"the ONLY canonical resolver\", and stopped being true: the\n * transcript gained `transcriptRoot()`, which is **home-anchored** (`~/.theokit`) with the same\n * `THEOKIT_HOME` override. The two defaults differ on purpose — unifying would move the\n * transcript of everyone who does NOT set the variable, which is a data migration and not a\n * re-export.\n *\n * A consequence worth writing down: **without `THEOKIT_HOME` the state stays split in two**\n * — registry in `<cwd>/.theokit`, transcript in `~/.theokit`. M94 unifies only for those who set\n * the variable. Unifying both defaults is another milestone's work.\n * - `getProfilesRoot()` is intentionally home-anchored (not affected by\n * `THEOKIT_HOME`) so `theokit profile list` discovers all profiles\n * regardless of which is active.\n * - `displayTheokitHome(cwd)` returns a human-readable path for logs.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst THEOKIT_DIR_NAME = \".theokit\";\n\n/**\n * Resolve the directory cwd-anchored SDK state lives in.\n *\n * `THEOKIT_HOME` wins when it is set and not blank after trimming; the trimmed value is used, and\n * it is used VERBATIM — it is not resolved against `cwd`, so a relative value stays relative and\n * `.theokit` is not appended to it. Otherwise the answer is `<cwd>/.theokit`.\n *\n * The environment is read on every call, so a change to the variable takes effect immediately\n * rather than being frozen at import.\n *\n * This creates nothing and checks nothing: the returned path may not exist, and the caller owns\n * the `mkdir`. Call it instead of writing `join(cwd, \".theokit\")` by hand, or the override stops\n * working for that one call site and tests silently touch the real home.\n *\n * Not the whole story about where state lives — the transcript is home-anchored via\n * `transcriptRoot()`, honoring the same variable but defaulting to `~/.theokit`. With\n * `THEOKIT_HOME` unset, state is genuinely split between two roots.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getTheokitHome(cwd: string): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) {\n return override;\n }\n return join(cwd, THEOKIT_DIR_NAME);\n}\n\n/**\n * The directory holding every profile: always `~/.theokit/profiles`, from `os.homedir()`.\n *\n * Deliberately NOT affected by `THEOKIT_HOME`, which is the one thing to remember about it. If it\n * followed the override, a session pointed at one profile would only be able to see that profile,\n * and `theokit profile list` could never enumerate the rest. Profiles are the thing the override\n * switches between, so their index cannot live behind it.\n *\n * Takes no `cwd` for the same reason. Creates nothing; the path may not exist.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getProfilesRoot(): string {\n return join(homedir(), THEOKIT_DIR_NAME, \"profiles\");\n}\n\n/**\n * The same path `getTheokitHome(cwd)` returns, shortened for display: the home directory prefix\n * collapses to `~`, so `/home/ada/.theokit` prints as `~/.theokit`.\n *\n * For humans only — log lines, CLI output, error messages. The result is NOT a usable path: `~`\n * is a shell convention that `fs` does not expand, so passing this to a filesystem call resolves\n * a literal directory named `~` relative to the process cwd. Use `getTheokitHome` for anything\n * that touches disk.\n *\n * Collapsing is a prefix match on the home directory followed by a literal `/`, so a sibling like\n * `/home/adalovelace` is left alone even though `/home/ada` is a string prefix of it. A path\n * outside the home directory comes back unchanged — and so does a Windows path, where the\n * separator is a backslash and the prefix test therefore never matches.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function displayTheokitHome(cwd: string): string {\n const resolved = getTheokitHome(cwd);\n const home = homedir();\n if (resolved === home) return \"~\";\n if (resolved.startsWith(`${home}/`)) {\n return `~${resolved.slice(home.length)}`;\n }\n return resolved;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AuthenticationError } from './chunk-
|
|
1
|
+
import { AuthenticationError } from './chunk-IDCKSLYH.js';
|
|
2
2
|
import { randomBytes } from 'crypto';
|
|
3
3
|
import { statSync, readFileSync, mkdirSync, chmodSync, openSync, writeFileSync, fsyncSync, closeSync, renameSync, unlinkSync } from 'fs';
|
|
4
4
|
import { join } from 'path';
|
|
@@ -143,5 +143,5 @@ function writeCredential(cred, config, env = {}) {
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
export { CredentialError, assertSecureModes, authFilePath, credentialHome, readAuthFile, readStoredOAuth, writeCredential };
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
146
|
+
//# sourceMappingURL=chunk-UQGQFBRL.js.map
|
|
147
|
+
//# sourceMappingURL=chunk-UQGQFBRL.js.map
|