@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 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IA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K6YR5P.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AA0CO,IAAM,mBAAA,GAAsB,GAAA;AAUnC,SAAS,QAAA,GAAsB;AAC7B,EAAA,OAAO,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAK,QAAA,EAAUC,aAAS,EAAG,KAAA,EAAO,IAAA,CAAK,GAAA,EAAI,EAAE;AACrE;AAWA,SAAS,UAAA,CAAW,UAAkB,KAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAKC,WAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAAC,YAAA,CAAU,EAAA,EAAI,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAInC,IAAAC,aAAA,CAAW,IAAI,GAAK,CAAA;AAAA,EACtB,CAAA,SAAE;AACA,IAAAC,YAAA,CAAU,EAAE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,EAAsC;AAC9E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAAG,SAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC,CAAA;AAAA,IACA,OAAO,MAAY;AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-4I55V454.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|
|
@@ -4,6 +4,13 @@ var chunkNINIJCHU_cjs = require('./chunk-NINIJCHU.cjs');
|
|
|
4
4
|
var zod = require('zod');
|
|
5
5
|
var async_hooks = require('async_hooks');
|
|
6
6
|
|
|
7
|
+
var depthStore = new async_hooks.AsyncLocalStorage();
|
|
8
|
+
async function withDelegationDepth(depth, fn) {
|
|
9
|
+
return depthStore.run(depth, fn);
|
|
10
|
+
}
|
|
11
|
+
function currentDelegationDepth() {
|
|
12
|
+
return depthStore.getStore() ?? 0;
|
|
13
|
+
}
|
|
7
14
|
var credentialsStore = new async_hooks.AsyncLocalStorage();
|
|
8
15
|
async function withInheritedSubAgentCredentials(credentials, fn) {
|
|
9
16
|
return credentialsStore.run(credentials, fn);
|
|
@@ -62,7 +69,13 @@ function buildChildCreateOptions(spec, inherited) {
|
|
|
62
69
|
tools: spec.tools ?? []
|
|
63
70
|
};
|
|
64
71
|
}
|
|
65
|
-
async function runChildAgent(spec, input, signal, maxSteps, inherited) {
|
|
72
|
+
async function runChildAgent(spec, input, signal, maxSteps, inherited, depth) {
|
|
73
|
+
return withDelegationDepth(
|
|
74
|
+
depth,
|
|
75
|
+
() => runChildAgentInScope(spec, input, signal, maxSteps, inherited)
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
async function runChildAgentInScope(spec, input, signal, maxSteps, inherited) {
|
|
66
79
|
const agent = await chunkNINIJCHU_cjs.getAgentFacade().create(buildChildCreateOptions(spec, inherited));
|
|
67
80
|
try {
|
|
68
81
|
const sendOptions = {
|
|
@@ -110,10 +123,9 @@ async function applyDelegationComplete(spec, input, result, iteration) {
|
|
|
110
123
|
return completion?.feedback !== void 0 ? result + completion.feedback : result;
|
|
111
124
|
}
|
|
112
125
|
function defineSubAgent(spec, _parentDepth = 0) {
|
|
113
|
-
const currentDepth = _parentDepth + 1;
|
|
114
126
|
const maxDepth = spec.maxDelegationDepth ?? 3;
|
|
115
|
-
if (
|
|
116
|
-
throw new MaxDelegationDepthError(
|
|
127
|
+
if (_parentDepth + 1 > maxDepth) {
|
|
128
|
+
throw new MaxDelegationDepthError(_parentDepth + 1, maxDepth);
|
|
117
129
|
}
|
|
118
130
|
const inputZod = zod.z.object({
|
|
119
131
|
input: zod.z.string().describe("Task for the subagent")
|
|
@@ -134,6 +146,10 @@ function defineSubAgent(spec, _parentDepth = 0) {
|
|
|
134
146
|
handler: async (rawInput, ctx) => {
|
|
135
147
|
const { input: parsed } = inputZod.parse(rawInput);
|
|
136
148
|
const inherited = currentInheritedSubAgentCredentials();
|
|
149
|
+
const currentDepth = _parentDepth + currentDelegationDepth() + 1;
|
|
150
|
+
if (currentDepth > maxDepth) {
|
|
151
|
+
throw new MaxDelegationDepthError(currentDepth, maxDepth);
|
|
152
|
+
}
|
|
137
153
|
iteration += 1;
|
|
138
154
|
const capturedIteration = iteration;
|
|
139
155
|
const start = await applyDelegationStart(spec, parsed, capturedIteration);
|
|
@@ -141,7 +157,14 @@ function defineSubAgent(spec, _parentDepth = 0) {
|
|
|
141
157
|
const input = applyMessageFilter(spec, start.input, ctx?.messages);
|
|
142
158
|
let result;
|
|
143
159
|
try {
|
|
144
|
-
result = await runChildAgent(
|
|
160
|
+
result = await runChildAgent(
|
|
161
|
+
spec,
|
|
162
|
+
input,
|
|
163
|
+
ctx?.signal,
|
|
164
|
+
start.maxSteps,
|
|
165
|
+
inherited,
|
|
166
|
+
currentDepth
|
|
167
|
+
);
|
|
145
168
|
} catch (error) {
|
|
146
169
|
await notifyDelegationError(spec, input, error, capturedIteration);
|
|
147
170
|
throw error;
|
|
@@ -179,5 +202,5 @@ exports.MaxDelegationDepthError = MaxDelegationDepthError;
|
|
|
179
202
|
exports.SubAgent = SubAgent;
|
|
180
203
|
exports.subAgentToolsFromDefinitions = subAgentToolsFromDefinitions;
|
|
181
204
|
exports.withInheritedSubAgentCredentials = withInheritedSubAgentCredentials;
|
|
182
|
-
//# sourceMappingURL=chunk-
|
|
183
|
-
//# sourceMappingURL=chunk-
|
|
205
|
+
//# sourceMappingURL=chunk-4O5TGQBW.cjs.map
|
|
206
|
+
//# sourceMappingURL=chunk-4O5TGQBW.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/concurrency/delegation-depth.ts","../src/internal/runtime/concurrency/subagent-credentials.ts","../src/a2a/subagent.ts"],"names":["AsyncLocalStorage","getAgentFacade","z"],"mappings":";;;;;;AA6BA,IAAM,UAAA,GAAa,IAAIA,6BAAA,EAA0B;AAWjD,eAAsB,mBAAA,CAAuB,OAAe,EAAA,EAAkC;AAC5F,EAAA,OAAO,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AACjC;AAUO,SAAS,sBAAA,GAAiC;AAC/C,EAAA,OAAO,UAAA,CAAW,UAAS,IAAK,CAAA;AAClC;ACiBA,IAAM,gBAAA,GAAmB,IAAIA,6BAAAA,EAAwC;AAUrE,eAAsB,gCAAA,CACpB,aACA,EA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AA,EAAe;AAC7D,IAAA,OAAO,cAAA,CAAe,MAAM,WAAW,CAAA;AAAA,EACzC;AACF;AAsBO,SAAS,4BAAA,CACd,QACA,WAAA,EACc;AACd,EAAA,OAAO,MAAA,CAAO,QAAQ,MAAM,CAAA,CAAE,IAAI,CAAC,CAAC,IAAA,EAAM,GAAG,CAAA,KAAM;AACjD,IAAA,MAAM,SAAA,GACJ,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,KAAK,CAAA,IAAK,GAAA,CAAI,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,IAAI,GAAA,CAAI,GAAA,CAAI,KAAK,CAAA,GAAI,MAAA;AAC1E,IAAA,MAAM,UAAA,GAAa,SAAA,GAAY,WAAA,CAAY,MAAA,CAAO,CAAC,CAAA,KAAM,SAAA,CAAU,GAAA,CAAI,CAAA,CAAE,IAAI,CAAC,CAAA,GAAI,WAAA;AAClF,IAAA,OAAO,cAAA,CAAe;AAAA,MACpB,IAAA;AAAA,MACA,aAAa,GAAA,CAAI,WAAA;AAAA,MACjB,cAAc,GAAA,CAAI,MAAA;AAAA;AAAA;AAAA,MAGlB,GAAI,GAAA,CAAI,KAAA,KAAU,MAAA,IAAa,GAAA,CAAI,KAAA,KAAU,SAAA,GAAY,EAAE,KAAA,EAAO,GAAA,CAAI,KAAA,EAAM,GAAI,EAAC;AAAA,MACjF,GAAI,IAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,GAAI,EAAC;AAAA,MAC5D,KAAA,EAAO,CAAC,GAAG,UAAU;AAAA,KACtB,CAAA;AAAA,EACH,CAAC,CAAA;AACH","file":"chunk-4O5TGQBW.cjs","sourcesContent":["/**\n * #364 — how deep the current delegation chain already is, delivered through the CALL.\n *\n * ## The bug this replaces\n *\n * `maxDelegationDepth` was checked once, at tool-CONSTRUCTION time, against a `_parentDepth`\n * argument that nothing in the SDK ever incremented. Constructing a tool says nothing about how\n * deep it will later be invoked, so with the documented call — `SubAgent.create(spec)` — the test\n * was `1 > maxDepth`, false for every spec that did not ask for depth 0. A subagent whose tools\n * include another subagent recursed unbounded, which is precisely what the guard exists to stop.\n * The only path that ever tripped it was a caller threading the number by hand.\n *\n * ## Why the async scope closes it\n *\n * Depth is a property of the RUN, not of the object. A child's run loop — and therefore every tool\n * it dispatches — executes inside the async continuation of its parent's handler, so a value\n * published on that context is exactly what a nested dispatch needs to read. This is the same seam\n * `subagent-credentials.ts` uses, and for the same reason: what survives every layer that rebuilds\n * a tool object is the call, never the object.\n *\n * It is kept in its own module rather than folded into the credentials payload because depth is a\n * separate concern with a separate lifetime — the credentials scope is opened once per run by the\n * run loop, while depth is opened per delegation by the dispatching tool.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst depthStore = new AsyncLocalStorage<number>();\n\n/**\n * Run `fn` with `depth` published as the delegation depth of the current chain.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so two sibling\n * delegations from the same parent each start from the parent's depth rather than from each\n * other's.\n *\n * @internal\n */\nexport async function withDelegationDepth<T>(depth: number, fn: () => Promise<T>): Promise<T> {\n return depthStore.run(depth, fn);\n}\n\n/**\n * The delegation depth of the current chain — `0` outside any delegation.\n *\n * `0` is the honest default rather than a fallback to some previous chain's value: a subagent\n * dispatched with no parent delegation IS at depth zero.\n *\n * @internal\n */\nexport function currentDelegationDepth(): number {\n return depthStore.getStore() ?? 0;\n}\n","/**\n * theokit#148 — the parent's credentials, delivered through the CALL, not through the tool object.\n *\n * ## The class of bug this replaces\n *\n * Credential inheritance used to ride a property installed on the subagent tool object — first a\n * unique `Symbol()`, then `Symbol.for` after #143. Both are the same shape of contract: \"this\n * object will reach the dispatcher with an extra property intact\". Nothing enforces that, and it\n * broke twice for two different reasons:\n *\n * - **Module duplication** (#142/#143): `tsup splitting: false` inlined a separate copy of the\n * module into each public entry, so the two copies disagreed on a unique `Symbol()` key. Fixed at\n * the build level by M78's `splitting: true`, but the fragile contract remained.\n * - **Object normalization** (#148): any layer that rebuilds the tool from its known fields drops\n * the property. `@theokit/agents`' `toCompiledTool` does exactly that, and had to add an explicit\n * `Object.getOwnPropertySymbols` copy loop to compensate — a band-aid the SDK's contract forced\n * onto a consumer. A named field would have been dropped by the same four-field rebuild, which is\n * why \"make it a typed field\" alone does not close this.\n *\n * ## Why the async scope closes it\n *\n * What survives a rebuild is not the object — it is the CALL. A normalizing wrapper builds a new\n * object but still invokes the original handler, inside the parent run's async context. So\n * credentials published on that context reach the handler regardless of what the tool object looks\n * like by then. There is no property left for a layer to drop.\n *\n * It also fixes a defect the per-object slot could not: credentials were stored per tool INSTANCE,\n * so one subagent tool shared by two agents got last-writer-wins. The scope is per run.\n *\n * Nothing is exposed to third-party tool code: the store is module-private, credentials never touch\n * a handler's `ctx`, and `currentInheritedSubAgentCredentials` is `@internal`.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport type { Plugin } from \"../../plugins/types.js\";\n\n/**\n * Credentials a parent agent hands down to its subagent tools so the child inherits the parent's\n * auth (and, absent an explicit `spec.model`, its model).\n *\n * Declared here rather than in `a2a/subagent.ts` so the delivery mechanism owns the payload shape\n * and the dependency runs one way (`a2a/subagent` -> this module). `a2a/subagent.ts` briefly\n * re-exported it \"for back-compat\"; knip proved there was no back-compat surface to preserve — the\n * type was never in the public barrel nor the exports map — so the re-export was deleted.\n *\n * Emitted rather than erased: `a2a/subagent.d.ts` imports it by name, and that entry IS published,\n * so erasing this declaration ships a `.d.ts` that does not compile. Not being in the exports map\n * is what keeps it out of the semver contract; erasure is not what does that.\n */\nexport interface InheritedCredentials {\n readonly apiKey?: string;\n readonly model?: ModelSelection;\n /**\n * The parent's shell-sandbox posture (`local.sandboxOptions.enabled`), handed down so a delegated\n * child of a sandboxed parent stays sandboxed unless its role explicitly opts out. Without this a\n * child ran unsandboxed whenever its role omitted `sandbox` — a default-open the sandbox wiring\n * exists to prevent.\n */\n readonly sandbox?: boolean;\n /**\n * #55 — the parent's code-registered plugins (e.g. a `PermissionPlugin`) handed down so the child\n * runs under the SAME policy. Without this, a delegated child's inner tool calls escape the\n * parent's argument-level permission gate. First-party delegation path only — never exposed to\n * third-party tool `ctx`.\n */\n readonly plugins?: readonly Plugin[];\n}\n\nconst credentialsStore = new AsyncLocalStorage<InheritedCredentials>();\n\n/**\n * Run `fn` with `credentials` published as the delegation credentials of the current run.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so a delegated child that\n * itself delegates hands down ITS credentials, not its parent's.\n *\n * @internal\n */\nexport async function withInheritedSubAgentCredentials<T>(\n credentials: InheritedCredentials,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialsStore.run(credentials, fn);\n}\n\n/**\n * The delegation credentials of the current run, or `undefined` outside a run scope.\n *\n * `undefined` is deliberately NOT a fallback to some previous run's value: a subagent dispatched\n * with no parent context must create its child without an inherited key rather than reuse a\n * credential that belonged to someone else.\n *\n * @internal\n */\nexport function currentInheritedSubAgentCredentials(): InheritedCredentials | undefined {\n return credentialsStore.getStore();\n}\n","/**\n * Subagent delegation — declarative child agent invocable as a tool.\n *\n * Per ADR D2: `defineSubAgent(spec)` returns a `CustomTool` that, when\n * invoked by the LLM, creates a child agent and sends the input as a\n * message. EC-2: delegation depth is tracked across the RUN (#364) — each\n * delegation publishes its depth on the async scope its child executes in, so a\n * subagent that delegates to a subagent is bounded by `maxDelegationDepth`\n * without the caller threading a counter by hand.\n *\n * SE10 — the handler forwards the parent run's `AbortSignal` to the child.\n * SE11 — optional `onDelegationStart` / `onDelegationComplete` lifecycle hooks\n * let the caller reject, rewrite, observe, or annotate a delegation.\n *\n * @public\n */\n\nimport { z } from \"zod\";\nimport {\n currentDelegationDepth,\n withDelegationDepth,\n} from \"../internal/runtime/concurrency/delegation-depth.js\";\nimport {\n currentInheritedSubAgentCredentials,\n type InheritedCredentials,\n} from \"../internal/runtime/concurrency/subagent-credentials.js\";\nimport { getAgentFacade } from \"../internal/runtime/registry/agent-factory-registry.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n CustomTool,\n ToolContextMessage,\n} from \"../types/agent.js\";\nimport type { ModelSelection } from \"../types/agent-prims.js\";\nimport type { Run } from \"../types/run.js\";\n\n/** Arguments passed to {@link SubAgentSpec.messageFilter} (SE12). */\nexport interface MessageFilterArgs {\n /** The supervisor transcript (read-only text projection) available to this delegation. */\n messages: readonly ToolContextMessage[];\n /** The prompt about to be delegated (after any `onDelegationStart` rewrite). */\n input: string;\n /** The subagent's name. */\n name: string;\n}\n\n/** Context passed to {@link SubAgentSpec.onDelegationStart} before the child runs. */\nexport interface DelegationStartContext {\n input: string;\n name: string;\n /**\n * SE15 — 1-based count of times THIS subagent tool has been invoked (a\n * per-`defineSubAgent`-instance counter). Incremented before this hook runs;\n * a rejected delegation still counts. Enables reject-after-N patterns.\n */\n iteration: number;\n}\n\n/**\n * Decision returned from {@link SubAgentSpec.onDelegationStart}. Discriminated on\n * `proceed` so a rejection (`proceed: false` + `rejectionReason`) and an approval\n * (`modifiedInput`) cannot be mixed into one nonsensical object.\n */\nexport type DelegationStartDecision =\n | { proceed: false; rejectionReason?: string }\n | {\n proceed?: true;\n modifiedInput?: string;\n /** SE13 — cap the child's iteration count (forwarded as `SendOptions.maxIterations`). */\n modifiedMaxSteps?: number;\n };\n\n/** Context passed to {@link SubAgentSpec.onDelegationComplete} after the child settles. */\nexport interface DelegationCompleteContext {\n input: string;\n name: string;\n /** The child's text result (present on success). */\n result?: string;\n /** The error the child threw (present on failure); the error is still re-thrown. */\n error?: unknown;\n /** SE15 — the same 1-based iteration this delegation's `onDelegationStart` saw. */\n iteration: number;\n}\n\n/**\n * The return of a delegation hook: a decision, a promise of one, or nothing —\n * `void` lets a side-effect-only callback (`(ctx) => { log(ctx) }`) type-check,\n * which is the common case (mirrors a peer framework's `async ctx => { ... }` hooks).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: `void` is the idiomatic return for an optional-return callback; the rule false-positives on callback return unions.\ntype DelegationHookResult<T> = T | void | Promise<T | void>;\n\n/** Decision returned from {@link SubAgentSpec.onDelegationComplete}. */\nexport interface DelegationCompleteDecision {\n /** Appended to the child's result string. */\n feedback?: string;\n}\n\n/**\n * The declaration of a delegating child agent, handed to `SubAgent.create(spec)`.\n *\n * `name`, `description` and `instructions` are the only required fields: the first\n * two become the tool the supervisor's model sees, the third becomes the child's\n * system prompt. Everything else narrows what the child inherits.\n *\n * const research = SubAgent.create({\n * name: \"research\",\n * description: \"Look a fact up\",\n * instructions: \"You answer with one sentence.\",\n * });\n * const agent = await Agent.create({ tools: [research] });\n *\n * The tool's own input schema is fixed — one required string property, `input`.\n * It is not derived from this spec and cannot be widened here.\n *\n * What the child inherits from the parent AT DISPATCH TIME, not from this object:\n * the API key, the model (unless `model` is set), the parent's plugins, and the\n * parent's sandbox posture (unless `sandbox` is set). An absent `sandbox` inherits;\n * an explicit `sandbox: false` turns confinement OFF for a child of a confined\n * parent, which is not the same thing.\n *\n * How it fails: the child's failure is re-thrown to the supervisor as a tool error\n * — a run ending in `status: \"error\"` becomes\n * `subagent \"<name>\" run failed: <cause>`. `onDelegationStart` and `messageFilter`\n * propagate their own throws; only a throw from `onDelegationComplete` ON THE\n * ERROR PATH is suppressed, so it cannot mask the real cause.\n *\n * Traps:\n * - `model` as a bare string drops reasoning parameters. Pass the\n * {@link ModelSelection} object form when the child needs `params`.\n * - `maxDelegationDepth` (default 3) bounds the delegation CHAIN, counted at\n * dispatch across the run (#364) — the depth is not something you thread. The\n * `parentDepth` argument of `SubAgent.create` still offsets it, for a supervisor\n * that wants a lower ceiling than the chain it sits in.\n * - Context isolation is the DEFAULT. Without `messageFilter` the child sees only\n * the delegated string; without `includeToolResults` the supervisor gets only\n * the child's final text.\n */\nexport interface SubAgentSpec {\n name: string;\n description: string;\n instructions: string;\n /**\n * A bare id string (back-compat) OR a full {@link ModelSelection} carrying\n * `params` (e.g. `[{ id: \"thinking\", value: \"low\" }]` for reasoning effort). The\n * object form is required for per-subagent reasoning effort to survive to the child\n * — the pre-M33 path took only `.id` and dropped params.\n */\n model?: string | ModelSelection;\n tools?: CustomTool[];\n /** Per-subagent shell sandbox toggle (M33). `true` ⇒ child `local.sandboxOptions.enabled`. */\n sandbox?: boolean;\n /**\n * Maximum length of the delegation CHAIN rooted at this tool, counted at dispatch\n * (default 3). Depth 1 is this subagent; a subagent it delegates to is depth 2.\n * Exceeding it throws {@link MaxDelegationDepthError} from the tool handler.\n */\n maxDelegationDepth?: number;\n /**\n * SE11 — called before the supervisor delegates. Return `{ proceed: false }`\n * to reject (the child never runs and `rejectionReason` becomes the tool\n * result), or `{ modifiedInput }` to rewrite the delegated prompt. A throwing\n * hook surfaces (never silently swallowed).\n */\n onDelegationStart?: (\n ctx: DelegationStartContext,\n ) => DelegationHookResult<DelegationStartDecision>;\n /**\n * SE11 — called after the delegation settles. On success `ctx.result` is set\n * and an optional `{ feedback }` is appended to it. On failure `ctx.error` is\n * set and the original error is ALWAYS re-thrown after this hook runs — a throw\n * from this hook on the error path is suppressed so it cannot mask the\n * delegation's real failure (on the success path a throw does propagate).\n */\n onDelegationComplete?: (\n ctx: DelegationCompleteContext,\n ) => DelegationHookResult<DelegationCompleteDecision>;\n /**\n * SE12 — opt-in parent-context forwarding. When set, the supervisor transcript\n * (`ctx.messages`, a read-only text projection) is passed to this filter and the\n * returned subset is forwarded to the child as a role-tagged context preamble\n * prepended to the delegated input. When ABSENT the child runs input-only —\n * memory isolation stays the default. A filter returning `[]` forwards nothing.\n * A throwing filter propagates (fail-fast, never swallowed — same contract as\n * `onDelegationStart`); the delegation surfaces as a tool error.\n */\n messageFilter?: (args: MessageFilterArgs) => readonly ToolContextMessage[];\n /**\n * SE14 — opt-in subagent result-context control. When `true`, the child's\n * completed tool-call results (name + result) are appended to the delegation\n * payload returned to the supervisor, inside a `<subagent-tool-results>` block.\n * When absent/`false` the delegation returns the child's final text only —\n * text-only stays the default (a peer framework's scoped posture). See ADR 0006.\n */\n includeToolResults?: boolean;\n}\n\n/**\n * Raised by `SubAgent.create(spec, parentDepth)` when `parentDepth + 1` exceeds\n * `spec.maxDelegationDepth` (default 3). Carries `currentDepth`, `maxDepth` and a\n * stable `code: \"max_delegation_depth\"`.\n *\n * Thrown from the subagent tool's handler when a delegation would exceed\n * `maxDelegationDepth` (default 3), so it surfaces as the tool call's failure —\n * catching it around the dispatching `agent.send()` works.\n *\n * Also thrown eagerly at TOOL-CONSTRUCTION time when a caller threads its own\n * `parentDepth` that is already past the limit; such a tool could never be\n * dispatched, so refusing to build it fails earlier and clearer.\n *\n * Before #364 the construction-time check was the ONLY one, against a depth\n * nothing in the SDK incremented — so under the documented `SubAgent.create(spec)`\n * call this error could not fire at all and nested delegation was unbounded. The\n * chain length now travels with the run (`internal/runtime/concurrency/delegation-depth.ts`),\n * and a caller-threaded `parentDepth` still adds to it.\n */\nexport class MaxDelegationDepthError extends Error {\n readonly code = \"max_delegation_depth\" as const;\n constructor(\n public readonly currentDepth: number,\n public readonly maxDepth: number,\n ) {\n super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);\n this.name = \"MaxDelegationDepthError\";\n }\n}\n\n/**\n * Run the `onDelegationStart` hook; returns either a rejection or the (possibly\n * rewritten) input plus the optional SE13 `maxSteps` cap.\n */\nasync function applyDelegationStart(\n spec: SubAgentSpec,\n input: string,\n iteration: number,\n): Promise<{ reject: string } | { input: string; maxSteps?: number }> {\n if (spec.onDelegationStart === undefined) return { input };\n const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });\n if (decision === undefined) return { input };\n if (decision.proceed === false)\n return { reject: decision.rejectionReason ?? \"(delegation rejected)\" };\n return {\n input: decision.modifiedInput ?? input,\n ...(decision.modifiedMaxSteps !== undefined ? { maxSteps: decision.modifiedMaxSteps } : {}),\n };\n}\n\n/**\n * SE14 — replay the child run's stream (a safe post-`wait()` idiom — the run buffers\n * events, `stream()` replays them) and collect every completed tool-call result into\n * a delimited block. Returns `\"\"` when the child ran no completed tool calls. See ADR 0006.\n */\nasync function collectChildToolResults(run: Run): Promise<string> {\n const lines: string[] = [];\n for await (const event of run.stream()) {\n if (event.type === \"tool_call\" && event.status === \"completed\") {\n const rendered =\n typeof event.result === \"string\" ? event.result : JSON.stringify(event.result ?? null);\n lines.push(`${event.name}: ${rendered}`);\n }\n }\n if (lines.length === 0) return \"\";\n return `\\n\\n<subagent-tool-results>\\n${lines.join(\"\\n\")}\\n</subagent-tool-results>`;\n}\n\n/**\n * Build the child agent's `Agent.create` options: the child inherits the parent's\n * apiKey (else `Agent.create` throws \"Missing API key\"), its model (unless the spec\n * overrides it), and — #55 — the parent's plugins (permission gate/guards) so the\n * child's inner tool calls run under the same policy.\n */\nexport function buildChildCreateOptions(\n spec: SubAgentSpec,\n inherited: InheritedCredentials | undefined,\n): AgentOptions {\n // M33 — carry the WHOLE model (a bare id becomes `{ id }`; a ModelSelection with\n // `params` keeps its reasoning effort). The pre-M33 path wrapped `spec.model` as\n // `{ id: spec.model }`, which only worked because spec.model was a string and\n // silently dropped reasoning params.\n const model: string | ModelSelection | undefined =\n spec.model !== undefined\n ? typeof spec.model === \"string\"\n ? { id: spec.model }\n : spec.model\n : inherited?.model;\n // M33 — the role's own `sandbox` wins; when it omits the field, inherit the parent's posture. A role's\n // explicit `sandbox: false` therefore confines-OFF a child of a sandboxed parent (distinct from absent).\n const sandbox = spec.sandbox ?? inherited?.sandbox;\n return {\n ...(inherited?.apiKey !== undefined ? { apiKey: inherited.apiKey } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(sandbox !== undefined ? { local: { sandboxOptions: { enabled: sandbox } } } : {}),\n ...(inherited?.plugins !== undefined ? { plugins: inherited.plugins } : {}),\n systemPrompt: spec.instructions,\n tools: spec.tools ?? [],\n };\n}\n\n/**\n * Create the transient child agent and send the input, composing every forwarded\n * `SendOptions` onto ONE `send` call — SE10 `signal` + SE13 `maxIterations`. Absent\n * every option ⇒ the pre-SE10 single-arg `send(input)` shape. SE14 — when\n * `includeToolResults` is set, append the child's completed tool results. Dispose in `finally`.\n */\nasync function runChildAgent(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n depth: number,\n): Promise<string> {\n // #364 — publish THIS delegation's depth for the whole child run. The child's loop, and every\n // tool it dispatches, runs inside this scope, so a nested subagent reads the real chain length\n // instead of the 0 every construction-time check saw.\n return withDelegationDepth(depth, () =>\n runChildAgentInScope(spec, input, signal, maxSteps, inherited),\n );\n}\n\nasync function runChildAgentInScope(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n): Promise<string> {\n // SE45 cycle 3 — use the registered Agent facade via the DIP seam\n // (agent-factory-registry) instead of a dynamic `import(\"../agent.js\")`.\n // This removes the last madge cycle (a2a/subagent -> agent -> ... -> real-local-run-tools\n // -> a2a/subagent): the facade registers itself at module-init via setAgentFacade,\n // so subagent depends only on the registry port, never on the facade module.\n const agent = await getAgentFacade().create(buildChildCreateOptions(spec, inherited));\n try {\n const sendOptions: {\n signal?: AbortSignal;\n maxIterations?: number;\n origin?: import(\"../types/run.js\").MessageOrigin;\n } = {\n ...(signal !== undefined ? { signal } : {}),\n ...(maxSteps !== undefined ? { maxIterations: maxSteps } : {}),\n // SE3 — a delegated child's turn is initiated by the coordinating parent.\n origin: { kind: \"coordinator\" },\n };\n const run = await agent.send(input, sendOptions);\n const result = await run.wait();\n // Fail-fast, don't swallow (Rule 8): a child that ended in error must surface — otherwise a real\n // failure (e.g. `provider_unresolved`) is hidden behind \"(no response)\" and the parent loops on it.\n if (result.status === \"error\") {\n const cause = (result as { error?: { message?: string } }).error;\n throw new Error(\n `subagent \"${spec.name}\" run failed: ${cause?.message ?? \"unknown error\"}`,\n cause !== undefined ? { cause } : undefined,\n );\n }\n const text = result.result ?? \"(no response)\";\n // SE14 — text-only by default; opt-in appends the child's tool results.\n return spec.includeToolResults === true ? text + (await collectChildToolResults(run)) : text;\n } finally {\n agent.dispose();\n }\n}\n\n/**\n * Best-effort error-path notification: run `onDelegationComplete` with the child's\n * error so the caller can observe the failure. The observer's own throw (sync or\n * async) is suppressed here so it cannot mask the delegation's real error, which the\n * handler re-throws next.\n */\nasync function notifyDelegationError(\n spec: SubAgentSpec,\n input: string,\n error: unknown,\n iteration: number,\n): Promise<void> {\n if (spec.onDelegationComplete === undefined) return;\n try {\n await spec.onDelegationComplete({ input, name: spec.name, error, iteration });\n } catch {\n // Subordinate to `error`; the child's real cause wins.\n }\n}\n\n/**\n * SE12 — apply `messageFilter` (if set) and prepend the filtered supervisor\n * transcript to the delegated input as a role-tagged context preamble. Absent\n * filter OR no messages OR an empty filtered subset ⇒ the original input\n * (isolation-by-default preserved).\n */\nfunction applyMessageFilter(\n spec: SubAgentSpec,\n input: string,\n messages: readonly ToolContextMessage[] | undefined,\n): string {\n if (spec.messageFilter === undefined || messages === undefined) return input;\n const filtered = spec.messageFilter({ messages, input, name: spec.name });\n if (filtered.length === 0) return input;\n const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join(\"\\n\");\n return `Prior conversation:\\n${preamble}\\n\\nTask:\\n${input}`;\n}\n\n/** Run the success-path `onDelegationComplete` hook; appends its `feedback` to the result. */\nasync function applyDelegationComplete(\n spec: SubAgentSpec,\n input: string,\n result: string,\n iteration: number,\n): Promise<string> {\n if (spec.onDelegationComplete === undefined) return result;\n const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });\n return completion?.feedback !== undefined ? result + completion.feedback : result;\n}\n\nfunction defineSubAgent(spec: SubAgentSpec, _parentDepth = 0): CustomTool {\n const maxDepth = spec.maxDelegationDepth ?? 3;\n\n // A caller that threads its own depth still gets the eager failure it always got: a spec that is\n // already too deep to ever be dispatchable is worth refusing at construction. What this check\n // CANNOT see is the runtime chain — constructing a tool says nothing about how deep it will later\n // be invoked — which is why the guard that actually bounds recursion lives at dispatch (#364).\n if (_parentDepth + 1 > maxDepth) {\n throw new MaxDelegationDepthError(_parentDepth + 1, maxDepth);\n }\n\n // Zod for RUNTIME validation of the tool_use input …\n const inputZod = z.object({\n input: z.string().describe(\"Task for the subagent\"),\n });\n // … and a real Draft-7 JSON Schema for the LLM. `CustomTool.inputSchema` is sent\n // to the model verbatim; a raw Zod object would serialize to garbage, so the\n // model emits malformed input that fails `inputZod.parse` and the delegation\n // never runs (the previous bug — the schema and the validator are now distinct).\n const inputSchema: Record<string, unknown> = {\n type: \"object\",\n properties: {\n input: { type: \"string\", description: \"Task for the subagent\" },\n },\n required: [\"input\"],\n additionalProperties: false,\n };\n\n // SE15 — per-instance delegation counter, surfaced as `iteration` on the hook\n // contexts. Incremented once per handler invocation before onDelegationStart.\n let iteration = 0;\n\n const tool: CustomTool = {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (\n rawInput: Record<string, unknown>,\n ctx?: {\n signal?: AbortSignal;\n context?: unknown;\n messages?: readonly ToolContextMessage[];\n },\n ): Promise<string> => {\n const { input: parsed } = inputZod.parse(rawInput);\n // theokit#148 — read the parent's credentials from the RUN's async scope, at dispatch time.\n // They used to be stashed on this tool object by the runtime, which meant any layer that\n // rebuilt the object (e.g. `@theokit/agents`' `toCompiledTool`) silently dropped them and the\n // child failed with `provider_unresolved`. The scope travels with the call, so nothing about\n // the object's shape matters — and two concurrent runs sharing one tool each read their own.\n const inherited = currentInheritedSubAgentCredentials();\n // #364 — the real bound. `currentDelegationDepth()` is the length of the chain that led here,\n // published by each ancestor's `runChildAgent`; a caller-threaded `_parentDepth` still adds to\n // it, so the pre-#364 hand-threaded behaviour is unchanged when the ambient depth is 0.\n const currentDepth = _parentDepth + currentDelegationDepth() + 1;\n if (currentDepth > maxDepth) {\n throw new MaxDelegationDepthError(currentDepth, maxDepth);\n }\n iteration += 1; // SE15 — before onDelegationStart; a rejected delegation still counts.\n // Pin THIS invocation's iteration before any await so a concurrent invocation\n // bumping the shared counter cannot change the value onDelegationComplete /\n // notifyDelegationError observe — they see the same iteration onDelegationStart did.\n const capturedIteration = iteration;\n\n const start = await applyDelegationStart(spec, parsed, capturedIteration);\n if (\"reject\" in start) return start.reject;\n // SE12 — opt-in: forward the filtered supervisor transcript as a preamble.\n const input = applyMessageFilter(spec, start.input, ctx?.messages);\n\n let result: string;\n try {\n // SE13 — apply the optional onDelegationStart maxSteps cap on the child send.\n result = await runChildAgent(\n spec,\n input,\n ctx?.signal,\n start.maxSteps,\n inherited,\n currentDepth,\n );\n } catch (error) {\n // SE11 — notify the completion hook of the failure (best-effort observer),\n // then re-throw the ORIGINAL error (Rule 8: never swallow the delegation's\n // own failure).\n await notifyDelegationError(spec, input, error, capturedIteration);\n throw error;\n }\n return applyDelegationComplete(spec, input, result, capturedIteration);\n },\n };\n\n // theokit#148 — nothing is installed on the tool. The credentials arrive through the run's async\n // scope (see `internal/runtime/concurrency/subagent-credentials.ts`), so there is no extra\n // property for a normalizing layer to drop.\n return tool;\n}\n\n/** SE36 — `SubAgent.create` replaces `defineSubAgent` (ADR 0015). @public */\nexport class SubAgent {\n private constructor() {}\n static create(spec: SubAgentSpec, parentDepth = 0): CustomTool {\n return defineSubAgent(spec, parentDepth);\n }\n}\n\n/**\n * Convert a parent's declarative `agents` map ({@link AgentDefinition} per key)\n * into delegation tools for the LOCAL runtime — the counterpart of the\n * cloud/fixture subagent wiring. Each child inherits the parent's `apiKey`/model\n * from the CALL, not from the tool object: `inheritSubAgentCredentials` used to\n * attach them to the tool, and any layer that rebuilt that object dropped them —\n * including the SDK's own rebuild (theokit#148). Credentials now ride the\n * dispatch, so a rebuilt tool cannot lose them. `def.model` overrides the model\n * (`\"inherit\"` keeps the parent's), and `def.tools` scopes the child to that\n * subset of the parent's tools (absent → the parent's full toolset, per the\n * `AgentDefinition.tools` contract).\n *\n * M33 — per-subagent `model` (with reasoning `params`) and `sandbox` are now wired\n * into local delegation: each is carried onto the {@link SubAgentSpec} and applied to\n * the child in {@link buildChildCreateOptions}. `\"inherit\"` (or an absent field) keeps\n * the parent's value. Per-subagent `mcp` is rejected at load (see subagents-loader) —\n * resolving server names→config on the local path is a follow-up.\n *\n * @internal\n */\nexport function subAgentToolsFromDefinitions(\n agents: Record<string, AgentDefinition>,\n parentTools: readonly CustomTool[],\n): CustomTool[] {\n return Object.entries(agents).map(([name, def]) => {\n const whitelist =\n Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : undefined;\n const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;\n return defineSubAgent({\n name,\n description: def.description,\n instructions: def.prompt,\n // Carry the FULL ModelSelection (id + reasoning params), not just the id, so\n // per-subagent reasoning effort survives to buildChildCreateOptions.\n ...(def.model !== undefined && def.model !== \"inherit\" ? { model: def.model } : {}),\n ...(def.sandbox !== undefined ? { sandbox: def.sandbox } : {}),\n tools: [...childTools],\n });\n });\n}\n"]}
|
|
@@ -15,5 +15,5 @@ exports.hydratedKeys = hydratedKeys;
|
|
|
15
15
|
exports.invalidateSessionCache = invalidateSessionCache;
|
|
16
16
|
exports.sessions = sessions;
|
|
17
17
|
exports.transcriptKey = transcriptKey;
|
|
18
|
-
//# sourceMappingURL=chunk-
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
18
|
+
//# sourceMappingURL=chunk-4OTIXDMU.cjs.map
|
|
19
|
+
//# sourceMappingURL=chunk-4OTIXDMU.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/session-cache.ts"],"names":[],"mappings":";;;AAgBO,IAAM,QAAA,uBAAe,GAAA;AACrB,IAAM,YAAA,uBAAmB,GAAA;AAGzB,SAAS,aAAA,CAAc,KAAa,OAAA,EAAyB;AAClE,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA;AAC3B;
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/session-cache.ts"],"names":[],"mappings":";;;AAgBO,IAAM,QAAA,uBAAe,GAAA;AACrB,IAAM,YAAA,uBAAmB,GAAA;AAGzB,SAAS,aAAA,CAAc,KAAa,OAAA,EAAyB;AAClE,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA;AAC3B;AAOO,SAAS,sBAAA,CAAuB,KAAa,OAAA,EAAuB;AACzE,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,YAAA,CAAa,MAAA,CAAO,aAAA,CAAc,GAAA,EAAK,OAAO,CAAC,CAAA;AACjD","file":"chunk-4OTIXDMU.cjs","sourcesContent":["import type { SessionMessage } from \"./session-types.js\";\n\n/**\n * The in-memory session cache — in a LEAF module, on purpose.\n *\n * The state and the invalidator lived in `agent-session.ts`, and `compact-session.ts` imported\n * `invalidateSessionCache` from there — while `agent-session.ts` imported `autoCompactIfNeeded`\n * back. The cycle was broken at runtime (the return edge is a dynamic `await import()`), but the detector\n * counts the dynamic edge, and counting a dynamic import as a cycle makes the gate impossible to satisfy\n * without abandoning the canonical cycle-breaking technique.\n *\n * This state's natural owner was never `agent-session.ts`: they are two process-wide maps that both\n * modules read. Extracting them into a leaf removes the cycle under ANY detector, with no tool\n * policy and without changing a line of behavior — the same `Map`/`Set` instances remain\n * the only ones in the process, because an ES module is a singleton.\n */\nexport const sessions = new Map<string, SessionMessage[]>();\nexport const hydratedKeys = new Set<string>();\n\n/** The per-(cwd, agentId) transcript key for cache/hydration bookkeeping. */\nexport function transcriptKey(cwd: string, agentId: string): string {\n return `${cwd}::${agentId}`;\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\nexport function invalidateSessionCache(cwd: string, agentId: string): void {\n sessions.delete(agentId);\n hydratedKeys.delete(transcriptKey(cwd, agentId));\n}\n"]}
|
|
@@ -40,5 +40,5 @@ exports.AuthCallbackError = AuthCallbackError;
|
|
|
40
40
|
exports.AuthCancelledError = AuthCancelledError;
|
|
41
41
|
exports.AuthConfigError = AuthConfigError;
|
|
42
42
|
exports.AuthProviderNotFoundError = AuthProviderNotFoundError;
|
|
43
|
-
//# sourceMappingURL=chunk-
|
|
44
|
-
//# sourceMappingURL=chunk-
|
|
43
|
+
//# sourceMappingURL=chunk-52NKC5HT.cjs.map
|
|
44
|
+
//# sourceMappingURL=chunk-52NKC5HT.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/auth/errors.ts"],"names":[],"mappings":";;;AAUO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvB,IAAA,GAAO,iBAAA;AAAA,EAChB,IAAA;AAAA,EAET,WAAA,CAAY,MAAc,OAAA,EAAiB;AACzC,IAAA,KAAA,CAAM,CAAA,CAAA,EAAI,IAAI,CAAA,EAAA,EAAK,OAAO,CAAA,CAAE,CAAA;AAC5B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAMO,IAAM,yBAAA,GAAN,cAAwC,KAAA,CAAM;AAAA,EACjC,IAAA,GAAO,2BAAA;AAAA,EAChB,YAAA;AAAA,EAET,YAAY,YAAA,EAAsB;AAChC,IAAA,KAAA;AAAA,MACE,6BAA6B,YAAY,CAAA,mDAAA;AAAA,KAC3C;AACA,IAAA,IAAA,CAAK,YAAA,GAAe,YAAA;AAAA,EACtB;AACF;AAcO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAe,mBAAA;AAAA,EACxB,IAAA;AAAA,EAET,WAAA,CAAY,MAAc,OAAA,EAAkB;AAC1C,IAAA,KAAA,CAAM,OAAA,IAAW,CAAA,sBAAA,EAAyB,IAAI,CAAA,CAAE,CAAA;AAChD,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAUO,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA,EACxB,gBAAA;AAAA,EAET,YAAY,gBAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,uBAAA,EAAyB,oBAAoB,mCAAmC,CAAA;AACtF,IAAA,IAAA,CAAK,gBAAA,GAAmB,gBAAA;AAAA,EAC1B;AACF","file":"chunk-52NKC5HT.cjs","sourcesContent":["/**\n * Typed error classes — `@theokit/sdk/server/auth`.\n *\n * Plan T1.2 + v1.1 EC-1 (AuthCancelledError for OAuth provider error response RFC 6749 §4.1.2.1).\n */\n\n/**\n * Thrown at `defineAuth()` time when configuration is invalid\n * (e.g., duplicate provider name, invalid email shape per EC-V1-12).\n */\nexport class AuthConfigError extends Error {\n override readonly name = \"AuthConfigError\";\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(`[${code}] ${message}`);\n this.code = code;\n }\n}\n\n/**\n * Thrown at `startSignIn(providerName, ...)` or `finishSignIn(providerName, ...)`\n * when the named provider is not registered in `providers[]`.\n */\nexport class AuthProviderNotFoundError extends Error {\n override readonly name = \"AuthProviderNotFoundError\";\n readonly providerName: string;\n\n constructor(providerName: string) {\n super(\n `Auth provider not found: '${providerName}'. Register it in defineAuth({ providers: [...] }).`,\n );\n this.providerName = providerName;\n }\n}\n\n/**\n * Thrown during OAuth callback handling for state mismatches, expired\n * transactions, missing query params, or provider 4xx/5xx errors.\n *\n * Typed `code` field lets consumers branch on cause:\n * - 'oauth_transaction_expired' — cookie tx > 10min old (per ADR D5)\n * - 'oauth_state_mismatch' — query state ≠ cookie state (CSRF defense per RFC 6749 §10.12)\n * - 'oauth_provider_error' — non-access_denied error in callback URL\n * - 'oauth_token_exchange_failed' — provider rejected code-for-tokens swap\n * - 'oauth_userinfo_failed' — userinfo endpoint returned error\n * - 'oauth_missing_code_or_state' — required query params absent\n */\nexport class AuthCallbackError extends Error {\n override readonly name: string = \"AuthCallbackError\";\n readonly code: string;\n\n constructor(code: string, message?: string) {\n super(message ?? `OAuth callback error: ${code}`);\n this.code = code;\n }\n}\n\n/**\n * Per v1.1 EC-1 MUST FIX — typed subclass of AuthCallbackError for the\n * specific case where user declined consent at provider screen.\n *\n * OAuth 2.0 RFC 6749 §4.1.2.1: provider redirects with `?error=access_denied`.\n * Apps can catch this distinctly from network/server errors to render\n * \"Login cancelled — try again\" UX instead of opaque \"callback failed\".\n */\nexport class AuthCancelledError extends AuthCallbackError {\n override readonly name: string = \"AuthCancelledError\";\n readonly errorDescription?: string;\n\n constructor(errorDescription?: string) {\n super(\"user_declined_consent\", errorDescription ?? \"User declined consent at provider\");\n this.errorDescription = errorDescription;\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
|
|
4
|
+
var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
|
|
5
5
|
var async_hooks = require('async_hooks');
|
|
6
6
|
var fs = require('fs');
|
|
7
7
|
var promises = require('fs/promises');
|
|
@@ -17,7 +17,7 @@ var warned = /* @__PURE__ */ new Set();
|
|
|
17
17
|
function warnOnce(key, message) {
|
|
18
18
|
if (warned.has(key)) return;
|
|
19
19
|
warned.add(key);
|
|
20
|
-
|
|
20
|
+
chunkNUKRL3I6_cjs.diag(`${message}
|
|
21
21
|
`);
|
|
22
22
|
}
|
|
23
23
|
async function loadHookConfig(cwd) {
|
|
@@ -35,7 +35,7 @@ async function loadHookConfig(cwd) {
|
|
|
35
35
|
try {
|
|
36
36
|
raw = await promises.readFile(jsonPath, "utf8");
|
|
37
37
|
} catch (cause) {
|
|
38
|
-
throw new
|
|
38
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {
|
|
39
39
|
code: "hooks_read_error",
|
|
40
40
|
cause
|
|
41
41
|
});
|
|
@@ -44,7 +44,7 @@ async function loadHookConfig(cwd) {
|
|
|
44
44
|
try {
|
|
45
45
|
parsed = JSON.parse(raw);
|
|
46
46
|
} catch (cause) {
|
|
47
|
-
throw new
|
|
47
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {
|
|
48
48
|
code: "hooks_json_invalid",
|
|
49
49
|
cause
|
|
50
50
|
});
|
|
@@ -53,7 +53,7 @@ async function loadHookConfig(cwd) {
|
|
|
53
53
|
}
|
|
54
54
|
function asRecord(value, path, where) {
|
|
55
55
|
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
56
|
-
throw new
|
|
56
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {
|
|
57
57
|
code: "hooks_json_invalid"
|
|
58
58
|
});
|
|
59
59
|
}
|
|
@@ -61,7 +61,7 @@ function asRecord(value, path, where) {
|
|
|
61
61
|
}
|
|
62
62
|
function asArray(value, path, where) {
|
|
63
63
|
if (!Array.isArray(value)) {
|
|
64
|
-
throw new
|
|
64
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {
|
|
65
65
|
code: "hooks_json_invalid"
|
|
66
66
|
});
|
|
67
67
|
}
|
|
@@ -99,13 +99,13 @@ function flattenEventGroups(groups, path, ccEvent) {
|
|
|
99
99
|
function parseClaudeCodeCommand(raw, matcher, path, ccEvent) {
|
|
100
100
|
const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);
|
|
101
101
|
if (cmd.type !== "command") {
|
|
102
|
-
throw new
|
|
102
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(
|
|
103
103
|
`hooks: only { "type": "command" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,
|
|
104
104
|
{ code: "hooks_unsupported_type" }
|
|
105
105
|
);
|
|
106
106
|
}
|
|
107
107
|
if (typeof cmd.command !== "string" || cmd.command.length === 0) {
|
|
108
|
-
throw new
|
|
108
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`hooks: "command" must be a non-empty string in ${path}`, {
|
|
109
109
|
code: "hooks_invalid_command"
|
|
110
110
|
});
|
|
111
111
|
}
|
|
@@ -137,5 +137,5 @@ exports.loadHookConfig = loadHookConfig;
|
|
|
137
137
|
exports.warnOnce = warnOnce;
|
|
138
138
|
exports.warnPersonalitySwitchInsideFork = warnPersonalitySwitchInsideFork;
|
|
139
139
|
exports.withPersonalityContext = withPersonalityContext;
|
|
140
|
-
//# sourceMappingURL=chunk-
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
//# sourceMappingURL=chunk-53CBTBWO.cjs.map
|
|
141
|
+
//# sourceMappingURL=chunk-53CBTBWO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","join","existsSync","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAYA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAAuB;AAC3D,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAAA,sBAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAcA,eAAsB,eAAe,GAAA,EAAkC;AACrE,EAAA,MAAM,QAAA,GAAWC,SAAA,CAAK,GAAA,EAAK,UAAA,EAAY,YAAY,CAAA;AAEnD,EAAA,IAAI,CAACC,aAAA,CAAW,QAAQ,CAAA,EAAG;AACzB,IAAA,IAAIA,cAAWD,SAAA,CAAK,GAAA,EAAK,UAAA,EAAY,OAAO,CAAC,CAAA,EAAG;AAC9C,MAAA,QAAA;AAAA,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AAI,OAAA,EAAQ;AAC/C,EAAA,IAAI,OAAA,KAAY,MAAA,EAAW,EAAA,CAAG,OAAA,GAAU,OAAA;AACxC,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,IAAY,GAAA,CAAI,UAAU,CAAA,EAAG;AACtD,IAAA,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAU,GAAI,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;ACrKA,IAAM,OAAA,GAAU,IAAIC,6BAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-665SFFFR.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","join","existsSync","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAY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":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from './chunk-
|
|
2
|
-
import { redactSecrets } from './chunk-
|
|
1
|
+
import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from './chunk-IDCKSLYH.js';
|
|
2
|
+
import { redactSecrets } from './chunk-T7XEKOVW.js';
|
|
3
3
|
|
|
4
4
|
// src/internal/error-mappers/shared.ts
|
|
5
5
|
var RAW_MAX_BYTES = 2048;
|
|
@@ -96,5 +96,5 @@ function formatMessage(providerId, status, code) {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
export { buildErrorMetadata, mapOpenAICompatibleError };
|
|
99
|
-
//# sourceMappingURL=chunk-
|
|
100
|
-
//# sourceMappingURL=chunk-
|
|
99
|
+
//# sourceMappingURL=chunk-5JLFFPCH.js.map
|
|
100
|
+
//# sourceMappingURL=chunk-5JLFFPCH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":[],"mappings":";;;;AAaA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACp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IACE,OAAA,CAAQ,QAAA,CAAS,iBAAiB,CAAA,IAClC,OAAA,CAAQ,QAAA,CAAS,mBAAmB,CAAA,IACpC,OAAA,CAAQ,QAAA,CAAS,eAAe,CAAA,EAChC;AACA,IAAA,OAAO,mBAAA;AAAA,EACT;AAMA,EAAA,IACE,MAAA,KAAW,OACX,OAAA,CAAQ,QAAA,CAAS,oBAAoB,CAAA,IACrC,OAAA,CAAQ,QAAA,CAAS,gBAAgB,CAAA,EACjC;AACA,IAAA,OAAO,gBAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK,OAAO,aAAA;AAC7C,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,YAAA;AAC3B,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,SAAA;AAC3B,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,iBAAA;AAC3B,EAAA,IAAI,MAAA,IAAU,GAAA,IAAO,MAAA,GAAS,GAAA,EAAK,OAAO,cAAA;AAC1C,EAAA,OAAO,SAAA;AACT;AAEA,SAAS,aAAA,CAAc,UAAA,EAAoB,MAAA,EAAgB,IAAA,EAAyB;AAClF,EAAA,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AACzD","file":"chunk-FFM3SJTQ.js","sourcesContent":["/**\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\nconst RAW_MAX_BYTES = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}…`;\n return redactSecrets(truncated);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — OpenAI 402 / OpenRouter \"Insufficient credits\" / `insufficient_quota`\n // body code now flow to canonical `quota_exceeded`. Pre-T3.7 we returned\n // `invalid_request` because the ErrorCode union lacked the bucket; T3.7\n // added it. AgentRunError.code (KnownAgentRunErrorCode, post-T1.1) has\n // always carried this value; this fix closes the metadata.code surface.\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(providerId: string, status: number, code: ErrorCode): string {\n return `${providerId} API error: ${code} (HTTP ${status})`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":[],"mappings":";;;;AAaA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,KAAK,CAAA,EAAG,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAEpD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA,SAAU,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,EAAI,IAAK,GAAI,CAAC,CAAA;AACvF,EAAA,OAAO,MAAA;AACT;AAkBO,SAAS,YAAY,IAAA,EAAwB;AAClD,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,IAAA,KAAS,MAAA,EAAW,OAAO,MAAA;AAChD,EAAA,MAAM,IAAI,OAAO,IAAA,KAAS,WAAW,IAAA,GAAO,IAAA,CAAK,UAAU,IAAI,CAAA;AAC/D,EAAA,MAAM,SAAA,GAAY,CAAA,CAAE,MAAA,IAAU,aAAA,GAAgB,CAAA,GAAI,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,aAAa,CAAC,CAAA,MAAA,CAAA;AA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,EAAA,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AACzD","file":"chunk-5JLFFPCH.js","sourcesContent":["/**\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\nconst RAW_MAX_BYTES = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}…`;\n return redactSecrets(truncated);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — OpenAI 402 / OpenRouter \"Insufficient credits\" / `insufficient_quota`\n // body code now flow to canonical `quota_exceeded`. Pre-T3.7 we returned\n // `invalid_request` because the ErrorCode union lacked the bucket; T3.7\n // added it. AgentRunError.code (KnownAgentRunErrorCode, post-T1.1) has\n // always carried this value; this fix closes the metadata.code surface.\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(providerId: string, status: number, code: ErrorCode): string {\n return `${providerId} API error: ${code} (HTTP ${status})`;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { findGitRoot, DEFAULT_DISCOVERY_SPECS, walkUpForFile, walkUpForGlob } from './chunk-
|
|
1
|
+
import { findGitRoot, DEFAULT_DISCOVERY_SPECS, walkUpForFile, walkUpForGlob } from './chunk-GTKFV7O5.js';
|
|
2
2
|
import { insideRoot } from './chunk-RIAM53CP.js';
|
|
3
3
|
import { homedir } from 'os';
|
|
4
4
|
import { dirname, relative, resolve, join, isAbsolute } from 'path';
|
|
@@ -329,5 +329,5 @@ async function loadPlainMarkdownSource(spec, path, id, opts, gitRoot) {
|
|
|
329
329
|
}
|
|
330
330
|
|
|
331
331
|
export { DEFAULT_MAX_BYTES_PER_FILE, parseRules, resolveImports, runDiscovery, shouldActivateRule, truncateWithMarker };
|
|
332
|
-
//# sourceMappingURL=chunk-
|
|
333
|
-
//# sourceMappingURL=chunk-
|
|
332
|
+
//# sourceMappingURL=chunk-5PHVENFV.js.map
|
|
333
|
+
//# sourceMappingURL=chunk-5PHVENFV.js.map
|