@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,5 +1,5 @@
|
|
|
1
1
|
import { atOrInsideRoot } from './chunk-RIAM53CP.js';
|
|
2
|
-
import { ConfigurationError } from './chunk-
|
|
2
|
+
import { ConfigurationError } from './chunk-IDCKSLYH.js';
|
|
3
3
|
import { createHash } from 'crypto';
|
|
4
4
|
import { realpathSync, lstatSync, readlinkSync } from 'fs';
|
|
5
5
|
import { resolve, dirname } from 'path';
|
|
@@ -41,14 +41,18 @@ function safePathJoin(base, ...parts) {
|
|
|
41
41
|
}
|
|
42
42
|
return target;
|
|
43
43
|
}
|
|
44
|
-
function
|
|
44
|
+
function firstControlCharLabel(input) {
|
|
45
45
|
for (let i = 0; i < input.length; i++) {
|
|
46
46
|
const code = input.charCodeAt(i);
|
|
47
47
|
if (code === 0 || code >= 1 && code <= 31 || code === 127) {
|
|
48
|
-
|
|
49
|
-
throw new PathTraversalError(`${role}: ${input}`, label);
|
|
48
|
+
return code === 0 ? "<nul-byte>" : `<control-char-0x${code.toString(16)}>`;
|
|
50
49
|
}
|
|
51
50
|
}
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
function rejectNulAndControlChars(input, role) {
|
|
54
|
+
const label = firstControlCharLabel(input);
|
|
55
|
+
if (label !== void 0) throw new PathTraversalError(`${role}: ${input}`, label);
|
|
52
56
|
}
|
|
53
57
|
function assertNoSymlinkEscape(path, base) {
|
|
54
58
|
rejectNulAndControlChars(path, "path");
|
|
@@ -186,7 +190,12 @@ function sanitizeIdentifier(input, options) {
|
|
|
186
190
|
code: "invalid_identifier"
|
|
187
191
|
});
|
|
188
192
|
}
|
|
189
|
-
|
|
193
|
+
const controlChar = firstControlCharLabel(input);
|
|
194
|
+
if (controlChar !== void 0) {
|
|
195
|
+
throw new ConfigurationError(`Identifier contains ${controlChar}: "${input}"`, {
|
|
196
|
+
code: "invalid_identifier"
|
|
197
|
+
});
|
|
198
|
+
}
|
|
190
199
|
if (!IDENTIFIER_PATTERN.test(input)) {
|
|
191
200
|
throw new ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
|
|
192
201
|
code: "invalid_identifier"
|
|
@@ -209,5 +218,5 @@ function safeFilenameForId(id, options) {
|
|
|
209
218
|
}
|
|
210
219
|
|
|
211
220
|
export { ForbiddenPathError, PathTraversalError, assertNoSymlinkEscape, isForbiddenPath, safeFilenameForId, safePathJoin, sanitizeIdentifier, validateArtifactPath };
|
|
212
|
-
//# sourceMappingURL=chunk-
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
221
|
+
//# sourceMappingURL=chunk-QARJGQSA.js.map
|
|
222
|
+
//# sourceMappingURL=chunk-QARJGQSA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/security/path-guard.ts"],"names":[],"mappings":";;;;;;AAgCO,IAAM,kBAAA,GAAN,cAAiC,kBAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,WAAA,CAAY,OAAe,YAAA,EAAsB;AAC/C,IAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,KAAK,CAAA,QAAA,EAAM,YAAY,CAAA,CAAA,EAAI;AAAA,MAC1D,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACF;AAYO,IAAM,kBAAA,GAAN,cAAiC,kBAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA;AAAA,MACE,SAAS,IAAI,CAAA,qFAAA,CAAA;AAAA,MACb;AAAA,QACE,IAAA,EAAM;AAAA;AACR,KACF;AAAA,EACF;AACF;AAeA,SAAS,QAAA,CAAS,QAAgB,IAAA,EAAuB;AASvD,EAAA,OAAO,cAAA,CAAe,QAAQ,IAAI,CAAA;AACpC;AAUO,SAAS,YAAA,CAAa,SAAiB,KAAA,EAAyB;AACrE,EAAA,IAAI,SAAS,EAAA,EAAI;AACf,IAAA,MAAM,IAAI,MAAM,sCAAsC,CAAA;AAAA,EACxD;AAKA,EAAA,wBAAA,CAAyB,MAAM,MAAM,CAAA;AACrC,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,wBAAA,CAAyB,MAAM,cAAc,CAAA;AAAA,EAC/C;AACA,EAAA,MAAM,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AA;AAAA,EACT;AACA,EAAA,OAAO,CAAA,EAAA,EAAK,UAAA,CAAW,QAAQ,CAAA,CAAE,MAAA,CAAO,EAAE,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACxE","file":"chunk-QARJGQSA.js","sourcesContent":["/**\n * Canonical path-guard module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { atOrInsideRoot } from \"../runtime/context/path-containment.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Is `target` the same as `base`, or strictly under it?\n *\n * The prefix must not double the separator. `resolve` strips a trailing `sep` from every base\n * EXCEPT the filesystem root, where `resolve(sep) === sep`; there `base + sep` would be `//`, which\n * no absolute path starts with, so a root base rejected EVERY path (#149). Only the root takes that\n * branch — for any other base the prefix is unchanged, so containment is not weakened.\n *\n * Both containment checks in this module go through here: they had the same defect and were fixed\n * one at a time, which is exactly how the two drifted apart in the first place.\n *\n * Both arguments MUST already be resolved absolute paths.\n */\nfunction isInside(target: string, base: string): boolean {\n // B-117 — compared after symlink resolution, via the shared rule. A prefix test judges a link by\n // its NAME: `<base>/link/x` where `link` points outside is lexically inside and physically not.\n // Measured reachable from the plugin manager and the MCP client before this was changed.\n //\n // The root itself stays allowed, which `insideRoot` alone does not answer: it returns false for\n // `target === base` (correct for its own caller, wrong here, where `safePathJoin(base)` with no\n // parts must return `base`). Kept as an explicit second clause rather than by weakening the\n // shared rule for everyone.\n return atOrInsideRoot(target, base);\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n // T5.5 — NUL byte + C0/DEL control char rejection at the boundary.\n // Apply before path resolution so a malicious input never reaches\n // `resolve` (which on some platforms behaved unexpectedly with NUL\n // and in N-API callers historically silently truncated).\n rejectNulAndControlChars(base, \"base\");\n for (const part of parts) {\n rejectNulAndControlChars(part, \"path segment\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (!isInside(target, baseResolved)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * T5.5 — the operator-legible label for the first NUL (`\\x00`), C0 control char (`\\x01-\\x1F`) or\n * DEL (`\\x7F`) in `input`, or `undefined` when it carries none. Centralizes the scan so every\n * public path-guard / sanitize entrypoint shares one definition of \"control character\".\n *\n * Detection is separated from the throw so the two callers can share the scan and the precise\n * diagnostic while each raising the error ITS OWN contract documents (#368) — a path guard reports\n * a traversal, an identifier validator reports an invalid identifier. Before that split both threw\n * `PathTraversalError`, which made an identifier validator's error class depend on the bytes of the\n * input it was handed.\n *\n * @internal\n */\nfunction firstControlCharLabel(input: string): string | undefined {\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n return code === 0x00 ? \"<nul-byte>\" : `<control-char-0x${code.toString(16)}>`;\n }\n }\n return undefined;\n}\n\n/**\n * Reject any path-shaped input carrying a NUL or control character, as `PathTraversalError` — the\n * same shape as every other path-shape rejection, so callers do not learn a second error class.\n *\n * @internal\n */\nfunction rejectNulAndControlChars(input: string, role: string): void {\n const label = firstControlCharLabel(input);\n if (label !== undefined) throw new PathTraversalError(`${role}: ${input}`, label);\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // T5.5 — reject NUL / control chars before any FS call (a NUL byte\n // in the path used to silently truncate at the C boundary on legacy\n // libc — defense in depth even on modern Node).\n rejectNulAndControlChars(path, \"path\");\n rejectNulAndControlChars(base, \"base\");\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (!isInside(resolved, baseResolved)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n// T5.6 — top-level credential dot-dirs / dot-files. Matching against\n// the FIRST path segment (lowercase). Adding any entry here costs a\n// CHANGELOG note + an explicit case-fold test (entries are lowercased\n// at module load).\nconst SENSITIVE_FIRST_SEGMENTS = new Set([\n \".ssh\",\n \".aws\",\n \".docker\",\n \".kube\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — credential basenames blocked at ANY depth (lowercase). Catches\n// the developer-laptop case where an agent recurses into a subdir.\nconst SENSITIVE_BASENAMES = new Set([\n \"id_rsa\",\n \"id_ed25519\",\n \"id_ecdsa\",\n \"id_dsa\",\n \"authorized_keys\",\n \"known_hosts\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — extension suffixes blocked at ANY depth (lowercase). Covers\n// the entire `*.pem` / `*.key` private-material family.\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // T5.6 — lowercase normalization defeats case-only bypass on\n // case-insensitive filesystems (Windows/macOS-default) where `.ENV`\n // and `.env` map to the same inode but a case-sensitive string\n // check passes the former.\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").toLowerCase();\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n if (isForbiddenFirstSegment(segments[0]!)) return true;\n if (isForbiddenBasename(segments[segments.length - 1]!)) return true;\n return false;\n}\n\nfunction isForbiddenFirstSegment(first: string): boolean {\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n if (first === \".git\" || first === \"node_modules\" || first === \".theo\") return true;\n return SENSITIVE_FIRST_SEGMENTS.has(first);\n}\n\nfunction isForbiddenBasename(basename: string): boolean {\n if (LOCK_FILES.has(basename)) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n for (const suffix of SENSITIVE_SUFFIXES) {\n if (basename.endsWith(suffix)) return true;\n }\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * T1.4 — validate a relative artifact path string BEFORE it is used to look\n * up a fixture or to fetch from PaaS. Rejects every well-known traversal\n * vector at the boundary, throwing `PathTraversalError`.\n *\n * Vectors rejected:\n * - classic `..` parent-directory traversal (any segment).\n * - backslash separators (Windows-style `..\\\\windows`).\n * - URL-encoded `%2e%2e` / `%2E%2E` (double-decoded traversal).\n * - NUL byte injection (`\\x00`).\n * - Windows drive letter prefix (`C:`, `D:\\\\...`).\n * - Home-tilde expansion (`~/`, `~root/...`).\n * - Absolute paths starting with `/`.\n *\n * Does NOT touch the filesystem — the call is shape-only. Live symlink\n * traversal protection happens via `assertNoSymlinkEscape` at the FS-resolve\n * boundary.\n *\n * @param input - Caller-supplied artifact path.\n * @throws `PathTraversalError` on any rejection.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/security` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function validateArtifactPath(input: string): void {\n rejectKnownPrefixVectors(input);\n const normalized = decodeAndNormalize(input);\n rejectParentTraversal(input, normalized);\n}\n\nfunction rejectKnownPrefixVectors(input: string): void {\n if (input.includes(\"\\x00\")) {\n throw new PathTraversalError(input, \"<nul-byte>\");\n }\n if (input.startsWith(\"/\") || input.startsWith(\"~\")) {\n throw new PathTraversalError(input, input);\n }\n if (/^[A-Za-z]:[\\\\/]?/.test(input)) {\n throw new PathTraversalError(input, input);\n }\n}\n\nfunction decodeAndNormalize(input: string): string {\n // URL-encoded traversal — 2 passes catches `%252e%252e`.\n // Malformed sequences (decodeURIComponent throws) are themselves a rejection.\n let decoded = input;\n for (let i = 0; i < 2; i += 1) {\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n throw new PathTraversalError(input, \"<malformed-url-encoding>\");\n }\n }\n // Normalize backslash to forward slash before segment-walking.\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction rejectParentTraversal(input: string, normalized: string): void {\n for (const segment of normalized.split(\"/\")) {\n if (segment === \"..\" || segment === \"..%00\") {\n throw new PathTraversalError(input, normalized);\n }\n }\n // Defense in depth: literal `..` anywhere in the normalized string.\n if (normalized.includes(\"..\")) {\n throw new PathTraversalError(input, normalized);\n }\n}\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * ONE error class leaves this function: `ConfigurationError` with code\n * `invalid_identifier`, for every rejection — length out of range, a path\n * separator, `..`, a space, a leading `-`, and a NUL / C0 control char / DEL\n * alike. A caller can branch on that code and know it has covered the whole\n * rejection surface.\n *\n * Before #368 the control-char branch threw `PathTraversalError` instead, which\n * made the error CLASS a function of the attacker's bytes; the message still names\n * the offending byte, which is the part that was worth keeping.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on every rejection.\n */\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n // T5.5 — explicit NUL / control char rejection ahead of the generic pattern check. The\n // IDENTIFIER_PATTERN regex already excludes these (they are not in `[a-z0-9\\-_]`); naming the\n // offending byte gives operators a precise diagnostic instead of the generic \"invalid characters\"\n // message, which is what makes a prompt-injection trace legible (Rule 3).\n //\n // #368 — the diagnostic used to arrive as a `PathTraversalError`, because the branch reused\n // `safePathJoin`'s thrower. That made the error CLASS a function of the attacker's bytes: a\n // caller branching on the documented `invalid_identifier` rethrew for any input carrying a\n // control char, so a rejection surfaced as a 500 and the 400/500 split became an oracle. The\n // detection is shared; the error each contract documents is not.\n const controlChar = firstControlCharLabel(input);\n if (controlChar !== undefined) {\n throw new ConfigurationError(`Identifier contains ${controlChar}: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n\n/**\n * Convert ANY opaque id (agent id, run id, conversation id, namespace, email,\n * arbitrary string) into a deterministic, filesystem-safe filename component.\n *\n * Unlike {@link sanitizeIdentifier} (which THROWS on non-conforming input),\n * this is a total function: it NEVER throws on a non-empty string. It returns\n * the lowercased id verbatim when it already matches the safe grammar\n * `^[a-z0-9][a-z0-9-_]*$` and fits `maxLen` (so UUIDs, hashes, and slugs stay\n * human-readable), otherwise a deterministic `h-<16 hex>` sha256 token\n * (collision-resistant and always a valid filename). The output charset is\n * always `[a-z0-9_-]`, safe as a literal path segment on every filesystem.\n *\n * @param id - any opaque identifier (must be a non-empty string)\n * @param options.maxLen - max length for the passthrough branch (default 128).\n * Ids longer than this are hashed; the hash token itself is always short.\n * @throws ConfigurationError (code `invalid_filename_id`) only on empty input.\n *\n * @example\n * safeFilenameForId(\"550e8400-e29b-41d4-a716-446655440000\") // passthrough\n * safeFilenameForId(\"user@example.com\") // \"h-<16hex>\"\n *\n */\nexport function safeFilenameForId(id: string, options?: { maxLen?: number }): string {\n if (id.length === 0) {\n throw new ConfigurationError(\"Filename id must be a non-empty string\", {\n code: \"invalid_filename_id\",\n });\n }\n const maxLen = options?.maxLen ?? 128;\n const lower = id.toLowerCase();\n if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {\n return lower;\n }\n return `h-${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 16)}`;\n}\n"]}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkWJVHMTKB_cjs = require('./chunk-WJVHMTKB.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
|
|
5
5
|
var module$1 = require('module');
|
|
6
6
|
|
|
7
7
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
8
8
|
var cachedZ;
|
|
9
9
|
function requireZod() {
|
|
10
10
|
if (cachedZ !== void 0) return cachedZ;
|
|
11
|
-
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-
|
|
11
|
+
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-QDED6YO6.cjs', document.baseURI).href)));
|
|
12
12
|
let mod;
|
|
13
13
|
try {
|
|
14
14
|
mod = r("zod");
|
|
15
15
|
} catch (cause) {
|
|
16
|
-
throw new
|
|
16
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(
|
|
17
17
|
'Structured output requires the optional peer dependency `zod`. Add `"zod": "^3.25.0 || ^4.0.0"` to your package.json and reinstall.',
|
|
18
18
|
{ code: "zod_not_installed", cause }
|
|
19
19
|
);
|
|
@@ -78,5 +78,5 @@ exports.disposeAndDeleteTransient = disposeAndDeleteTransient;
|
|
|
78
78
|
exports.extractUsage = extractUsage;
|
|
79
79
|
exports.makeOutputTool = makeOutputTool;
|
|
80
80
|
exports.setupStructuredOutput = setupStructuredOutput;
|
|
81
|
-
//# sourceMappingURL=chunk-
|
|
82
|
-
//# sourceMappingURL=chunk-
|
|
81
|
+
//# sourceMappingURL=chunk-QDED6YO6.cjs.map
|
|
82
|
+
//# sourceMappingURL=chunk-QDED6YO6.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/structured-output-helpers.ts"],"names":["createRequire","ConfigurationError","toJsonSchema"],"mappings":";;;;;;;AAoBA,IAAI,OAAA;AAMG,SAAS,UAAA,GAAkC;AAChD,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAClC,EAAA,MAAM,CAAA,GAAIA,sBAAA,CAAc,oQAAe,CAAA;AACvC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,EAAE,KAAK,CAAA;AAAA,EACf,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAIC,oCAAA;AAAA,MACR,qIAAA;AAAA,MAEA,EAAE,IAAA,EAAM,mBAAA,EAAqB,KAAA;AAAM,KACrC;AAAA,EACF;AACA,EAAA,OAAA,GAAW,IAAI,CA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A,CAAA;AAClB;AAOO,SAAS,qBAAA,CACd,QACA,UAAA,EACA;AACA,EAAA,MAAM,IAAI,UAAA,EAAW;AAErB,EAAA,MAAM,aAAaC,8BAAA,CAAa,MAAA,EAAQ,EAAE,eAAA,EAAiB,OAAO,CAAA;AAClE,EAAA,OAAO;AAAA,IACL,CAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAY,UAAA,IAAc,CAAA;AAAA,IAC1B,YAAA,EAAc,EAAE,WAAA,EAAa,CAAA,EAAG,cAAc,CAAA;AAAE,GAClD;AACF;AAQA,eAAsB,yBAAA,CACpB,OACA,OAAA,EACe;AACf,EAAA,MAAM,MAAM,OAAA,EAAQ;AACpB,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,MAAM,OAAO,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/internal/structured-output-helpers.ts"],"names":["createRequire","ConfigurationError","toJsonSchema"],"mappings":";;;;;;;AAoBA,IAAI,OAAA;AAMG,SAAS,UAAA,GAAkC;AAChD,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAClC,EAAA,MAAM,CAAA,GAAIA,sBAAA,CAAc,oQAAe,CAAA;AACvC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,EAAE,KAAK,CAAA;AAAA,EACf,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAIC,oCAAA;AAAA,MACR,qIAAA;AAAA,MAEA,EAAE,IAAA,EAAM,mBAAA,EAAqB,KAAA;AAAM,KACrC;AAAA,EACF;AACA,EAAA,OAAA,GAAW,IAAI,CAAA,IAAK,GAAA;AACpB,EAAA,OAAO,OAAA;AACT;AAQO,SAAS,cAAA,CACd,YACA,SAAA,EACY;AACZ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,QAAA;AAAA,IACN,WAAA,EAAa,kFAAA;AAAA,IACb,WAAA,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,EAAA,OAAO;AAAA,IACL,CAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAY,UAAA,IAAc,CAAA;AAAA,IAC1B,YAAA,EAAc,EAAE,WAAA,EAAa,CAAA,EAAG,cAAc,CAAA;AAAE,GAClD;AACF;AAQA,eAAsB,yBAAA,CACpB,OACA,OAAA,EACe;AACf,EAAA,MAAM,MAAM,OAAA,EAAQ;AACpB,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,MAAM,OAAO,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-QDED6YO6.cjs","sourcesContent":["import { createRequire } from \"node:module\";\nimport type { z as ZodNamespace, ZodType } from \"zod\";\nimport { ConfigurationError } from \"../errors.js\";\n\nimport type { AgentOptions, CustomTool, LocalOptions, ModelSelection } from \"../types/agent.js\";\nimport type { ProviderRoutingSettings } from \"../types/providers.js\";\nimport { toJsonSchema } from \"./zod/to-json-schema.js\";\n\n/**\n * Shared helpers for `Agent.generateObject` (ADR D33) and\n * `Agent.streamObject` (ADR D39). Both build a transient agent with a\n * single synthetic `output` tool whose handler captures the model's\n * structured response.\n *\n * Extracted from inline duplicates to keep jscpd quiet AND to keep the\n * two public APIs in lockstep.\n *\n * @internal\n */\n\nlet cachedZ: typeof ZodNamespace | undefined;\n\n/**\n * Load Zod via createRequire (it's an optional peer dep). Throws a typed\n * ConfigurationError if Zod isn't installed.\n */\nexport function requireZod(): typeof ZodNamespace {\n if (cachedZ !== undefined) return cachedZ;\n const r = createRequire(import.meta.url);\n let mod: { z?: typeof ZodNamespace } & typeof ZodNamespace;\n try {\n mod = r(\"zod\") as typeof mod;\n } catch (cause) {\n throw new ConfigurationError(\n \"Structured output requires the optional peer dependency `zod`. \" +\n 'Add `\"zod\": \"^3.25.0 || ^4.0.0\"` to your package.json and reinstall.',\n { code: \"zod_not_installed\", cause },\n );\n }\n cachedZ = (mod.z ?? mod) as typeof ZodNamespace;\n return cachedZ;\n}\n\n/**\n * Build the synthetic `output` tool used by both `generateObject` and\n * `streamObject`. The handler captures the raw input on first call only\n * (EC-D10 / EC-6: parallel tool use in Claude 3.5+ may invoke `output`\n * twice; later calls are ignored).\n */\nexport function makeOutputTool(\n jsonSchema: Record<string, unknown>,\n onCapture: (input: unknown) => string | Promise<string> | undefined,\n): CustomTool {\n return {\n name: \"output\",\n description: \"Call this tool with your final structured answer. Match the JSON schema exactly.\",\n inputSchema: jsonSchema,\n handler: (input) => {\n const out = onCapture(input);\n // Some callers throw a sentinel (generate-object) and never return.\n // Others return a string (stream-object). Anything else → empty string.\n if (typeof out === \"string\") return out;\n if (out instanceof Promise) return out;\n return \"\";\n },\n };\n}\n\n/**\n * Assemble the AgentOptions for the transient agent. Shared shape:\n * model + local + tools[output] + systemPrompt + apiKey.\n */\nexport function buildTransientAgentOptions(params: {\n // SE8 — accepts the bare-string shorthand; forwarded to AgentOptions.model\n // (normalized at Agent.create).\n model: string | ModelSelection;\n local: LocalOptions;\n outputTool: CustomTool;\n systemPrompt?: string;\n apiKey?: string;\n providers?: ProviderRoutingSettings;\n}): AgentOptions {\n return {\n model: params.model,\n local: params.local,\n tools: [params.outputTool],\n systemPrompt:\n params.systemPrompt ??\n \"You produce structured output by calling the `output` tool exactly once. Match the JSON schema.\",\n ...(params.apiKey !== undefined ? { apiKey: params.apiKey } : {}),\n ...(params.providers !== undefined ? { providers: params.providers } : {}),\n };\n}\n\n/**\n * Best-effort extraction of token usage from a run result. Local runtimes\n * may not expose it; default to zeros.\n */\nexport function extractUsage(result: unknown): { inputTokens: number; outputTokens: number } {\n const u = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;\n if (u === undefined) return { inputTokens: 0, outputTokens: 0 };\n return { inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0 };\n}\n\n/**\n * Build the user-message prompt that instructs the model to call the\n * `output` tool with a schema-matched structured answer.\n */\nexport function buildToolPrompt(prompt: string): string {\n return `${prompt}\\n\\nRespond by calling the \\`output\\` tool with the structured answer that matches the schema.`;\n}\n\n/**\n * One-shot setup shared by both `generateObject` and `streamObject`. Loads\n * Zod, computes the JSON schema, primes the captured-raw / usage / retry\n * state. Returns the values needed by the caller's loop.\n */\nexport function setupStructuredOutput<T extends ZodType>(\n schema: T,\n maxRetries: number | undefined,\n) {\n const z = requireZod();\n // Universal Zod 3+4 conversion (feature-detects native v4, falls back to lib on v3).\n const jsonSchema = toJsonSchema(schema, { unrepresentable: \"any\" });\n return {\n z,\n jsonSchema,\n maxRetries: maxRetries ?? 1,\n initialUsage: { inputTokens: 0, outputTokens: 0 },\n };\n}\n\n/**\n * Cleanup the transient agent after generateObject/streamObject finish.\n * Disposes AND hard-deletes from the registry so the count stays stable.\n *\n * @internal\n */\nexport async function disposeAndDeleteTransient(\n agent: { dispose: () => Promise<void>; agentId: string },\n deletor: (agentId: string) => Promise<void>,\n): Promise<void> {\n await agent.dispose();\n try {\n await deletor(agent.agentId);\n } catch {\n // Best-effort cleanup.\n }\n}\n\nvoid (null as unknown as ZodType); // satisfies unused-import check\n"]}
|
|
@@ -86,5 +86,5 @@ exports.isEmptyRound = isEmptyRound;
|
|
|
86
86
|
exports.promptForRound = promptForRound;
|
|
87
87
|
exports.resolveContinuation = resolveContinuation;
|
|
88
88
|
exports.runToCompletionImpl = runToCompletionImpl;
|
|
89
|
-
//# sourceMappingURL=chunk-
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
89
|
+
//# sourceMappingURL=chunk-QKLOP4VC.cjs.map
|
|
90
|
+
//# sourceMappingURL=chunk-QKLOP4VC.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/lifecycle/run-to-completion.ts"],"names":[],"mappings":";;;AA+BO,IAAM,kBAAA,GAAqB;AAE3B,IAAM,2BAAA,GACX;AAQK,SAAS,aAAa,MAAA,EAA4B;AACvD,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAA,IAAU,EAAA,EAAI,IAAA,EAAK,KAAM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AA,KACN;AACA,IAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAAA,EACpC;AACF","file":"chunk-VK7MAV65.cjs","sourcesContent":["/**\n * `runToCompletion` continuation driver (M1 Phase 3 — plan m1-run-to-completion).\n *\n * Drives repeated `send()`s on a STATEFUL agent until a genuine terminal,\n * consuming the `RunResult.stoppedAtIterationLimit` signal shipped in 2.2.0.\n * The agent's session preserves conversation history across sends, so after a\n * truncated round the driver only re-sends a short continuation prompt (it does\n * NOT reconstruct history). Mirrors the injectable shape of `run-until.ts` and\n * absorbs the outer-loop policy hand-rolled in `theocode/server/lib/agent-loop.ts`.\n *\n * The core is decision-pure + injectable (`agent` is only the `.send` port) so\n * every terminal is unit-testable with a fake send — fixture mode never sets\n * `stoppedAtIterationLimit`, so injection is the only deterministic path.\n *\n * @internal\n */\n\nimport type {\n RunResult,\n RunToCompletionOptions,\n RunToCompletionResult,\n SendOptions,\n} from \"../../../types/run.js\";\nimport type { TokenUsage } from \"../../../types/usage.js\";\n\n/** Minimal agent port the driver needs — the instance `.send()` surface. */\nexport interface RunToCompletionAgent {\n send(message: string, options?: SendOptions): Promise<{ wait(): Promise<RunResult> }>;\n}\n\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_MAX_ROUNDS = 5;\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_CONTINUATION_PROMPT =\n \"Continue from where you left off and finish the task. If it is already complete, give the final answer.\";\n\ntype RoundDecision = \"done\" | \"continue\" | \"step_limit\" | \"no_progress\";\n\n/**\n * True when a round produced no observable output text.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function isEmptyRound(result: RunResult): boolean {\n return (result.result ?? \"\").trim() === \"\";\n}\n\n/**\n * Pure decision: given a round's result + position + the running empty streak,\n * decide whether to finish (`done`), keep going (`continue`), or bail\n * (`step_limit` / `no_progress`).\n *\n * @internal\n */\nexport function classifyRound(\n result: RunResult,\n round: number,\n maxRounds: number,\n emptyStreak: number,\n): RoundDecision {\n // Doom-loop stop is a genuine terminal (the model repeated identical tool calls) — classify it as\n // `no_progress` FIRST, before the iteration-limit check, so it is never mistaken for a truncation\n // to re-send (which would re-trigger the loop). Complements the empty-round `no_progress` below.\n if (result.stoppedByDoomLoop === true) return \"no_progress\";\n if (result.stoppedAtIterationLimit !== true) return \"done\";\n // Truncated at the iteration ceiling.\n if (isEmptyRound(result) && emptyStreak >= 1) return \"no_progress\";\n if (round >= maxRounds) return \"step_limit\";\n return \"continue\";\n}\n\n/**\n * Sum a round's usage into the running aggregate. `requests` is intentionally\n * dropped (concatenating per-run request breakdowns across continuation rounds\n * would falsely imply a single multi-call run). `totalTokens` is DERIVED\n * (`inputTokens + outputTokens`), never summed independently, to preserve the\n * EC-10 invariant (`usage.ts`) at this aggregation boundary even if a provider\n * folded extra buckets into a round's own `totalTokens`.\n */\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport function addUsage(\n acc: TokenUsage | undefined,\n u: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (u === undefined) return acc;\n const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;\n const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;\n const sumOpt = (a: number | undefined, b: number | undefined): number | undefined =>\n a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),\n cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),\n reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens),\n };\n}\n\n/**\n * Assemble the result object, omitting `usage` when no round reported any.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function buildResult(\n terminal: RunToCompletionResult[\"terminal\"],\n rounds: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n): RunToCompletionResult {\n return { terminal, rounds, lastResult, ...(usage !== undefined ? { usage } : {}) };\n}\n\n/**\n * The shared between-rounds tail: fire `onTruncated`, then — re-reading `aborted`\n * (a getter that can flip between rounds) — return a `step_limit` result if the\n * signal aborted, else `undefined` to continue. Used by BOTH the stateful driver\n * and its streaming twin (V3-4), so the continuation-end policy has one home.\n * @internal\n */\nexport async function continuationTail(\n round: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<RunToCompletionResult | undefined> {\n await onTruncated?.({ round });\n return signal?.aborted === true ? buildResult(\"step_limit\", round, lastResult, usage) : undefined;\n}\n\n/**\n * Carried state between continuation rounds.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport interface RoundState {\n usage: TokenUsage | undefined;\n emptyStreak: number;\n}\n\n/** Resolved continuation config + fresh initial state — shared by both drivers. @internal */\nexport interface ResolvedContinuation {\n maxRounds: number;\n continuationPrompt: string;\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined;\n signal: AbortSignal | undefined;\n sendOptions: SendOptions | undefined;\n state: RoundState;\n}\n\n/** Resolve options to the continuation config + a fresh state. One home for the defaults. @internal */\nexport function resolveContinuation(options?: RunToCompletionOptions): ResolvedContinuation {\n return {\n maxRounds: options?.maxRounds ?? DEFAULT_MAX_ROUNDS,\n continuationPrompt: options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT,\n onTruncated: options?.onTruncated,\n signal: options?.signal,\n sendOptions: options?.sendOptions,\n state: { usage: undefined, emptyStreak: 0 },\n };\n}\n\n/** The round's prompt: the task on round 0, the continuation prompt after. @internal */\nexport function promptForRound(round: number, message: string, continuationPrompt: string): string {\n return round === 0 ? message : continuationPrompt;\n}\n\n/** A round either reaches a terminal, or yields the state to carry into the next round. */\ntype RoundOutcome =\n | { terminal: RunToCompletionResult }\n | { next: RoundState; lastResult: RunResult };\n\n/** Send one round, fold usage, classify. Splits the loop body out to cap complexity. */\nasync function stepRound(\n agent: RunToCompletionAgent,\n prompt: string,\n sendOptions: SendOptions | undefined,\n round: number,\n maxRounds: number,\n state: RoundState,\n): Promise<RoundOutcome> {\n // SE3 — a continuation round (round > 0) is a driver-initiated turn; stamp its\n // provenance so a consumer can tell it apart from the caller's first send.\n const roundOptions: SendOptions | undefined =\n round === 0 ? sendOptions : { ...(sendOptions ?? {}), origin: { kind: \"auto-continuation\" } };\n const run = await agent.send(prompt, roundOptions);\n const result = await run.wait();\n const usage = addUsage(state.usage, result.usage);\n const decision = classifyRound(result, round, maxRounds, state.emptyStreak);\n if (decision !== \"continue\") return { terminal: buildResult(decision, round, result, usage) };\n const emptyStreak = isEmptyRound(result) ? state.emptyStreak + 1 : 0;\n return { next: { usage, emptyStreak }, lastResult: result };\n}\n\n/**\n * Drive `agent.send()` until a terminal. See {@link RunToCompletionOptions}.\n *\n * @internal\n */\nexport async function runToCompletionImpl(\n agent: RunToCompletionAgent,\n message: string,\n options?: RunToCompletionOptions,\n): Promise<RunToCompletionResult> {\n const cfg = resolveContinuation(options);\n let state = cfg.state;\n\n for (let round = 0; ; round += 1) {\n const prompt = promptForRound(round, message, cfg.continuationPrompt);\n const outcome = await stepRound(agent, prompt, cfg.sendOptions, round, cfg.maxRounds, state);\n if (\"terminal\" in outcome) return outcome.terminal;\n\n // Truncated and below the round budget — re-send next iteration.\n state = outcome.next;\n const aborted = await continuationTail(\n round,\n outcome.lastResult,\n state.usage,\n cfg.onTruncated,\n cfg.signal,\n );\n if (aborted !== undefined) return aborted;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/lifecycle/run-to-completion.ts"],"names":[],"mappings":";;;AA+BO,IAAM,kBAAA,GAAqB;AAE3B,IAAM,2BAAA,GACX;AAQK,SAAS,aAAa,MAAA,EAA4B;AACvD,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAA,IAAU,EAAA,EAAI,IAAA,EAA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AAI;AAAA,KACN;AACA,IAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAAA,EACpC;AACF","file":"chunk-QKLOP4VC.cjs","sourcesContent":["/**\n * `runToCompletion` continuation driver (M1 Phase 3 — plan m1-run-to-completion).\n *\n * Drives repeated `send()`s on a STATEFUL agent until a genuine terminal,\n * consuming the `RunResult.stoppedAtIterationLimit` signal shipped in 2.2.0.\n * The agent's session preserves conversation history across sends, so after a\n * truncated round the driver only re-sends a short continuation prompt (it does\n * NOT reconstruct history). Mirrors the injectable shape of `run-until.ts` and\n * absorbs the outer-loop policy hand-rolled in `theocode/server/lib/agent-loop.ts`.\n *\n * The core is decision-pure + injectable (`agent` is only the `.send` port) so\n * every terminal is unit-testable with a fake send — fixture mode never sets\n * `stoppedAtIterationLimit`, so injection is the only deterministic path.\n *\n * @internal\n */\n\nimport type {\n RunResult,\n RunToCompletionOptions,\n RunToCompletionResult,\n SendOptions,\n} from \"../../../types/run.js\";\nimport type { TokenUsage } from \"../../../types/usage.js\";\n\n/** Minimal agent port the driver needs — the instance `.send()` surface. */\nexport interface RunToCompletionAgent {\n send(message: string, options?: SendOptions): Promise<{ wait(): Promise<RunResult> }>;\n}\n\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_MAX_ROUNDS = 5;\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_CONTINUATION_PROMPT =\n \"Continue from where you left off and finish the task. If it is already complete, give the final answer.\";\n\ntype RoundDecision = \"done\" | \"continue\" | \"step_limit\" | \"no_progress\";\n\n/**\n * True when a round produced no observable output text.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function isEmptyRound(result: RunResult): boolean {\n return (result.result ?? \"\").trim() === \"\";\n}\n\n/**\n * Pure decision: given a round's result + position + the running empty streak,\n * decide whether to finish (`done`), keep going (`continue`), or bail\n * (`step_limit` / `no_progress`).\n *\n * @internal\n */\nexport function classifyRound(\n result: RunResult,\n round: number,\n maxRounds: number,\n emptyStreak: number,\n): RoundDecision {\n // Doom-loop stop is a genuine terminal (the model repeated identical tool calls) — classify it as\n // `no_progress` FIRST, before the iteration-limit check, so it is never mistaken for a truncation\n // to re-send (which would re-trigger the loop). Complements the empty-round `no_progress` below.\n if (result.stoppedByDoomLoop === true) return \"no_progress\";\n if (result.stoppedAtIterationLimit !== true) return \"done\";\n // Truncated at the iteration ceiling.\n if (isEmptyRound(result) && emptyStreak >= 1) return \"no_progress\";\n if (round >= maxRounds) return \"step_limit\";\n return \"continue\";\n}\n\n/**\n * Sum a round's usage into the running aggregate. `requests` is intentionally\n * dropped (concatenating per-run request breakdowns across continuation rounds\n * would falsely imply a single multi-call run). `totalTokens` is DERIVED\n * (`inputTokens + outputTokens`), never summed independently, to preserve the\n * EC-10 invariant (`usage.ts`) at this aggregation boundary even if a provider\n * folded extra buckets into a round's own `totalTokens`.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function addUsage(\n acc: TokenUsage | undefined,\n u: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (u === undefined) return acc;\n const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;\n const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;\n const sumOpt = (a: number | undefined, b: number | undefined): number | undefined =>\n a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),\n cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),\n reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens),\n };\n}\n\n/**\n * Assemble the result object, omitting `usage` when no round reported any.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function buildResult(\n terminal: RunToCompletionResult[\"terminal\"],\n rounds: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n): RunToCompletionResult {\n return { terminal, rounds, lastResult, ...(usage !== undefined ? { usage } : {}) };\n}\n\n/**\n * The shared between-rounds tail: fire `onTruncated`, then — re-reading `aborted`\n * (a getter that can flip between rounds) — return a `step_limit` result if the\n * signal aborted, else `undefined` to continue. Used by BOTH the stateful driver\n * and its streaming twin (V3-4), so the continuation-end policy has one home.\n * @internal\n */\nexport async function continuationTail(\n round: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<RunToCompletionResult | undefined> {\n await onTruncated?.({ round });\n return signal?.aborted === true ? buildResult(\"step_limit\", round, lastResult, usage) : undefined;\n}\n\n/**\n * Carried state between continuation rounds.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport interface RoundState {\n usage: TokenUsage | undefined;\n emptyStreak: number;\n}\n\n/** Resolved continuation config + fresh initial state — shared by both drivers. @internal */\nexport interface ResolvedContinuation {\n maxRounds: number;\n continuationPrompt: string;\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined;\n signal: AbortSignal | undefined;\n sendOptions: SendOptions | undefined;\n state: RoundState;\n}\n\n/** Resolve options to the continuation config + a fresh state. One home for the defaults. @internal */\nexport function resolveContinuation(options?: RunToCompletionOptions): ResolvedContinuation {\n return {\n maxRounds: options?.maxRounds ?? DEFAULT_MAX_ROUNDS,\n continuationPrompt: options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT,\n onTruncated: options?.onTruncated,\n signal: options?.signal,\n sendOptions: options?.sendOptions,\n state: { usage: undefined, emptyStreak: 0 },\n };\n}\n\n/** The round's prompt: the task on round 0, the continuation prompt after. @internal */\nexport function promptForRound(round: number, message: string, continuationPrompt: string): string {\n return round === 0 ? message : continuationPrompt;\n}\n\n/** A round either reaches a terminal, or yields the state to carry into the next round. */\ntype RoundOutcome =\n | { terminal: RunToCompletionResult }\n | { next: RoundState; lastResult: RunResult };\n\n/** Send one round, fold usage, classify. Splits the loop body out to cap complexity. */\nasync function stepRound(\n agent: RunToCompletionAgent,\n prompt: string,\n sendOptions: SendOptions | undefined,\n round: number,\n maxRounds: number,\n state: RoundState,\n): Promise<RoundOutcome> {\n // SE3 — a continuation round (round > 0) is a driver-initiated turn; stamp its\n // provenance so a consumer can tell it apart from the caller's first send.\n const roundOptions: SendOptions | undefined =\n round === 0 ? sendOptions : { ...(sendOptions ?? {}), origin: { kind: \"auto-continuation\" } };\n const run = await agent.send(prompt, roundOptions);\n const result = await run.wait();\n const usage = addUsage(state.usage, result.usage);\n const decision = classifyRound(result, round, maxRounds, state.emptyStreak);\n if (decision !== \"continue\") return { terminal: buildResult(decision, round, result, usage) };\n const emptyStreak = isEmptyRound(result) ? state.emptyStreak + 1 : 0;\n return { next: { usage, emptyStreak }, lastResult: result };\n}\n\n/**\n * Drive `agent.send()` until a terminal. See {@link RunToCompletionOptions}.\n *\n * @internal\n */\nexport async function runToCompletionImpl(\n agent: RunToCompletionAgent,\n message: string,\n options?: RunToCompletionOptions,\n): Promise<RunToCompletionResult> {\n const cfg = resolveContinuation(options);\n let state = cfg.state;\n\n for (let round = 0; ; round += 1) {\n const prompt = promptForRound(round, message, cfg.continuationPrompt);\n const outcome = await stepRound(agent, prompt, cfg.sendOptions, round, cfg.maxRounds, state);\n if (\"terminal\" in outcome) return outcome.terminal;\n\n // Truncated and below the round budget — re-send next iteration.\n state = outcome.next;\n const aborted = await continuationTail(\n round,\n outcome.lastResult,\n state.usage,\n cfg.onTruncated,\n cfg.signal,\n );\n if (aborted !== undefined) return aborted;\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-
|
|
1
|
+
import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-AEOZTXVW.js';
|
|
2
2
|
|
|
3
3
|
// src/generate-object.ts
|
|
4
4
|
var GenerateObjectError = class extends Error {
|
|
@@ -138,5 +138,5 @@ async function generateObjectImpl(options, deps) {
|
|
|
138
138
|
}
|
|
139
139
|
|
|
140
140
|
export { GenerateObjectError, generateObjectImpl };
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
142
|
-
//# sourceMappingURL=chunk-
|
|
141
|
+
//# sourceMappingURL=chunk-QRSUA2CV.js.map
|
|
142
|
+
//# sourceMappingURL=chunk-QRSUA2CV.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generate-object.ts"],"names":[],"mappings":";;;AAyFO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC3B,IAAA,GAAO,qBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,WAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AACtD,IAAA,IAAI,OAAO,WAAA,EAAa,SAAA,KAAc,UAAA,EAAY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OAAA,EAAS;AAClB,QAAA,OAAO;AAAA,UACL,QAAQ,MAAA,CAAO,IAAA;AAAA,UACf,GAAA,EAAK,WAAA;AAAA,UACL,KAAA,EAAO,SAAA;AAAA,UACP,YAAA,EAAc;AAAA,SAChB;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,MAAA,CAAO,KAAA;AAAA,IAC1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACA,wCAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAM,yBAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-FIOCJYLA.js","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n /**\n * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends Error {\n override readonly name = \"GenerateObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n *\n * @internal\n */\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/generate-object.ts"],"names":[],"mappings":";;;AAyFO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC3B,IAAA,GAAO,qBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,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;AACA,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,SAAA,CAAU,WAAW,CAAA;AACnD,MAAA,IAAI,OAAO,OAAA,EAAS;AAClB,QAAA,OAAO;AAAA,UACL,QAAQ,MAAA,CAAO,IAAA;AAAA,UACf,GAAA,EAAK,WAAA;AAAA,UACL,KAAA,EAAO,SAAA;AAAA,UACP,YAAA,EAAc;AAAA,SAChB;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,MAAA,CAAO,KAAA;AAAA,IAC1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACA,wCAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAM,yBAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-QRSUA2CV.js","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n /**\n * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends Error {\n override readonly name = \"GenerateObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkVKJ7V7EB_cjs = require('./chunk-VKJ7V7EB.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
|
|
5
5
|
var crypto = require('crypto');
|
|
6
6
|
var fs = require('fs');
|
|
7
7
|
var path = require('path');
|
|
8
8
|
|
|
9
|
-
var PathTraversalError = class extends
|
|
9
|
+
var PathTraversalError = class extends chunkK3FW2XZD_cjs.ConfigurationError {
|
|
10
10
|
name = "PathTraversalError";
|
|
11
11
|
constructor(input, resolvedPath) {
|
|
12
12
|
super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
|
|
@@ -14,7 +14,7 @@ var PathTraversalError = class extends chunkLPVIRJVF_cjs.ConfigurationError {
|
|
|
14
14
|
});
|
|
15
15
|
}
|
|
16
16
|
};
|
|
17
|
-
var ForbiddenPathError = class extends
|
|
17
|
+
var ForbiddenPathError = class extends chunkK3FW2XZD_cjs.ConfigurationError {
|
|
18
18
|
name = "ForbiddenPathError";
|
|
19
19
|
constructor(path) {
|
|
20
20
|
super(
|
|
@@ -43,14 +43,18 @@ function safePathJoin(base, ...parts) {
|
|
|
43
43
|
}
|
|
44
44
|
return target;
|
|
45
45
|
}
|
|
46
|
-
function
|
|
46
|
+
function firstControlCharLabel(input) {
|
|
47
47
|
for (let i = 0; i < input.length; i++) {
|
|
48
48
|
const code = input.charCodeAt(i);
|
|
49
49
|
if (code === 0 || code >= 1 && code <= 31 || code === 127) {
|
|
50
|
-
|
|
51
|
-
throw new PathTraversalError(`${role}: ${input}`, label);
|
|
50
|
+
return code === 0 ? "<nul-byte>" : `<control-char-0x${code.toString(16)}>`;
|
|
52
51
|
}
|
|
53
52
|
}
|
|
53
|
+
return void 0;
|
|
54
|
+
}
|
|
55
|
+
function rejectNulAndControlChars(input, role) {
|
|
56
|
+
const label = firstControlCharLabel(input);
|
|
57
|
+
if (label !== void 0) throw new PathTraversalError(`${role}: ${input}`, label);
|
|
54
58
|
}
|
|
55
59
|
function assertNoSymlinkEscape(path$1, base) {
|
|
56
60
|
rejectNulAndControlChars(path$1, "path");
|
|
@@ -184,13 +188,18 @@ function rejectParentTraversal(input, normalized) {
|
|
|
184
188
|
function sanitizeIdentifier(input, options) {
|
|
185
189
|
const maxLen = options?.maxLen ?? 64;
|
|
186
190
|
if (input.length === 0 || input.length > maxLen) {
|
|
187
|
-
throw new
|
|
191
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
|
|
192
|
+
code: "invalid_identifier"
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const controlChar = firstControlCharLabel(input);
|
|
196
|
+
if (controlChar !== void 0) {
|
|
197
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier contains ${controlChar}: "${input}"`, {
|
|
188
198
|
code: "invalid_identifier"
|
|
189
199
|
});
|
|
190
200
|
}
|
|
191
|
-
rejectNulAndControlChars(input, "identifier");
|
|
192
201
|
if (!IDENTIFIER_PATTERN.test(input)) {
|
|
193
|
-
throw new
|
|
202
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
|
|
194
203
|
code: "invalid_identifier"
|
|
195
204
|
});
|
|
196
205
|
}
|
|
@@ -198,7 +207,7 @@ function sanitizeIdentifier(input, options) {
|
|
|
198
207
|
}
|
|
199
208
|
function safeFilenameForId(id, options) {
|
|
200
209
|
if (id.length === 0) {
|
|
201
|
-
throw new
|
|
210
|
+
throw new chunkK3FW2XZD_cjs.ConfigurationError("Filename id must be a non-empty string", {
|
|
202
211
|
code: "invalid_filename_id"
|
|
203
212
|
});
|
|
204
213
|
}
|
|
@@ -218,5 +227,5 @@ exports.safeFilenameForId = safeFilenameForId;
|
|
|
218
227
|
exports.safePathJoin = safePathJoin;
|
|
219
228
|
exports.sanitizeIdentifier = sanitizeIdentifier;
|
|
220
229
|
exports.validateArtifactPath = validateArtifactPath;
|
|
221
|
-
//# sourceMappingURL=chunk-
|
|
222
|
-
//# sourceMappingURL=chunk-
|
|
230
|
+
//# sourceMappingURL=chunk-R3UPQFKK.cjs.map
|
|
231
|
+
//# sourceMappingURL=chunk-R3UPQFKK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/security/path-guard.ts"],"names":["ConfigurationError","atOrInsideRoot","resolve","path","realpathSync","lstatSync","readlinkSync","dirname","createHash"],"mappings":";;;;;;;;AAgCO,IAAM,kBAAA,GAAN,cAAiCA,oCAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,WAAA,CAAY,OAAe,YAAA,EAAsB;AAC/C,IAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,KAAK,CAAA,QAAA,EAAM,YAAY,CAAA,CAAA,EAAI;AAAA,MAC1D,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,E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,CAAA;AAAA,EACH;AACA,EAAA,IAAI,CAAC,kBAAA,CAAmB,IAAA,CAAK,KAAK,CAAA,EAAG;AACnC,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,yCAAA,EAA4C,KAAK,CAAA,CAAA,CAAA,EAAK;AAAA,MACjF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,MAAM,WAAA,EAAY;AAC3B;AAwBO,SAAS,iBAAA,CAAkB,IAAY,OAAA,EAAuC;AACnF,EAAA,IAAI,EAAA,CAAG,WAAW,CAAA,EAAG;AACnB,IAAA,MAAM,IAAIA,qCAAmB,wCAAA,EAA0C;AAAA,MACrE,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,GAAA;AAClC,EAAA,MAAM,KAAA,GAAQ,GAAG,WAAA,EAAY;AAC7B,EAAA,IAAI,MAAM,MAAA,IAAU,MAAA,IAAU,kBAAA,CAAmB,IAAA,CAAK,KAAK,CAAA,EAAG;AAC5D,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,CAAA,EAAA,EAAKQ,iBAAA,CAAW,QAAQ,CAAA,CAAE,MAAA,CAAO,EAAE,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACxE","file":"chunk-R3UPQFKK.cjs","sourcesContent":["/**\n * Canonical path-guard module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { atOrInsideRoot } from \"../runtime/context/path-containment.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Is `target` the same as `base`, or strictly under it?\n *\n * The prefix must not double the separator. `resolve` strips a trailing `sep` from every base\n * EXCEPT the filesystem root, where `resolve(sep) === sep`; there `base + sep` would be `//`, which\n * no absolute path starts with, so a root base rejected EVERY path (#149). Only the root takes that\n * branch — for any other base the prefix is unchanged, so containment is not weakened.\n *\n * Both containment checks in this module go through here: they had the same defect and were fixed\n * one at a time, which is exactly how the two drifted apart in the first place.\n *\n * Both arguments MUST already be resolved absolute paths.\n */\nfunction isInside(target: string, base: string): boolean {\n // B-117 — compared after symlink resolution, via the shared rule. A prefix test judges a link by\n // its NAME: `<base>/link/x` where `link` points outside is lexically inside and physically not.\n // Measured reachable from the plugin manager and the MCP client before this was changed.\n //\n // The root itself stays allowed, which `insideRoot` alone does not answer: it returns false for\n // `target === base` (correct for its own caller, wrong here, where `safePathJoin(base)` with no\n // parts must return `base`). Kept as an explicit second clause rather than by weakening the\n // shared rule for everyone.\n return atOrInsideRoot(target, base);\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n // T5.5 — NUL byte + C0/DEL control char rejection at the boundary.\n // Apply before path resolution so a malicious input never reaches\n // `resolve` (which on some platforms behaved unexpectedly with NUL\n // and in N-API callers historically silently truncated).\n rejectNulAndControlChars(base, \"base\");\n for (const part of parts) {\n rejectNulAndControlChars(part, \"path segment\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (!isInside(target, baseResolved)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * T5.5 — the operator-legible label for the first NUL (`\\x00`), C0 control char (`\\x01-\\x1F`) or\n * DEL (`\\x7F`) in `input`, or `undefined` when it carries none. Centralizes the scan so every\n * public path-guard / sanitize entrypoint shares one definition of \"control character\".\n *\n * Detection is separated from the throw so the two callers can share the scan and the precise\n * diagnostic while each raising the error ITS OWN contract documents (#368) — a path guard reports\n * a traversal, an identifier validator reports an invalid identifier. Before that split both threw\n * `PathTraversalError`, which made an identifier validator's error class depend on the bytes of the\n * input it was handed.\n *\n * @internal\n */\nfunction firstControlCharLabel(input: string): string | undefined {\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n return code === 0x00 ? \"<nul-byte>\" : `<control-char-0x${code.toString(16)}>`;\n }\n }\n return undefined;\n}\n\n/**\n * Reject any path-shaped input carrying a NUL or control character, as `PathTraversalError` — the\n * same shape as every other path-shape rejection, so callers do not learn a second error class.\n *\n * @internal\n */\nfunction rejectNulAndControlChars(input: string, role: string): void {\n const label = firstControlCharLabel(input);\n if (label !== undefined) throw new PathTraversalError(`${role}: ${input}`, label);\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // T5.5 — reject NUL / control chars before any FS call (a NUL byte\n // in the path used to silently truncate at the C boundary on legacy\n // libc — defense in depth even on modern Node).\n rejectNulAndControlChars(path, \"path\");\n rejectNulAndControlChars(base, \"base\");\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (!isInside(resolved, baseResolved)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n// T5.6 — top-level credential dot-dirs / dot-files. Matching against\n// the FIRST path segment (lowercase). Adding any entry here costs a\n// CHANGELOG note + an explicit case-fold test (entries are lowercased\n// at module load).\nconst SENSITIVE_FIRST_SEGMENTS = new Set([\n \".ssh\",\n \".aws\",\n \".docker\",\n \".kube\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — credential basenames blocked at ANY depth (lowercase). Catches\n// the developer-laptop case where an agent recurses into a subdir.\nconst SENSITIVE_BASENAMES = new Set([\n \"id_rsa\",\n \"id_ed25519\",\n \"id_ecdsa\",\n \"id_dsa\",\n \"authorized_keys\",\n \"known_hosts\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — extension suffixes blocked at ANY depth (lowercase). Covers\n// the entire `*.pem` / `*.key` private-material family.\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // T5.6 — lowercase normalization defeats case-only bypass on\n // case-insensitive filesystems (Windows/macOS-default) where `.ENV`\n // and `.env` map to the same inode but a case-sensitive string\n // check passes the former.\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").toLowerCase();\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n if (isForbiddenFirstSegment(segments[0]!)) return true;\n if (isForbiddenBasename(segments[segments.length - 1]!)) return true;\n return false;\n}\n\nfunction isForbiddenFirstSegment(first: string): boolean {\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n if (first === \".git\" || first === \"node_modules\" || first === \".theo\") return true;\n return SENSITIVE_FIRST_SEGMENTS.has(first);\n}\n\nfunction isForbiddenBasename(basename: string): boolean {\n if (LOCK_FILES.has(basename)) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n for (const suffix of SENSITIVE_SUFFIXES) {\n if (basename.endsWith(suffix)) return true;\n }\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * T1.4 — validate a relative artifact path string BEFORE it is used to look\n * up a fixture or to fetch from PaaS. Rejects every well-known traversal\n * vector at the boundary, throwing `PathTraversalError`.\n *\n * Vectors rejected:\n * - classic `..` parent-directory traversal (any segment).\n * - backslash separators (Windows-style `..\\\\windows`).\n * - URL-encoded `%2e%2e` / `%2E%2E` (double-decoded traversal).\n * - NUL byte injection (`\\x00`).\n * - Windows drive letter prefix (`C:`, `D:\\\\...`).\n * - Home-tilde expansion (`~/`, `~root/...`).\n * - Absolute paths starting with `/`.\n *\n * Does NOT touch the filesystem — the call is shape-only. Live symlink\n * traversal protection happens via `assertNoSymlinkEscape` at the FS-resolve\n * boundary.\n *\n * @param input - Caller-supplied artifact path.\n * @throws `PathTraversalError` on any rejection.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/security` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function validateArtifactPath(input: string): void {\n rejectKnownPrefixVectors(input);\n const normalized = decodeAndNormalize(input);\n rejectParentTraversal(input, normalized);\n}\n\nfunction rejectKnownPrefixVectors(input: string): void {\n if (input.includes(\"\\x00\")) {\n throw new PathTraversalError(input, \"<nul-byte>\");\n }\n if (input.startsWith(\"/\") || input.startsWith(\"~\")) {\n throw new PathTraversalError(input, input);\n }\n if (/^[A-Za-z]:[\\\\/]?/.test(input)) {\n throw new PathTraversalError(input, input);\n }\n}\n\nfunction decodeAndNormalize(input: string): string {\n // URL-encoded traversal — 2 passes catches `%252e%252e`.\n // Malformed sequences (decodeURIComponent throws) are themselves a rejection.\n let decoded = input;\n for (let i = 0; i < 2; i += 1) {\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n throw new PathTraversalError(input, \"<malformed-url-encoding>\");\n }\n }\n // Normalize backslash to forward slash before segment-walking.\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction rejectParentTraversal(input: string, normalized: string): void {\n for (const segment of normalized.split(\"/\")) {\n if (segment === \"..\" || segment === \"..%00\") {\n throw new PathTraversalError(input, normalized);\n }\n }\n // Defense in depth: literal `..` anywhere in the normalized string.\n if (normalized.includes(\"..\")) {\n throw new PathTraversalError(input, normalized);\n }\n}\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * ONE error class leaves this function: `ConfigurationError` with code\n * `invalid_identifier`, for every rejection — length out of range, a path\n * separator, `..`, a space, a leading `-`, and a NUL / C0 control char / DEL\n * alike. A caller can branch on that code and know it has covered the whole\n * rejection surface.\n *\n * Before #368 the control-char branch threw `PathTraversalError` instead, which\n * made the error CLASS a function of the attacker's bytes; the message still names\n * the offending byte, which is the part that was worth keeping.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on every rejection.\n */\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n // T5.5 — explicit NUL / control char rejection ahead of the generic pattern check. The\n // IDENTIFIER_PATTERN regex already excludes these (they are not in `[a-z0-9\\-_]`); naming the\n // offending byte gives operators a precise diagnostic instead of the generic \"invalid characters\"\n // message, which is what makes a prompt-injection trace legible (Rule 3).\n //\n // #368 — the diagnostic used to arrive as a `PathTraversalError`, because the branch reused\n // `safePathJoin`'s thrower. That made the error CLASS a function of the attacker's bytes: a\n // caller branching on the documented `invalid_identifier` rethrew for any input carrying a\n // control char, so a rejection surfaced as a 500 and the 400/500 split became an oracle. The\n // detection is shared; the error each contract documents is not.\n const controlChar = firstControlCharLabel(input);\n if (controlChar !== undefined) {\n throw new ConfigurationError(`Identifier contains ${controlChar}: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n\n/**\n * Convert ANY opaque id (agent id, run id, conversation id, namespace, email,\n * arbitrary string) into a deterministic, filesystem-safe filename component.\n *\n * Unlike {@link sanitizeIdentifier} (which THROWS on non-conforming input),\n * this is a total function: it NEVER throws on a non-empty string. It returns\n * the lowercased id verbatim when it already matches the safe grammar\n * `^[a-z0-9][a-z0-9-_]*$` and fits `maxLen` (so UUIDs, hashes, and slugs stay\n * human-readable), otherwise a deterministic `h-<16 hex>` sha256 token\n * (collision-resistant and always a valid filename). The output charset is\n * always `[a-z0-9_-]`, safe as a literal path segment on every filesystem.\n *\n * @param id - any opaque identifier (must be a non-empty string)\n * @param options.maxLen - max length for the passthrough branch (default 128).\n * Ids longer than this are hashed; the hash token itself is always short.\n * @throws ConfigurationError (code `invalid_filename_id`) only on empty input.\n *\n * @example\n * safeFilenameForId(\"550e8400-e29b-41d4-a716-446655440000\") // passthrough\n * safeFilenameForId(\"user@example.com\") // \"h-<16hex>\"\n *\n */\nexport function safeFilenameForId(id: string, options?: { maxLen?: number }): string {\n if (id.length === 0) {\n throw new ConfigurationError(\"Filename id must be a non-empty string\", {\n code: \"invalid_filename_id\",\n });\n }\n const maxLen = options?.maxLen ?? 128;\n const lower = id.toLowerCase();\n if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {\n return lower;\n }\n return `h-${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 16)}`;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/llm/model-identifier.ts"],"names":[],"mappings":";AAkCA,IAAM,gBAAA,GAAqD;AAAA,EACzD,WAAA,EAAa,UAAA;AAAA,EACb,WAAA,EAAa,UAAA;AAAA,EACb,WAAA,EAAa,UAAA;AAAA,EACb,SAAA,EAAW;AACb,CAAA;AA4BO,SAAS,aAAa,OAAA,EAA4C;AACvE,EAAA,IAAI,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG;AACjD,IAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAW,IAAA,EAAM,EAAA,EAAG;AAAA,EACzC;AACA,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AACjC,EAAA,IAAI,KAAA,IAAS,CAAA,IAAK,KAAA,KAAU,OAAA,CAAQ,SAAS,CAAA,EAAG;AAC9C,IAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAW,IAAA,EAAM,OAAA,EAAQ;AAAA,EAC9C;AACA,EAAA,MAAM,WAAA,GAAc,QAAQ,KAAA,CAAM,CAAA,EAAG,KAAK,CAAA,CAAE,IAAA,GAAO,WAAA,EAAY;AAC/D,EAAA,MAAM,OAAO,OAAA,CAAQ,KAAA,CAAM,KAAA,GAAQ,CAAC,EAAE,IAAA,EAAK;AAC3C,EAAA,IAAI,WAAA,CAAY,MAAA,KAAW,CAAA,IAAK,IAAA,CAAK,WAAW,CAAA,EAAG;AACjD,IAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAW,IAAA,EAAM,OAAA,EAAQ;AAAA,EAC9C;AACA,EAAA,MAAM,SAAA,GAAY,gBAAA,CAAiB,WAAW,CAAA,IAAK,WAAA;AACnD,EAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,IAAA,EAAK;AACrC","file":"chunk-R7WIIPUR.js","sourcesContent":["/**\n * Model identifier parsing (T1.2 follow-up, ADR D182 zero-config UX).\n *\n * SDK callers pass model strings like:\n * - `\"ollama/llama3.2:3b\"` → provider=\"ollama\", name=\"llama3.2:3b\"\n * - `\"anthropic/claude-3-5-sonnet\"` → provider=\"anthropic\", name=\"claude-3-5-sonnet\"\n * - `\"openrouter/meta-llama/llama-3\"` → provider=\"openrouter\", name=\"meta-llama/llama-3\"\n * - `\"claude-sonnet-4-6\"` → provider=undefined, name=\"claude-sonnet-4-6\"\n *\n * The first `/` separates the provider from the rest. Models with embedded\n * slashes (e.g. OpenRouter routing) keep the remainder intact. Tag suffixes\n * (`:latest`, `:3b`) are preserved as part of the name — Ollama expects them.\n *\n * **Returns `undefined` provider** when no `/` is present so callers can\n * fall back to env-var detection. Empty/whitespace components are treated\n * as no-prefix.\n *\n * Aligned with peer-project `extensions/ollama/src/discovery-shared.ts`\n * (`OLLAMA_PROVIDER_ID = \"ollama\"`) and Hermes `hermes_cli/providers.py`\n * (ALIASES table, `normalize_provider`).\n *\n * Public via `@theokit/sdk/models` (M5-8).\n *\n * @public\n */\n\nexport interface ParsedModelId {\n /** Provider name extracted from the prefix (lowercase), or undefined. */\n provider: string | undefined;\n /** Model name to send to the provider — prefix stripped. */\n name: string;\n}\n\n/** Provider aliases mirrored from Hermes `hermes_cli/providers.py` ALIASES. */\nconst PROVIDER_ALIASES: Readonly<Record<string, string>> = {\n \"llama-cpp\": \"llamacpp\",\n \"llama.cpp\": \"llamacpp\",\n \"lm-studio\": \"lmstudio\",\n lm_studio: \"lmstudio\",\n};\n\n/**\n * Split a model string into `{ provider, name }` at the FIRST `/`.\n *\n * parseModelId(\"ollama/llama3.2:3b\") // { provider: \"ollama\", name: \"llama3.2:3b\" }\n * parseModelId(\"openrouter/meta-llama/llama-3\") // { provider: \"openrouter\", name: \"meta-llama/llama-3\" }\n * parseModelId(\"claude-sonnet-4-6\") // { provider: undefined, name: \"claude-sonnet-4-6\" }\n *\n * Pure and synchronous: no catalog lookup, no network, and no check that the\n * provider or the model exists. The provider is lowercased and mapped through a\n * small alias table (`llama-cpp` / `llama.cpp` to `llamacpp`, `lm-studio` /\n * `lm_studio` to `lmstudio`); the name keeps its remaining slashes and any `:tag`\n * suffix, which Ollama needs.\n *\n * Never throws and never returns an error shape. `provider: undefined` means \"no\n * usable prefix\" and is the caller's cue to fall back to env-var detection.\n *\n * Traps:\n * - `undefined` or `\"\"` yields `{ provider: undefined, name: \"\" }` — an EMPTY\n * name, not `undefined`. A caller forwarding `name` unchecked sends an empty\n * model id to the provider.\n * - A degenerate prefix is not an error. `\"/foo\"`, `\"foo/\"` and `\" /x\"` all come\n * back with `provider: undefined` and the ORIGINAL, untrimmed string as `name`;\n * trimming happens only when both halves are non-empty.\n * - Only the first `/` splits. `\"openrouter/meta-llama/llama-3\"` keeps\n * `meta-llama/llama-3` whole as the name.\n */\nexport function parseModelId(modelId: string | undefined): ParsedModelId {\n if (modelId === undefined || modelId.length === 0) {\n return { provider: undefined, name: \"\" };\n }\n const slash = modelId.indexOf(\"/\");\n if (slash <= 0 || slash === modelId.length - 1) {\n return { provider: undefined, name: modelId };\n }\n const rawProvider = modelId.slice(0, slash).trim().toLowerCase();\n const name = modelId.slice(slash + 1).trim();\n if (rawProvider.length === 0 || name.length === 0) {\n return { provider: undefined, name: modelId };\n }\n const canonical = PROVIDER_ALIASES[rawProvider] ?? rawProvider;\n return { provider: canonical, name };\n}\n"]}
|