@theokit/sdk 4.53.0 → 4.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -8
- package/LICENSE +2 -2
- package/README.md +5 -5
- package/bin/theokit-migrate-config.mjs +11 -2
- package/dist/{agent-BiCINq25.d.ts → agent-B9HXlwID.d.ts} +21 -8
- package/dist/agent-FFVV4U5N.js +50 -0
- package/dist/{agent-ZAGG6ZBS.js.map → agent-FFVV4U5N.js.map} +1 -1
- package/dist/agent-YLAHVHEH.cjs +59 -0
- package/dist/{agent-JX5SBYDE.cjs.map → agent-YLAHVHEH.cjs.map} +1 -1
- package/dist/{agent-Zta1kvGH.d.cts → agent-nLqeXKIX.d.cts} +21 -8
- package/dist/agent-session-store-DUGBAX5V.cjs +23 -0
- package/dist/{agent-session-store-EPX2WQI4.cjs.map → agent-session-store-DUGBAX5V.cjs.map} +1 -1
- package/dist/agent-session-store-TNCGL5RN.js +6 -0
- package/dist/{agent-session-store-JMU7ASDB.js.map → agent-session-store-TNCGL5RN.js.map} +1 -1
- package/dist/agent.d.ts +16 -1
- package/dist/auth/index.cjs +18 -18
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +6 -6
- package/dist/auth/index.js.map +1 -1
- package/dist/{batch-NLIS4QTW.js → batch-UPKN4SG6.js} +9 -9
- package/dist/{batch-NLIS4QTW.js.map → batch-UPKN4SG6.js.map} +1 -1
- package/dist/{batch-WQ3AJCDV.cjs → batch-ZEFN5SO7.cjs} +26 -26
- package/dist/{batch-WQ3AJCDV.cjs.map → batch-ZEFN5SO7.cjs.map} +1 -1
- package/dist/{chunk-2QMK627M.cjs → chunk-2D43RD5D.cjs} +8 -8
- package/dist/{chunk-2QMK627M.cjs.map → chunk-2D43RD5D.cjs.map} +1 -1
- package/dist/{chunk-DM6Y5B2G.cjs → chunk-2FYEVT2B.cjs} +121 -121
- package/dist/{chunk-DM6Y5B2G.cjs.map → chunk-2FYEVT2B.cjs.map} +1 -1
- package/dist/{chunk-BBZYXVLZ.cjs → chunk-2ZPEDVLM.cjs} +2 -2
- package/dist/chunk-2ZPEDVLM.cjs.map +1 -0
- package/dist/{chunk-T6QUCG7L.cjs → chunk-3BK6YR5P.cjs} +4 -4
- package/dist/{chunk-T6QUCG7L.cjs.map → chunk-3BK6YR5P.cjs.map} +1 -1
- package/dist/{chunk-23VZBRDQ.js → chunk-3V7UJLQT.js} +3 -3
- package/dist/chunk-3V7UJLQT.js.map +1 -0
- package/dist/{chunk-ITQ4NO4P.js → chunk-3WVMJY7F.js} +3 -3
- package/dist/{chunk-ITQ4NO4P.js.map → chunk-3WVMJY7F.js.map} +1 -1
- package/dist/{chunk-RAACTJ7C.cjs → chunk-3X6PM7DU.cjs} +4 -4
- package/dist/{chunk-RAACTJ7C.cjs.map → chunk-3X6PM7DU.cjs.map} +1 -1
- package/dist/{chunk-DEZ75ET5.js → chunk-4Q4K4WB5.js} +3 -3
- package/dist/{chunk-DEZ75ET5.js.map → chunk-4Q4K4WB5.js.map} +1 -1
- package/dist/{chunk-4X3SBHPK.js → chunk-5F5NWKPN.js} +20 -4
- package/dist/chunk-5F5NWKPN.js.map +1 -0
- package/dist/{chunk-NUEL6RCZ.cjs → chunk-5YKNEMXR.cjs} +4 -4
- package/dist/chunk-5YKNEMXR.cjs.map +1 -0
- package/dist/{chunk-3YYDHUNH.cjs → chunk-665SFFFR.cjs} +11 -11
- package/dist/{chunk-3YYDHUNH.cjs.map → chunk-665SFFFR.cjs.map} +1 -1
- package/dist/{chunk-CHVSMEKM.js → chunk-6AZDM6LK.js} +3 -3
- package/dist/chunk-6AZDM6LK.js.map +1 -0
- package/dist/{chunk-AMYY3JHQ.cjs → chunk-ADLLFY3H.cjs} +9 -9
- package/dist/{chunk-AMYY3JHQ.cjs.map → chunk-ADLLFY3H.cjs.map} +1 -1
- package/dist/{chunk-634YVZLU.js → chunk-B6HOIWQ6.js} +5 -5
- package/dist/{chunk-634YVZLU.js.map → chunk-B6HOIWQ6.js.map} +1 -1
- package/dist/{chunk-EQMLJ52C.cjs → chunk-BDTVFIPB.cjs} +26 -26
- package/dist/{chunk-EQMLJ52C.cjs.map → chunk-BDTVFIPB.cjs.map} +1 -1
- package/dist/{chunk-UJ3SXRZZ.js → chunk-BERBYXFH.js} +3 -3
- package/dist/{chunk-UJ3SXRZZ.js.map → chunk-BERBYXFH.js.map} +1 -1
- package/dist/{chunk-KZBB4YKU.js → chunk-BFYGJGC5.js} +3 -3
- package/dist/{chunk-KZBB4YKU.js.map → chunk-BFYGJGC5.js.map} +1 -1
- package/dist/{chunk-SXSPMRSV.cjs → chunk-BM6N4KHO.cjs} +21 -3
- package/dist/chunk-BM6N4KHO.cjs.map +1 -0
- package/dist/{chunk-2CFEET3Y.cjs → chunk-C4H6PB5J.cjs} +4 -4
- package/dist/chunk-C4H6PB5J.cjs.map +1 -0
- package/dist/{chunk-NFATC6ZF.cjs → chunk-C5DEO6OI.cjs} +4 -4
- package/dist/{chunk-NFATC6ZF.cjs.map → chunk-C5DEO6OI.cjs.map} +1 -1
- package/dist/{chunk-EUBGGYPH.cjs → chunk-CZ2GKKYL.cjs} +5 -5
- package/dist/{chunk-EUBGGYPH.cjs.map → chunk-CZ2GKKYL.cjs.map} +1 -1
- package/dist/{chunk-I732VEDW.js → chunk-D24WJWN2.js} +3 -3
- package/dist/{chunk-I732VEDW.js.map → chunk-D24WJWN2.js.map} +1 -1
- package/dist/{chunk-3R4ZCQAZ.cjs → chunk-D75S2X6I.cjs} +5 -5
- package/dist/{chunk-3R4ZCQAZ.cjs.map → chunk-D75S2X6I.cjs.map} +1 -1
- package/dist/{chunk-5XXUYU3M.js → chunk-DGOG5NXR.js} +3 -3
- package/dist/{chunk-5XXUYU3M.js.map → chunk-DGOG5NXR.js.map} +1 -1
- package/dist/{chunk-RTLUZKDL.cjs → chunk-E7FJOO4G.cjs} +11 -11
- package/dist/{chunk-RTLUZKDL.cjs.map → chunk-E7FJOO4G.cjs.map} +1 -1
- package/dist/{chunk-BWGXYOBZ.cjs → chunk-ELKO4ZLR.cjs} +4 -4
- package/dist/{chunk-BWGXYOBZ.cjs.map → chunk-ELKO4ZLR.cjs.map} +1 -1
- package/dist/{chunk-FBZMSLDC.cjs → chunk-EZ2YEF4F.cjs} +4 -4
- package/dist/{chunk-FBZMSLDC.cjs.map → chunk-EZ2YEF4F.cjs.map} +1 -1
- package/dist/{chunk-2VFZQEDW.cjs → chunk-F77UENR6.cjs} +343 -324
- package/dist/chunk-F77UENR6.cjs.map +1 -0
- package/dist/{chunk-OZXPA3ME.js → chunk-FFM3SJTQ.js} +4 -4
- package/dist/{chunk-OZXPA3ME.js.map → chunk-FFM3SJTQ.js.map} +1 -1
- package/dist/{chunk-PLUCC4N5.js → chunk-FIOCJYLA.js} +3 -3
- package/dist/{chunk-PLUCC4N5.js.map → chunk-FIOCJYLA.js.map} +1 -1
- package/dist/{chunk-Z5U2JGEK.cjs → chunk-FOXKFTVZ.cjs} +11 -11
- package/dist/{chunk-Z5U2JGEK.cjs.map → chunk-FOXKFTVZ.cjs.map} +1 -1
- package/dist/{chunk-K42QGAKM.cjs → chunk-FPYT5WZP.cjs} +10 -10
- package/dist/{chunk-K42QGAKM.cjs.map → chunk-FPYT5WZP.cjs.map} +1 -1
- package/dist/{chunk-NZOR3N4E.js → chunk-G3JWXOGY.js} +78 -58
- package/dist/chunk-G3JWXOGY.js.map +1 -0
- package/dist/{chunk-DHVNJYTO.js → chunk-GBBDINFK.js} +3 -3
- package/dist/{chunk-DHVNJYTO.js.map → chunk-GBBDINFK.js.map} +1 -1
- package/dist/{chunk-V45L2OYP.cjs → chunk-GD63JPGC.cjs} +9 -9
- package/dist/{chunk-V45L2OYP.cjs.map → chunk-GD63JPGC.cjs.map} +1 -1
- package/dist/{chunk-I5OTK2RP.js → chunk-GOVJO4YE.js} +5 -5
- package/dist/{chunk-I5OTK2RP.js.map → chunk-GOVJO4YE.js.map} +1 -1
- package/dist/{chunk-CZHPR2G7.cjs → chunk-HAWE74GQ.cjs} +8 -8
- package/dist/{chunk-CZHPR2G7.cjs.map → chunk-HAWE74GQ.cjs.map} +1 -1
- package/dist/{chunk-KIX45IKP.js → chunk-HE4BIAOS.js} +4 -4
- package/dist/{chunk-KIX45IKP.js.map → chunk-HE4BIAOS.js.map} +1 -1
- package/dist/{chunk-AM2CNBKE.js → chunk-HKCKOAIO.js} +2 -2
- package/dist/chunk-HKCKOAIO.js.map +1 -0
- package/dist/{chunk-2YWWPCGX.js → chunk-HSQ5Q3I5.js} +10 -12
- package/dist/chunk-HSQ5Q3I5.js.map +1 -0
- package/dist/{chunk-QLAWEGTZ.cjs → chunk-JIQRXKTA.cjs} +7 -7
- package/dist/chunk-JIQRXKTA.cjs.map +1 -0
- package/dist/{chunk-EFXJ5C7X.js → chunk-KSWHTR54.js} +5 -5
- package/dist/{chunk-EFXJ5C7X.js.map → chunk-KSWHTR54.js.map} +1 -1
- package/dist/{chunk-6PTCKXD3.js → chunk-LD4MOBFX.js} +8 -8
- package/dist/{chunk-6PTCKXD3.js.map → chunk-LD4MOBFX.js.map} +1 -1
- package/dist/{chunk-2YGIBOUH.cjs → chunk-LPVIRJVF.cjs} +9 -9
- package/dist/chunk-LPVIRJVF.cjs.map +1 -0
- package/dist/{chunk-2Y5NO2SY.js → chunk-LS3LMQ23.js} +9 -9
- package/dist/{chunk-2Y5NO2SY.js.map → chunk-LS3LMQ23.js.map} +1 -1
- package/dist/{chunk-N43XLTHZ.js → chunk-LTSTGCL6.js} +3 -3
- package/dist/{chunk-N43XLTHZ.js.map → chunk-LTSTGCL6.js.map} +1 -1
- package/dist/{chunk-W4FV7JBH.js → chunk-MSFLYJDY.js} +4 -4
- package/dist/chunk-MSFLYJDY.js.map +1 -0
- package/dist/{chunk-C4EU627W.js → chunk-N5CR3TJZ.js} +4 -4
- package/dist/{chunk-C4EU627W.js.map → chunk-N5CR3TJZ.js.map} +1 -1
- package/dist/{chunk-HTK54K2J.js → chunk-NZL4BNFQ.js} +3 -3
- package/dist/{chunk-HTK54K2J.js.map → chunk-NZL4BNFQ.js.map} +1 -1
- package/dist/{chunk-T5ZWI3MC.cjs → chunk-OUOXM36O.cjs} +11 -11
- package/dist/{chunk-T5ZWI3MC.cjs.map → chunk-OUOXM36O.cjs.map} +1 -1
- package/dist/{chunk-BXVSBYGW.js → chunk-OY7O3Q6R.js} +5 -5
- package/dist/{chunk-BXVSBYGW.js.map → chunk-OY7O3Q6R.js.map} +1 -1
- package/dist/{chunk-L7EGRCKJ.js → chunk-PBZ7HMBP.js} +4 -4
- package/dist/{chunk-L7EGRCKJ.js.map → chunk-PBZ7HMBP.js.map} +1 -1
- package/dist/{chunk-OIBHY6JQ.js → chunk-PGP7IOJ2.js} +4 -4
- package/dist/{chunk-OIBHY6JQ.js.map → chunk-PGP7IOJ2.js.map} +1 -1
- package/dist/{chunk-R7TKOQMJ.js → chunk-POWRZSK4.js} +3 -3
- package/dist/{chunk-R7TKOQMJ.js.map → chunk-POWRZSK4.js.map} +1 -1
- package/dist/{chunk-R3CKCRK3.cjs → chunk-Q4RESANI.cjs} +4 -4
- package/dist/{chunk-R3CKCRK3.cjs.map → chunk-Q4RESANI.cjs.map} +1 -1
- package/dist/{chunk-QN5N3ZVT.cjs → chunk-QBTVATSF.cjs} +25 -24
- package/dist/chunk-QBTVATSF.cjs.map +1 -0
- package/dist/{chunk-ZSJPRPN7.js → chunk-R5YZACGK.js} +3 -3
- package/dist/{chunk-ZSJPRPN7.js.map → chunk-R5YZACGK.js.map} +1 -1
- package/dist/{chunk-ADVZIC43.cjs → chunk-RAHSWE5C.cjs} +10 -10
- package/dist/{chunk-ADVZIC43.cjs.map → chunk-RAHSWE5C.cjs.map} +1 -1
- package/dist/{chunk-NOS7PTKP.js → chunk-SEL2ZQMT.js} +7 -7
- package/dist/{chunk-NOS7PTKP.js.map → chunk-SEL2ZQMT.js.map} +1 -1
- package/dist/{chunk-XWCTBGYK.js → chunk-SK4QLUBK.js} +3 -3
- package/dist/chunk-SK4QLUBK.js.map +1 -0
- package/dist/{chunk-XRI6DXPZ.js → chunk-SSDD676S.js} +3 -3
- package/dist/chunk-SSDD676S.js.map +1 -0
- package/dist/{chunk-E3OCRJU6.cjs → chunk-SVO5WPZX.cjs} +11 -11
- package/dist/{chunk-E3OCRJU6.cjs.map → chunk-SVO5WPZX.cjs.map} +1 -1
- package/dist/{chunk-44IISBRZ.cjs → chunk-SZHU7A5B.cjs} +4 -4
- package/dist/{chunk-44IISBRZ.cjs.map → chunk-SZHU7A5B.cjs.map} +1 -1
- package/dist/{chunk-TR4V2LHV.cjs → chunk-TTJ54H3E.cjs} +5 -5
- package/dist/{chunk-TR4V2LHV.cjs.map → chunk-TTJ54H3E.cjs.map} +1 -1
- package/dist/{chunk-HI4ZW62S.js → chunk-U4UJHOSH.js} +4 -4
- package/dist/chunk-U4UJHOSH.js.map +1 -0
- package/dist/{chunk-XGYI2KQH.js → chunk-UFIXH26P.js} +4 -4
- package/dist/{chunk-XGYI2KQH.js.map → chunk-UFIXH26P.js.map} +1 -1
- package/dist/{chunk-JJZ4NIAG.js → chunk-V26QVGUG.js} +7 -6
- package/dist/chunk-V26QVGUG.js.map +1 -0
- package/dist/{chunk-3SHW7XKK.js → chunk-V6HWJQQV.js} +6 -5
- package/dist/chunk-V6HWJQQV.js.map +1 -0
- package/dist/{chunk-MV4TOCUK.js → chunk-VC5ABJXC.js} +3 -3
- package/dist/{chunk-MV4TOCUK.js.map → chunk-VC5ABJXC.js.map} +1 -1
- package/dist/{chunk-33L2NVTJ.cjs → chunk-VF7X6HDR.cjs} +8 -8
- package/dist/chunk-VF7X6HDR.cjs.map +1 -0
- package/dist/{chunk-7HQVDLFI.cjs → chunk-VGPXHHF3.cjs} +11 -9
- package/dist/chunk-VGPXHHF3.cjs.map +1 -0
- package/dist/{chunk-BC5EUG7R.cjs → chunk-VUKQL3L2.cjs} +18 -20
- package/dist/chunk-VUKQL3L2.cjs.map +1 -0
- package/dist/{chunk-PVBANCWU.cjs → chunk-VW6M4B3Z.cjs} +5 -5
- package/dist/{chunk-PVBANCWU.cjs.map → chunk-VW6M4B3Z.cjs.map} +1 -1
- package/dist/{chunk-KNZU4YO5.cjs → chunk-WQ53UQL4.cjs} +4 -4
- package/dist/{chunk-KNZU4YO5.cjs.map → chunk-WQ53UQL4.cjs.map} +1 -1
- package/dist/{chunk-6DCTL32L.cjs → chunk-XPR366DL.cjs} +17 -17
- package/dist/{chunk-6DCTL32L.cjs.map → chunk-XPR366DL.cjs.map} +1 -1
- package/dist/{chunk-7TB5U7RK.js → chunk-XROIW6BH.js} +6 -6
- package/dist/{chunk-7TB5U7RK.js.map → chunk-XROIW6BH.js.map} +1 -1
- package/dist/{chunk-ECPL5RV6.cjs → chunk-Y4AXQOT4.cjs} +8 -8
- package/dist/{chunk-ECPL5RV6.cjs.map → chunk-Y4AXQOT4.cjs.map} +1 -1
- package/dist/{chunk-E6T264NS.js → chunk-Y4I4EQFK.js} +3 -3
- package/dist/{chunk-E6T264NS.js.map → chunk-Y4I4EQFK.js.map} +1 -1
- package/dist/{chunk-FUASIT3E.cjs → chunk-ZN2DGEY3.cjs} +15 -15
- package/dist/{chunk-FUASIT3E.cjs.map → chunk-ZN2DGEY3.cjs.map} +1 -1
- package/dist/{chunk-YTO5BRBD.cjs → chunk-ZT57WTUJ.cjs} +8 -8
- package/dist/chunk-ZT57WTUJ.cjs.map +1 -0
- package/dist/compact-session-4MNKNMO2.js +21 -0
- package/dist/{compact-session-EJ36VH5I.js.map → compact-session-4MNKNMO2.js.map} +1 -1
- package/dist/compact-session-EPFBQ46Z.cjs +58 -0
- package/dist/{compact-session-6GKIS4SD.cjs.map → compact-session-EPFBQ46Z.cjs.map} +1 -1
- package/dist/compaction.cjs +16 -16
- package/dist/compaction.js +3 -3
- package/dist/concurrency.cjs +6 -6
- package/dist/concurrency.js +4 -4
- package/dist/context-7USNN6LP.cjs +22 -0
- package/dist/{context-4HGPCOH6.cjs.map → context-7USNN6LP.cjs.map} +1 -1
- package/dist/context-ENXZNF6J.js +5 -0
- package/dist/{context-DCECDKWN.js.map → context-ENXZNF6J.js.map} +1 -1
- package/dist/{cron-DyWQsEG6.d.ts → cron-BMjgFH-_.d.ts} +1 -1
- package/dist/{cron-DgHJnMAK.d.cts → cron-DFDdCdMM.d.cts} +1 -1
- package/dist/cron.cjs +33 -33
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +32 -32
- package/dist/errors.cjs +21 -21
- package/dist/errors.js +2 -2
- package/dist/eval.cjs +43 -43
- package/dist/eval.js +33 -33
- package/dist/{executor-4SW7QGZ4.cjs → executor-2Z3LGG3I.cjs} +24 -24
- package/dist/{executor-4SW7QGZ4.cjs.map → executor-2Z3LGG3I.cjs.map} +1 -1
- package/dist/{executor-3CGPLVJL.js → executor-2Z6XJJJG.js} +7 -7
- package/dist/{executor-3CGPLVJL.js.map → executor-2Z6XJJJG.js.map} +1 -1
- package/dist/filesystem/index.cjs +7 -7
- package/dist/filesystem/index.js +3 -3
- package/dist/fs-session-store-R5FD3EN6.js +10 -0
- package/dist/{fs-session-store-LIKYT24K.js.map → fs-session-store-R5FD3EN6.js.map} +1 -1
- package/dist/fs-session-store-VVY2AHWG.cjs +19 -0
- package/dist/{fs-session-store-VXXDIBGM.cjs.map → fs-session-store-VVY2AHWG.cjs.map} +1 -1
- package/dist/generate-object-AVXOJK2I.cjs +20 -0
- package/dist/{generate-object-E465DX5I.cjs.map → generate-object-AVXOJK2I.cjs.map} +1 -1
- package/dist/generate-object-WQRCXFD2.js +7 -0
- package/dist/{generate-object-TVQCW2IZ.js.map → generate-object-WQRCXFD2.js.map} +1 -1
- package/dist/index-manager-VRU3A2YL.cjs +21 -0
- package/dist/{index-manager-HGGL4DD5.cjs.map → index-manager-VRU3A2YL.cjs.map} +1 -1
- package/dist/index-manager-WS7TVKUW.js +12 -0
- package/dist/{index-manager-EA6FGIQG.js.map → index-manager-WS7TVKUW.js.map} +1 -1
- package/dist/index.cjs +143 -135
- package/dist/index.d.cts +64 -8
- package/dist/index.d.ts +64 -8
- package/dist/index.js +45 -45
- package/dist/{inject-session-67SF65FC.cjs → inject-session-AUQLBDRS.cjs} +9 -9
- package/dist/{inject-session-67SF65FC.cjs.map → inject-session-AUQLBDRS.cjs.map} +1 -1
- package/dist/{inject-session-HO7FYVCX.js → inject-session-GMBMJVNZ.js} +7 -7
- package/dist/{inject-session-HO7FYVCX.js.map → inject-session-GMBMJVNZ.js.map} +1 -1
- package/dist/internal/auth/auth-types.d.ts +1 -1
- package/dist/internal/auth/oauth-device.d.ts +2 -2
- package/dist/internal/local-agent/mcp-pool.d.ts +2 -4
- package/dist/internal/mcp/oauth.d.ts +14 -1
- package/dist/internal/mcp/token-storage.d.ts +18 -1
- package/dist/internal/memory/adapters/index.cjs +8 -8
- package/dist/internal/memory/adapters/index.js +7 -7
- package/dist/internal/persistence/atomic-write.d.cts +93 -0
- package/dist/internal/persistence/atomic-write.d.ts +93 -0
- package/dist/internal/persistence/file-lock.d.cts +13 -1
- package/dist/internal/persistence/file-lock.d.ts +13 -1
- package/dist/internal/persistence/fts5-sanitize.d.cts +9 -1
- package/dist/internal/persistence/fts5-sanitize.d.ts +9 -1
- package/dist/internal/persistence/index.cjs +25 -25
- package/dist/internal/persistence/index.js +6 -6
- package/dist/internal/persistence/session-dir.d.cts +1 -0
- package/dist/internal/persistence/session-dir.d.ts +1 -0
- package/dist/internal/persistence/session-writer.d.cts +13 -0
- package/dist/internal/persistence/session-writer.d.ts +13 -0
- package/dist/internal/persistence/sqlite-wal.d.cts +9 -1
- package/dist/internal/persistence/sqlite-wal.d.ts +9 -1
- package/dist/internal/providers/builtin/cerebras.d.ts +2 -2
- package/dist/internal/providers/builtin/deepinfra.d.ts +1 -1
- package/dist/internal/providers/catalog-source-models-dev.d.ts +1 -1
- package/dist/internal/runtime/lifecycle/env-policy.d.ts +1 -3
- package/dist/internal/security/index.cjs +13 -13
- package/dist/internal/security/index.js +3 -3
- package/dist/internal/security/path-guard.d.cts +61 -0
- package/dist/internal/security/path-guard.d.ts +61 -0
- package/dist/internal/session/compact-session.d.ts +2 -2
- package/dist/internal/telemetry/tracer.d.ts +24 -0
- package/dist/judge-call-G5SGV2M2.cjs +22 -0
- package/dist/{judge-call-GVIJWQVE.cjs.map → judge-call-G5SGV2M2.cjs.map} +1 -1
- package/dist/judge-call-MDIPTBJI.js +5 -0
- package/dist/{judge-call-QMKGC2ZK.js.map → judge-call-MDIPTBJI.js.map} +1 -1
- package/dist/mcp-auth.cjs +14 -14
- package/dist/mcp-auth.cjs.map +1 -1
- package/dist/mcp-auth.js +4 -4
- package/dist/mcp-auth.js.map +1 -1
- package/dist/models.cjs +22 -22
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +7 -7
- package/dist/models.js.map +1 -1
- package/dist/path-safety.cjs +10 -10
- package/dist/path-safety.js +3 -3
- package/dist/persistence.cjs +28 -28
- package/dist/persistence.js +8 -8
- package/dist/project.cjs +5 -5
- package/dist/project.js +3 -3
- package/dist/registry-63ASMXT4.cjs +46 -0
- package/dist/{registry-UBY26R4I.cjs.map → registry-63ASMXT4.cjs.map} +1 -1
- package/dist/registry-O7FJ2MPM.js +9 -0
- package/dist/{registry-GC7BQMSV.js.map → registry-O7FJ2MPM.js.map} +1 -1
- package/dist/retry.cjs +4 -4
- package/dist/retry.js +3 -3
- package/dist/sandbox/bwrap.d.cts +1 -2
- package/dist/sandbox/bwrap.d.ts +1 -2
- package/dist/sandbox/index.cjs +20 -20
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +5 -5
- package/dist/sandbox/index.js.map +1 -1
- package/dist/server/errors-envelope.cjs +14 -14
- package/dist/server/errors-envelope.js +3 -3
- package/dist/session-transcript-DOM3UTXR.cjs +50 -0
- package/dist/{session-transcript-TNAJ4O3M.cjs.map → session-transcript-DOM3UTXR.cjs.map} +1 -1
- package/dist/session-transcript-RAKEK76V.js +5 -0
- package/dist/{session-transcript-SKIRBEJE.js.map → session-transcript-RAKEK76V.js.map} +1 -1
- package/dist/skills.cjs +7 -7
- package/dist/skills.js +5 -5
- package/dist/stream-object-L3Q7PBMF.cjs +20 -0
- package/dist/{stream-object-T4DAMNVB.cjs.map → stream-object-L3Q7PBMF.cjs.map} +1 -1
- package/dist/stream-object-ZYXWS4B2.js +7 -0
- package/dist/{stream-object-QMNR3YFF.js.map → stream-object-ZYXWS4B2.js.map} +1 -1
- package/dist/subagents-loader-I56GSKAQ.js +6 -0
- package/dist/{subagents-loader-WN2SB6PV.js.map → subagents-loader-I56GSKAQ.js.map} +1 -1
- package/dist/subagents-loader-VRW73QQT.cjs +15 -0
- package/dist/{subagents-loader-3CXBQWWY.cjs.map → subagents-loader-VRW73QQT.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +6 -6
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subagents-loader.js +4 -4
- package/dist/subscription/index.cjs +3 -3
- package/dist/subscription/index.js +2 -2
- package/dist/task-store.cjs +7 -7
- package/dist/task-store.js +4 -4
- package/dist/types/agent.d.ts +19 -6
- package/dist/types/provider-profile.d.ts +2 -2
- package/dist/workflow.cjs +27 -27
- package/dist/workflow.js +6 -6
- package/package.json +18 -18
- package/dist/agent-JX5SBYDE.cjs +0 -59
- package/dist/agent-ZAGG6ZBS.js +0 -50
- package/dist/agent-session-store-EPX2WQI4.cjs +0 -23
- package/dist/agent-session-store-JMU7ASDB.js +0 -6
- package/dist/chunk-23VZBRDQ.js.map +0 -1
- package/dist/chunk-2CFEET3Y.cjs.map +0 -1
- package/dist/chunk-2VFZQEDW.cjs.map +0 -1
- package/dist/chunk-2YGIBOUH.cjs.map +0 -1
- package/dist/chunk-2YWWPCGX.js.map +0 -1
- package/dist/chunk-33L2NVTJ.cjs.map +0 -1
- package/dist/chunk-3SHW7XKK.js.map +0 -1
- package/dist/chunk-4X3SBHPK.js.map +0 -1
- package/dist/chunk-7HQVDLFI.cjs.map +0 -1
- package/dist/chunk-AM2CNBKE.js.map +0 -1
- package/dist/chunk-BBZYXVLZ.cjs.map +0 -1
- package/dist/chunk-BC5EUG7R.cjs.map +0 -1
- package/dist/chunk-CHVSMEKM.js.map +0 -1
- package/dist/chunk-HI4ZW62S.js.map +0 -1
- package/dist/chunk-JJZ4NIAG.js.map +0 -1
- package/dist/chunk-NUEL6RCZ.cjs.map +0 -1
- package/dist/chunk-NZOR3N4E.js.map +0 -1
- package/dist/chunk-QLAWEGTZ.cjs.map +0 -1
- package/dist/chunk-QN5N3ZVT.cjs.map +0 -1
- package/dist/chunk-SXSPMRSV.cjs.map +0 -1
- package/dist/chunk-W4FV7JBH.js.map +0 -1
- package/dist/chunk-XRI6DXPZ.js.map +0 -1
- package/dist/chunk-XWCTBGYK.js.map +0 -1
- package/dist/chunk-YTO5BRBD.cjs.map +0 -1
- package/dist/compact-session-6GKIS4SD.cjs +0 -58
- package/dist/compact-session-EJ36VH5I.js +0 -21
- package/dist/context-4HGPCOH6.cjs +0 -22
- package/dist/context-DCECDKWN.js +0 -5
- package/dist/fs-session-store-LIKYT24K.js +0 -10
- package/dist/fs-session-store-VXXDIBGM.cjs +0 -19
- package/dist/generate-object-E465DX5I.cjs +0 -20
- package/dist/generate-object-TVQCW2IZ.js +0 -7
- package/dist/index-manager-EA6FGIQG.js +0 -12
- package/dist/index-manager-HGGL4DD5.cjs +0 -21
- package/dist/judge-call-GVIJWQVE.cjs +0 -22
- package/dist/judge-call-QMKGC2ZK.js +0 -5
- package/dist/registry-GC7BQMSV.js +0 -9
- package/dist/registry-UBY26R4I.cjs +0 -46
- package/dist/session-transcript-SKIRBEJE.js +0 -5
- package/dist/session-transcript-TNAJ4O3M.cjs +0 -50
- package/dist/stream-object-QMNR3YFF.js +0 -7
- package/dist/stream-object-T4DAMNVB.cjs +0 -20
- package/dist/subagents-loader-3CXBQWWY.cjs +0 -15
- package/dist/subagents-loader-WN2SB6PV.js +0 -6
- package/docs/error-codes.md +0 -179
- package/docs/harness-capability-map.md +0 -304
|
@@ -55,5 +55,5 @@ function resolveChildEnv(options = {}) {
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
exports.resolveChildEnv = resolveChildEnv;
|
|
58
|
-
//# sourceMappingURL=chunk-
|
|
59
|
-
//# sourceMappingURL=chunk-
|
|
58
|
+
//# sourceMappingURL=chunk-2ZPEDVLM.cjs.map
|
|
59
|
+
//# sourceMappingURL=chunk-2ZPEDVLM.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/lifecycle/env-policy.ts"],"names":[],"mappings":";;;AAiDA,IAAM,eAAA,GAAqC;AAAA,EACzC,MAAA;AAAA,EACA,SAAA;AAAA,EACA,QAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EACA,UAAA;AAAA,EACA,aAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAAA,EACA,wBAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAMA,IAAM,SAAA,GAA+B;AAAA,EACnC,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAA;AAEA,SAAS,aAAa,IAAA,EAAuB;AAC3C,EAAA,OAAO,gBAAgB,IAAA,CAAK,CAAC,OAAO,EAAA,CAAG,IAAA,CAAK,IAAI,CAAC,CAAA;AACnD;AAGA,SAAS,mBAAA,CAAoB,MAAc,MAAA,EAA4B;AACrE,EAAA,IAAI,MAAA,KAAW,OAAO,OAAO,IAAA;AAC7B,EAAA,IAAI,MAAA,KAAW,MAAA,EAAQ,OAAO,SAAA,CAAU,SAAS,IAAI,CAAA;AACrD,EAAA,OAAO,CAAC,aAAa,IAAI,CAAA;AAC3B;AAEO,SAAS,eAAA,CAAgB,OAAA,GAAkC,EAAC,EAA2B;AAC5F,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,GAAA;AACzC,EAAA,MAAM,MAAA,GAAS,QAAQ,MAAA,IAAU,kBAAA;AAEjC,EAAA,MAAM,OAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClD,IAAA,IAAI,KAAA,KAAU,UAAa,mBAAA,CAAoB,IAAA,EAAM,MAAM,CAAA,EAAG,IAAA,CAAK,IAAI,CAAA,GAAI,KAAA;AAAA,EAC7E;AAGA,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,CAAA,IAAK,MAAA,CAAO,QAAQ,OAAA,CAAQ,SAAA,IAAa,EAAE,CAAA,EAAG;AACnE,IAAA,IAAA,CAAK,IAAI,CAAA,GAAI,KAAA;AAAA,EACf;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-2ZPEDVLM.cjs","sourcesContent":["/**\n * Child-process environment policy (#54).\n *\n * Every subprocess the SDK spawns previously inherited the FULL `process.env`,\n * so API keys, tokens and passwords leaked into hook scripts and shell tools.\n * `resolveChildEnv` computes the env a child receives under an explicit policy.\n *\n * Modes:\n * - `inherit-scrubbed` (DEFAULT) — inherit all parent vars EXCEPT secret-like\n * names (`*KEY*`, `*SECRET*`, `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Non-breaking:\n * existing spawns keep every non-secret var; only secrets stop leaking.\n * - `core` — inherit ONLY a safe base allowlist (PATH/HOME/…); strongest scrub.\n * - `all` — explicit opt-out: inherit everything, secrets included.\n *\n * Explicit `overrides` ALWAYS win (merged last), so a tool can re-inject a var\n * it genuinely needs even under a scrubbing policy.\n *\n * @internal\n */\n\nimport type { EnvPolicy } from \"../../../types/env-policy.js\";\n\n// The `EnvPolicy` contract now lives in the domain `types/` layer (SE46 DIP\n// direction). Re-exported here so existing importers of this module keep\n// resolving the same name.\nexport type { EnvPolicy } from \"../../../types/env-policy.js\";\n\nexport interface ResolveChildEnvOptions {\n /** Source env to derive from. Defaults to `process.env`. */\n parent?: Record<string, string | undefined>;\n /** Inherit/scrub policy. Defaults to `inherit-scrubbed`. */\n policy?: EnvPolicy;\n /** Explicit vars merged AFTER the policy — always win. */\n overrides?: Record<string, string>;\n}\n\n/**\n * Secret-like variable-name patterns (case-insensitive). A parent var whose\n * name matches any of these is dropped under `inherit-scrubbed`. Conservative\n * by design — see the EC-4 false-positive test. `[_-]PWD` (not bare `PWD`)\n * catches `DB_PWD` without dropping the shell's working-directory `PWD`.\n * `CREDENTIAL` catches `GOOGLE_APPLICATION_CREDENTIALS`. #54-a extends the list to\n * the highest-signal VALUE-embedded-secret conventions — connection strings that\n * carry `user:password@` (`DATABASE_URL`, `REDIS_URL`, `MONGODB_URI`, `DB_URL`, …),\n * `DSN`, `WEBHOOK`, `COOKIE`, and `CONNECTION_STRING` — while deliberately NOT\n * dropping generic non-secret URLs (`PUBLIC_BASE_URL`, `API_URL`, `PGHOST`). A\n * denylist still cannot catch EVERY value-embedded secret — for untrusted children\n * use policy `\"core\"` (allowlist), the only fail-closed mode.\n */\nconst SECRET_PATTERNS: readonly RegExp[] = [\n /KEY/i,\n /SECRET/i,\n /TOKEN/i,\n /PASSWORD/i,\n /PASSWD/i,\n /PASSPHRASE/i,\n /[_-]PWD/i,\n /CREDENTIAL/i,\n /PRIVATE/i,\n /_AUTH/i,\n // #54-a — value-embedded-secret conventions (no generic `*_URL` — see keep-list test).\n /DSN/i,\n /WEBHOOK/i,\n /COOKIE/i,\n /CONNECTION[_-]?STRING/i,\n // Known DB / message-broker connection-string vars (carry `user:pass@`).\n /(?:^|[_-])(?:DATABASE|DB|REDIS|MONGO(?:DB)?|POSTGRES(?:QL)?|MYSQL|MARIADB|AMQP|RABBITMQ|CLICKHOUSE|ELASTIC(?:SEARCH)?|CASSANDRA|COUCHDB|MEMCACHED|NATS|KAFKA)[_-]?(?:URL|URI|DSN|CONNECTION)/i,\n];\n\n/**\n * Safe base variables kept under the `core` policy. Process-hygiene vars a\n * child almost always needs; none are secret-bearing.\n */\nconst CORE_VARS: readonly string[] = [\n \"PATH\",\n \"HOME\",\n \"SHELL\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TMPDIR\",\n \"TMP\",\n \"TEMP\",\n \"USER\",\n \"LOGNAME\",\n];\n\nfunction isSecretName(name: string): boolean {\n return SECRET_PATTERNS.some((re) => re.test(name));\n}\n\n/** Whether a parent var of the given name is inherited under `policy`. */\nfunction inheritsUnderPolicy(name: string, policy: EnvPolicy): boolean {\n if (policy === \"all\") return true;\n if (policy === \"core\") return CORE_VARS.includes(name);\n return !isSecretName(name); // inherit-scrubbed\n}\n\nexport function resolveChildEnv(options: ResolveChildEnvOptions = {}): Record<string, string> {\n const parent = options.parent ?? process.env;\n const policy = options.policy ?? \"inherit-scrubbed\";\n\n const base: Record<string, string> = {};\n for (const [name, value] of Object.entries(parent)) {\n if (value !== undefined && inheritsUnderPolicy(name, policy)) base[name] = value;\n }\n\n // Explicit overrides always win — even over a scrub.\n for (const [name, value] of Object.entries(options.overrides ?? {})) {\n base[name] = value;\n }\n return base;\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
|
|
4
4
|
var fs = require('fs');
|
|
5
5
|
var os = require('os');
|
|
6
6
|
|
|
7
|
-
var SessionBusyError = class extends
|
|
7
|
+
var SessionBusyError = class extends chunkLPVIRJVF_cjs.TheokitAgentError {
|
|
8
8
|
constructor(sessionPath) {
|
|
9
9
|
super(
|
|
10
10
|
`another process is already writing this session: ${sessionPath}. Fork it to a new id instead of appending \u2014 two writers interleave lines into a sequence that parses but is not what either process wrote.`,
|
|
@@ -107,5 +107,5 @@ function createLease(sessionPath, lockPath) {
|
|
|
107
107
|
exports.SessionBusyError = SessionBusyError;
|
|
108
108
|
exports.acquireSessionWriter = acquireSessionWriter;
|
|
109
109
|
exports.sessionHasWriter = sessionHasWriter;
|
|
110
|
-
//# sourceMappingURL=chunk-
|
|
111
|
-
//# sourceMappingURL=chunk-
|
|
110
|
+
//# sourceMappingURL=chunk-3BK6YR5P.cjs.map
|
|
111
|
+
//# sourceMappingURL=chunk-3BK6YR5P.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAiDO,IAAM,mBAAA,GAAsB,GAAA;AAUnC,SAAS,QAAA,GAAsB;AAC7B,EAAA,OAAO,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAK,QAAA,EAAUC,aAAS,EAAG,KAAA,EAAO,IAAA,CAAK,GAAA,EAAI,EAAE;AACrE;AAWA,SAAS,UAAA,CAAW,UAAkB,KAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAKC,WAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAAC,YAAA,CAAU,EAAA,EAAI,IAAA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ACZ,EAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AAEzB,EAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAC1C;AAGA,SAAS,WAAA,CAAY,aAAqB,QAAA,EAAsC;AAC9E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAAG,SAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC,CAAA;AAAA,IACA,OAAO,MAAY;AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-T6QUCG7L.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n * @internal\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,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AKL,WAAA,CAAS,QAAA,EAAU,IAAA,EAAM,GAAK,CAAA;AAAA,EACrC,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,IAAA,KAAS,QAAA,EAAU,MAAM,GAAA;AAI5D,IAAA,IAAI,CAAC,YAAY,SAAA,CAAU,QAAQ,CAAC,CAAA,EAAG,MAAM,IAAI,gBAAA,CAAiB,WAAW,CAAA;AAC7E,IAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AACzB,IAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAAA,EAC1C;AACA,EAAAG,YAAA,CAAU,EAAE,CAAA;AACZ,EAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AAEzB,EAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAC1C;AAGA,SAAS,WAAA,CAAY,aAAqB,QAAA,EAAsC;AAC9E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAAG,SAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC,CAAA;AAAA,IACA,OAAO,MAAY;AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-3BK6YR5P.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AuthenticationError } from './chunk-
|
|
1
|
+
import { AuthenticationError } from './chunk-U4UJHOSH.js';
|
|
2
2
|
import { randomBytes } from 'crypto';
|
|
3
3
|
import { statSync, readFileSync, mkdirSync, chmodSync, openSync, writeFileSync, fsyncSync, closeSync, renameSync, unlinkSync } from 'fs';
|
|
4
4
|
import { join } from 'path';
|
|
@@ -143,5 +143,5 @@ function writeCredential(cred, config, env = {}) {
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
export { CredentialError, assertSecureModes, authFilePath, credentialHome, readAuthFile, readStoredOAuth, writeCredential };
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
146
|
+
//# sourceMappingURL=chunk-3V7UJLQT.js.map
|
|
147
|
+
//# sourceMappingURL=chunk-3V7UJLQT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/auth/credential-store.ts"],"names":[],"mappings":";;;;;;AAwCO,SAAS,cAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,MAAM,QAAA,GAAW,OAAO,UAAA,KAAe,MAAA,GAAY,IAAI,MAAA,CAAO,UAAU,CAAA,EAAG,IAAA,EAAK,GAAI,MAAA;AACpF,EAAA,OAAO,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,GAC/C,WACA,IAAA,CAAK,MAAA,CAAO,IAAA,EAAM,MAAA,CAAO,OAAO,CAAA;AACtC;AAGO,SAAS,YAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,OAAO,KAAK,cAAA,CAAe,MAAA,EAAQ,GAAG,CAAA,EAAG,OAAO,QAAQ,CAAA;AAC1D;AAmBO,IAAM,eAAA,GAAN,cAA8B,mBAAA,CAAoB;AAAA;AAAA;AAAA;AAAA,EAIrC,IAAA,GAAe,iBAAA;AACnC;AAOA,IAAM,aAAA,GAAgB,EACnB,MAAA,CAAO;AAAA,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AACpC,IAAA,IAAI;AACF,MAAA,aAAA,CAAc,IAAI,CAAA,EAAG,IAAA,CAAK,UAAU,OAAA,EAAS,IAAA,EAAM,CAAC,CAAC;AAAA,CAAI,CAAA;AACzD,MAAA,SAAA,CAAU,EAAE,CAAA;AAAA,IACd,CAAA,SAAE;AACA,MAAA,SAAA,CAAU,EAAE,CAAA;AAAA,IACd;AACA,IAAA,SAAA,CAAU,KAAK,GAAK,CAAA;AACpB,IAAA,UAAA,CAAW,KAAK,IAAI,CAAA;AAAA,EACtB,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI;AACF,MAAA,UAAA,CAAW,GAAG,CAAA;AAAA,IAChB,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,eAAA,CAAgB,CAAA,aAAA,EAAgB,IAAI,CAAA,EAAA,EAAM,GAAA,CAAc,OAAO,CAAA,CAAE,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-3V7UJLQT.js","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { AuthenticationError } from \"../../errors.js\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * @internal\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/**\n * A credential problem the caller can act on. Never carries the key value.\n *\n * M78 — this used to extend bare `Error`, which quietly disabled classification for the entire auth\n * path: `isTransientError` is `err instanceof TheokitAgentError && err.isRetryable === true`\n * (`errors.ts:443`), so a credential failure could never be judged transient OR permanent. The\n * predicate was not \"forgotten\" downstream — it was unusable there by construction.\n *\n * Extending `AuthenticationError` is ADDITIVE: the class still exists, still reports\n * `name: \"CredentialError\"`, and every existing `instanceof CredentialError` stays true. It only\n * gains ancestors. `AuthenticationError` pins `isRetryable: false`, so gaining the ability to be\n * classified does NOT turn a revoked credential into a retry loop.\n *\n * The single reference does the same thing with one root type: Codex routes every domain failure\n * through `CodexErr` with `is_retryable()` as a method (`protocol/src/error.rs:176`), rather than\n * parallel classes extending the language's `Error`.\n */\nexport class CredentialError extends AuthenticationError {\n // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`\n // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the\n // suite was green with the broken assignment because the transpiler strips the type.\n override readonly name: string = \"CredentialError\";\n}\n\n/**\n * The on-disk store — a discriminated union on `type`. A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nexport function assertSecureModes(dirPath: string, path: string): void {\n // Windows has no POSIX mode bits. `statSync().mode` there is SYNTHETIC — 0666 for any writable\n // entry, whatever the ACLs actually say — so `mode & 0o022` was non-zero for every valid store and\n // this gate refused all of them, which made the credential path unreadable on that platform\n // rather than protected. A check that cannot observe the real permission system must not report a\n // verdict about it; ACL enforcement is a separate mechanism and not one this function can fake.\n if (process.platform === \"win32\") return;\n\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createSemaphore } from './chunk-
|
|
1
|
+
import { createSemaphore } from './chunk-R5YZACGK.js';
|
|
2
2
|
|
|
3
3
|
// src/internal/runtime/concurrency/map-with-concurrency.ts
|
|
4
4
|
var NEVER_ABORT = new AbortController().signal;
|
|
@@ -21,5 +21,5 @@ async function mapWithConcurrency(items, concurrency, fn, options) {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export { mapWithConcurrency };
|
|
24
|
-
//# sourceMappingURL=chunk-
|
|
25
|
-
//# sourceMappingURL=chunk-
|
|
24
|
+
//# sourceMappingURL=chunk-3WVMJY7F.js.map
|
|
25
|
+
//# sourceMappingURL=chunk-3WVMJY7F.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,I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AE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-3WVMJY7F.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
|
|
5
5
|
var async_hooks = require('async_hooks');
|
|
6
6
|
|
|
7
7
|
// src/internal/llm/credential-pool-types.ts
|
|
@@ -70,7 +70,7 @@ var CredentialPool = class _CredentialPool {
|
|
|
70
70
|
entries;
|
|
71
71
|
constructor(provider, entries, strategy = "fill_first") {
|
|
72
72
|
if (entries.length === 0) {
|
|
73
|
-
throw new
|
|
73
|
+
throw new chunkLPVIRJVF_cjs.ConfigurationError(
|
|
74
74
|
`credential-pool: cannot construct empty pool for provider "${provider}"`,
|
|
75
75
|
{ code: "credential_pool_empty" }
|
|
76
76
|
);
|
|
@@ -292,5 +292,5 @@ exports.currentCredentialPool = currentCredentialPool;
|
|
|
292
292
|
exports.newPooledCredential = newPooledCredential;
|
|
293
293
|
exports.sleepWithAbort = sleepWithAbort;
|
|
294
294
|
exports.withCredentialPool = withCredentialPool;
|
|
295
|
-
//# sourceMappingURL=chunk-
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
295
|
+
//# sourceMappingURL=chunk-3X6PM7DU.cjs.map
|
|
296
|
+
//# sourceMappingURL=chunk-3X6PM7DU.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,c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AA,MAAM,UAAU,KAAA,CAAM,gBAAA;AACtB,MAAA,IAAI,OAAA,KAAY,MAAA,IAAa,GAAA,IAAO,OAAA,EAAS;AAC3C,QAAA,KAAA,CAAM,UAAA,GAAa,IAAA;AACnB,QAAA,KAAA,CAAM,YAAA,GAAe,MAAA;AACrB,QAAA,KAAA,CAAM,aAAA,GAAgB,MAAA;AACtB,QAAA,KAAA,CAAM,gBAAA,GAAmB,MAAA;AACzB,QAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;AAMA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAA0B,EAAC;AACjC,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAIC,6BAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-RAACTJ7C.cjs","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AAchB,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,MAAM,IAAA,GAAO,KAAK,MAAA,IAAU,eAAA;AAC5B,EAAA,MAAM,GAAA,GAAM,KAAK,KAAA,IAAS,cAAA;AAC1B,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,IAAA,CAAK,MAAA;AAC7B,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,IAAa,IAAA,CAAK,gBAAgB,CAAA,EAAG;AAC7D,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAM,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,YAAY,CAAC,CAAA;AAAA,EACxD;AACA,EAAA,MAAM,UAAU,IAAA,CAAK,GAAA,CAAI,KAAK,IAAA,GAAO,CAAA,IAAK,KAAK,OAAO,CAAA;AACtD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,EAAI,GAAI,OAAO,CAAA;AACnC;AASO,SAAS,cAAA,CAAe,IAAY,MAAA,EAAoC;A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AA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAIC,6BAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-3X6PM7DU.cjs","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveChildEnv } from './chunk-
|
|
1
|
+
import { resolveChildEnv } from './chunk-HKCKOAIO.js';
|
|
2
2
|
import { execFile } from 'child_process';
|
|
3
3
|
import { mkdir, writeFile } from 'fs/promises';
|
|
4
4
|
import { dirname } from 'path';
|
|
@@ -125,5 +125,5 @@ var LocalSandbox = class extends SandboxBackend {
|
|
|
125
125
|
};
|
|
126
126
|
|
|
127
127
|
export { LocalSandbox, SandboxBackend, SandboxNotAvailableError, SandboxSecurityError, resolveSandbox, shellEscapePosix };
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
129
|
-
//# sourceMappingURL=chunk-
|
|
128
|
+
//# sourceMappingURL=chunk-4Q4K4WB5.js.map
|
|
129
|
+
//# sourceMappingURL=chunk-4Q4K4WB5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,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,CAAA;AAAA,MACvC;AAAA,KACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAA,CAAW,IAAA,EAAc,OAAA,EAAyC;AACtE,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,GAAI,IAAA,GAAO,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAC7E,IAAA,MAAM,MAAM,OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,IAAA,MAAMA,SAAA,CAAY,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AAAA,EAC9C;AACF","file":"chunk-DEZ75ET5.js","sourcesContent":["/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport type { EnvPolicy } from \"../types/env-policy.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n /**\n * #54 — env inherit/scrub policy for the executed command's child process.\n * Defaults to `\"inherit-scrubbed\"` (drop secret-like vars: `*KEY*`, `*SECRET*`,\n * `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Pass `\"all\"` to restore full inheritance\n * or `\"core\"` for a minimal safe allowlist.\n */\n env?: EnvPolicy;\n}\n\nexport class SandboxSecurityError extends Error {\n readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxSecurityError\";\n }\n}\n\nexport class SandboxNotAvailableError extends Error {\n readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxNotAvailableError\";\n }\n}\n\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n // #54 — preserve the env policy so backends can scrub secrets.\n env: config.env ?? \"inherit-scrubbed\",\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n\n/**\n * A backend OR a per-request resolver of one — mirrors `FilesystemProvider` / `InteractiveProvider`.\n * A resolver runs at tool-execution time (request scope), so a multi-tenant / multi-role agent gets a\n * distinct sandbox per request without a shared mutable one. This is how a tool takes execution as an\n * INJECTED capability: the same tool runs on a local sandbox, a container/E2B backend (cluster/web), or\n * any future backend, with no direct `child_process` import.\n *\n * @public\n */\nexport type SandboxProvider<Ctx = unknown> =\n | SandboxBackend\n | ((ctx: Ctx) => SandboxBackend | Promise<SandboxBackend>);\n\n/** Resolve a {@link SandboxProvider} to a concrete backend for `ctx`. */\nexport async function resolveSandbox<Ctx>(\n provider: SandboxProvider<Ctx>,\n ctx: Ctx,\n): Promise<SandboxBackend> {\n return provider instanceof SandboxBackend ? provider : provider(ctx);\n}\n","/**\n * LocalSandbox — subprocess-based execution. **This is NOT an isolation\n * boundary.** It runs the command via `/bin/sh -c` in the SAME OS as the host\n * with the host's filesystem and network fully reachable — it provides NO\n * process, filesystem, or network isolation. Its only safety affordances are:\n * - a wall-clock timeout (kills a runaway command),\n * - an output-size cap (bounds memory), and\n * - env scrubbing (#54): secret-like parent env vars (`*KEY*`/`*SECRET*`/\n * `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`) are dropped from the child by default\n * (`SandboxConfig.env`), so a shell tool cannot exfiltrate host secrets via\n * the environment.\n *\n * For real isolation (untrusted code), use a container/VM backend — NOT this.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { resolveChildEnv } from \"../internal/runtime/lifecycle/env-policy.js\";\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n // #54 — scrub secret-like host env vars from the child by default.\n env: resolveChildEnv({ policy: this.config.env }),\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n return {\n stdout: this.truncateOutput(stdout),\n stderr: this.truncateOutput(stderr),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/shell-escape.ts","../src/sandbox/types.ts","../src/sandbox/local-sandbox.ts"],"names":["fsWriteFile"],"mappings":";;;;;;AASO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;;;ACsBO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;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OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,IAAA,MAAMA,SAAA,CAAY,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AAAA,EAC9C;AACF","file":"chunk-4Q4K4WB5.js","sourcesContent":["/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport type { EnvPolicy } from \"../types/env-policy.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n /**\n * #54 — env inherit/scrub policy for the executed command's child process.\n * Defaults to `\"inherit-scrubbed\"` (drop secret-like vars: `*KEY*`, `*SECRET*`,\n * `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Pass `\"all\"` to restore full inheritance\n * or `\"core\"` for a minimal safe allowlist.\n */\n env?: EnvPolicy;\n}\n\nexport class SandboxSecurityError extends Error {\n readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxSecurityError\";\n }\n}\n\nexport class SandboxNotAvailableError extends Error {\n readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxNotAvailableError\";\n }\n}\n\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n // #54 — preserve the env policy so backends can scrub secrets.\n env: config.env ?? \"inherit-scrubbed\",\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n\n/**\n * A backend OR a per-request resolver of one — mirrors `FilesystemProvider` / `InteractiveProvider`.\n * A resolver runs at tool-execution time (request scope), so a multi-tenant / multi-role agent gets a\n * distinct sandbox per request without a shared mutable one. This is how a tool takes execution as an\n * INJECTED capability: the same tool runs on a local sandbox, a container/E2B backend (cluster/web), or\n * any future backend, with no direct `child_process` import.\n *\n * @public\n */\nexport type SandboxProvider<Ctx = unknown> =\n | SandboxBackend\n | ((ctx: Ctx) => SandboxBackend | Promise<SandboxBackend>);\n\n/** Resolve a {@link SandboxProvider} to a concrete backend for `ctx`. */\nexport async function resolveSandbox<Ctx>(\n provider: SandboxProvider<Ctx>,\n ctx: Ctx,\n): Promise<SandboxBackend> {\n return provider instanceof SandboxBackend ? provider : provider(ctx);\n}\n","/**\n * LocalSandbox — subprocess-based execution. **This is NOT an isolation\n * boundary.** It runs the command via `/bin/sh -c` in the SAME OS as the host\n * with the host's filesystem and network fully reachable — it provides NO\n * process, filesystem, or network isolation. Its only safety affordances are:\n * - a wall-clock timeout (kills a runaway command),\n * - an output-size cap (bounds memory), and\n * - env scrubbing (#54): secret-like parent env vars (`*KEY*`/`*SECRET*`/\n * `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`) are dropped from the child by default\n * (`SandboxConfig.env`), so a shell tool cannot exfiltrate host secrets via\n * the environment.\n *\n * For real isolation (untrusted code), use a container/VM backend — NOT this.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { resolveChildEnv } from \"../internal/runtime/lifecycle/env-policy.js\";\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n // #54 — scrub secret-like host env vars from the child by default.\n env: resolveChildEnv({ policy: this.config.env }),\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n return {\n stdout: this.truncateOutput(stdout),\n stderr: this.truncateOutput(stderr),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n"]}
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
// src/internal/env.ts
|
|
2
|
+
var API_KEY_ENV_VAR = "THEOKIT_API_KEY";
|
|
3
|
+
function readEnv(name) {
|
|
4
|
+
return globalThis.process?.env?.[name];
|
|
5
|
+
}
|
|
6
|
+
function resolveApiKey(explicit) {
|
|
7
|
+
if (explicit !== void 0 && explicit.length > 0) {
|
|
8
|
+
return explicit;
|
|
9
|
+
}
|
|
10
|
+
const fromEnv = readEnv(API_KEY_ENV_VAR);
|
|
11
|
+
if (fromEnv !== void 0 && fromEnv.length > 0) {
|
|
12
|
+
return fromEnv;
|
|
13
|
+
}
|
|
14
|
+
return void 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
1
17
|
// src/internal/diagnostics.ts
|
|
2
18
|
var SINK_SLOT = /* @__PURE__ */ Symbol.for("theokit.sdk.diagnostics.sink.v1");
|
|
3
19
|
function currentSink() {
|
|
@@ -18,7 +34,7 @@ function diag(message) {
|
|
|
18
34
|
// src/internal/security/redact.ts
|
|
19
35
|
var REDACT_ENABLED = readEnvOnce();
|
|
20
36
|
function readEnvOnce() {
|
|
21
|
-
const raw =
|
|
37
|
+
const raw = readEnv("THEOKIT_REDACT_SECRETS");
|
|
22
38
|
if (raw === void 0) return true;
|
|
23
39
|
return ["1", "true", "yes", "on"].includes(raw.toLowerCase());
|
|
24
40
|
}
|
|
@@ -147,6 +163,6 @@ function redactSecrets(text, opts) {
|
|
|
147
163
|
return s;
|
|
148
164
|
}
|
|
149
165
|
|
|
150
|
-
export { addPattern, diag, maskToken, redactSecrets, setDiagnosticsSink };
|
|
151
|
-
//# sourceMappingURL=chunk-
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
166
|
+
export { addPattern, diag, maskToken, readEnv, redactSecrets, resolveApiKey, setDiagnosticsSink };
|
|
167
|
+
//# sourceMappingURL=chunk-5F5NWKPN.js.map
|
|
168
|
+
//# sourceMappingURL=chunk-5F5NWKPN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/env.ts","../src/internal/diagnostics.ts","../src/internal/security/redact.ts"],"names":[],"mappings":";AAKO,IAAM,eAAA,GAAkB,iBAAA;AAoBxB,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,OAAO,UAAA,CAAW,OAAA,EAAS,GAAA,GAAM,IAAI,CAAA;AACvC;AAYO,SAAS,cAAc,QAAA,EAAuC;AACnE,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,EAAG;AACjD,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,eAAe,CAAA;AACvC,EAAA,IAAI,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AAC/C,IAAA,OAAO,OAAA;AAAA,EACT;AACA,EAAA,OAAO,MAAA;AACT;;;ACoBA,IAAM,SAA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","sourcesContent":["/**\n * Environment variable used to provide the default API key.\n *\n * @internal\n */\nexport const API_KEY_ENV_VAR = \"THEOKIT_API_KEY\";\n\n/**\n * Read an environment variable without assuming `process` exists.\n *\n * Parts of this package legitimately reach a browser: `errors.ts` is imported by the client\n * bindings that framework consumers ship to the front end, and it in turn pulls in the redaction\n * and retry modules. `process` is a Node global — a bare `process.env` in any of them throws\n * `ReferenceError: process is not defined` while the module graph is still evaluating, before a\n * single component renders. The page goes blank with one console error that names no cause.\n *\n * `globalThis.process?.env?.[name]` degrades instead: on the server it reads the variable, and in\n * a browser it yields `undefined`, which every caller here already treats as \"not set\". Bundlers\n * that inline `process.env.X` at build time keep working, because they replace the expression\n * before it ever runs.\n *\n * This is the same pattern the sibling design system uses for `NODE_ENV`, for the same reason.\n *\n * @internal\n */\nexport function readEnv(name: string): string | undefined {\n return globalThis.process?.env?.[name];\n}\n\n/**\n * Resolve the API key with the documented precedence:\n *\n * 1. Explicit `apiKey` argument.\n * 2. The `THEOKIT_API_KEY` environment variable.\n *\n * Returns `undefined` when neither is set.\n *\n * @internal\n */\nexport function resolveApiKey(explicit?: string): string | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = readEnv(API_KEY_ENV_VAR);\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return undefined;\n}\n","/**\n * The library's single diagnostics channel — silent by default (#147).\n *\n * ## The problem\n *\n * The SDK wrote diagnostics straight to `process.stderr` from hot paths — 92 sites across 51\n * files under `internal/`. In a TUI host (Ink, alternate screen), those writes interleave with the\n * render and **corrupt the frame**. And the host had no way to intercept them: there was no\n * injectable logger. One consumer went as far as installing `proper-lockfile` just to silence ONE\n * of them.\n *\n * A library cannot assume `stdout`/`stderr` are free sinks. The application owns the terminal, not\n * the dependency.\n *\n * ## The contract\n *\n * - **`setDiagnosticsSink(fn)`** hands the messages to the application, which decides where to put\n * them (a status line, a file, a panel). It is what was missing for a TUI to coexist with the SDK.\n * - **With no sink, nothing is emitted.** A library does not own the host's terminal.\n *\n * ## Silent by default, and how 36 suites survived the flip\n *\n * The default WAS `stderr`, and 36 test files spy on `process.stderr.write` to assert a given\n * warning is emitted. That contract is real and had to survive; migrating all 36 by hand, across\n * four different spy styles, is how you weaken 36 suites in one commit.\n *\n * So the flip happened at the default, and `vitest.setup.ts` installs a sink that FORWARDS to\n * `stderr` for the duration of every test. Those assertions still test what they always tested —\n * \"this condition emits a diagnostic\" — through the channel a host would use, while production\n * emits nothing unless asked.\n *\n * The cost is stated rather than hidden: no test observes the production default by accident, so\n * `tests/diagnostics-public-entry.test.ts` pins it explicitly by clearing the sink first.\n *\n * ## Coverage is the whole guarantee\n *\n * The first sweep migrated the 92 sites under `internal/` and left `src/`'s own modules —\n * `event-bus.ts`, `batch.ts`, `compaction.ts`, `internal/workflow/step-branch.ts`. A host could\n * therefore install a sink and still have its frame corrupted by a batch run, which is the reported\n * defect with a smaller blast radius. Those are routed here too, and\n * `tests/lint/no-direct-terminal-write.test.ts` is what keeps the next hot path from\n * reintroducing one. \"Mostly interceptable\" is not interceptable.\n *\n * The remaining direct writers are allowlisted there with a reason, and every one of them is a seam\n * whose destination the CALLER already chooses (`opts.warn`, `opts.logger`, the Workflow logger).\n *\n * ## What this is NOT\n *\n * It is not a logger with levels, formatting or multiple destinations. It is the minimum that\n * resolves the reported blocker; a full logger here would be inventing a requirement nobody asked\n * for.\n */\n\n/** Receives each diagnostic message already formatted, with the trailing `\\n`. */\nexport type DiagnosticsSink = (message: string) => void;\n\n/**\n * The registry lives on `globalThis`, not in a module-level `let` (theokit#173).\n *\n * A module-level binding is a per-INSTANCE singleton, and a package manager will install two\n * physical copies of the same version whenever two dependents resolve different peer sets. Measured:\n * `@theokit/sdk@4.39.1` existed under two pnpm store hashes in the theokit workspace, so a sink\n * installed through `@theokit/agents` landed in a different registry than the emitter writes to.\n *\n * The failure mode is the quiet one — the re-export resolves, the function is callable, nothing\n * throws, and no diagnostic ever arrives. `Symbol.for` gives every copy in the process the same\n * slot; the `v1` suffix leaves room to change the shape without colliding with an older copy.\n */\nconst SINK_SLOT = Symbol.for(\"theokit.sdk.diagnostics.sink.v1\");\n\ntype SinkHolder = Record<symbol, DiagnosticsSink | undefined>;\n\nfunction currentSink(): DiagnosticsSink | undefined {\n return (globalThis as unknown as SinkHolder)[SINK_SLOT];\n}\n\n/**\n * Installs (or removes, by passing `undefined`) the diagnostics destination.\n *\n * When a sink is present it is the ONLY destination — `stderr` gets no copy. Duplicating\n * destinations would hand the problem back to the TUI that installed the sink precisely to get the\n * messages out of the terminal.\n */\nexport function setDiagnosticsSink(next: DiagnosticsSink | undefined): void {\n (globalThis as unknown as SinkHolder)[SINK_SLOT] = next;\n}\n\n/**\n * Emits a library diagnostic message.\n *\n * Replaces `process.stderr.write` on internal paths. Never throws: a faulty sink must not\n * must not take down the run it merely observes.\n */\nexport function diag(message: string): void {\n // Silent by default (#147): with no sink installed the message is dropped. A library must not\n // assume the host's stdout/stderr are free-form log sinks — in a TUI they are the render surface.\n const sink = currentSink();\n if (sink === undefined) return;\n try {\n sink(message);\n } catch {\n // Observability never breaks the run — same principle as `emitRunEvent`.\n }\n}\n\n/**\n * Emits a diagnostic that reports a USER-VISIBLE FAILURE, and is never silently dropped.\n *\n * `diag` is silent with no sink installed, and that is right for chatter: a library must not assume\n * the host's stderr is a free-form log, because in a TUI it is the render surface. A failure is a\n * different message. `theokit-sdk#189` is the record of the difference — an MCP server failed to\n * start, the only report went to `diag()`, the embedding UI never read it, and the user saw an\n * agent with missing tools and no reason given.\n *\n * The two failure modes are not symmetric, which is the whole decision: a corrupted frame is\n * visible and recoverable, while a silently dropped failure is neither. So this falls back to\n * stderr rather than to silence.\n *\n * A sink still takes precedence — the host installed it precisely to keep these off the terminal —\n * EXCEPT when the sink throws. A broken sink swallowing the one report of a failure is the same\n * defect one layer further in.\n *\n * @internal\n */\nexport function diagFailure(message: string): void {\n const sink = currentSink();\n if (sink !== undefined) {\n try {\n sink(message);\n return;\n } catch {\n // Fall through: the sink is broken, and this message is too important to drop with it.\n }\n }\n try {\n // `globalThis.process?.stderr` rather than a bare `process`: in a browser the bare form is a\n // ReferenceError that the catch below would swallow — working by accident, on an exception used\n // as ordinary control flow. Optional chaining states the intent: write to stderr where one\n // exists, stay silent where none does.\n globalThis.process?.stderr?.write(`${message}\\n`);\n } catch {\n // Nothing left to try. Observability never breaks the run.\n }\n}\n","import { diag } from \"../diagnostics.js\";\nimport { readEnv } from \"../env.js\";\n\n/**\n * Canonical secret redaction module (ADRs D68-D73).\n *\n * Single source of truth for credential pattern masking across the SDK.\n * Wired at output boundaries: `ErrorMetadata.raw` (mappers/shared.ts),\n * telemetry span attributes (telemetry/tracer.ts), transcript JSONL\n * appends (agent-session-store.ts), migration logger output\n * (memory/migrate-sqlite-to-lance.ts).\n *\n * - D68: central module, single source of truth (replaces 2 duplicates)\n * - D69: env snapshot at module init (prompt-injection defense)\n * - D70: ON by default, warn on opt-out\n * - D71: two-bucket masking — short fully masked, long preserves prefix+suffix\n * - D72: `codeFile` opt-out for legitimate prefix-shaped content\n * - D73: redact at OUTPUT boundaries, not at storage\n *\n * @internal\n */\n\n// D69: env snapshot captured at module load. Subsequent mutations of\n// process.env.THEOKIT_REDACT_SECRETS are ignored — defends against\n// prompt injection that tries to disable redaction mid-run.\nlet REDACT_ENABLED: boolean = readEnvOnce();\n\nfunction readEnvOnce(): boolean {\n // `readEnv` rather than `process.env`: this module reaches the browser through `errors.ts`, and\n // a bare `process` there is a ReferenceError at module scope — a blank page, not a warning.\n const raw = readEnv(\"THEOKIT_REDACT_SECRETS\");\n if (raw === undefined) return true; // D70: default ON\n return [\"1\", \"true\", \"yes\", \"on\"].includes(raw.toLowerCase());\n}\n\n// D70: warn once on opt-out so the user knows they're vulnerable.\nlet warnedOptOut = false;\nif (!REDACT_ENABLED && !warnedOptOut) {\n diag(\n \"[theokit-sdk] Secret redaction is DISABLED via THEOKIT_REDACT_SECRETS. \" +\n \"Credentials may leak into errors, telemetry, logs, transcripts.\\n\",\n );\n warnedOptOut = true;\n}\n\n/**\n * Built-in credential patterns. Order matters — more specific prefixes\n * must come before generic ones (e.g., `sk-ant-` before `sk-`). Quantifiers\n * are all bounded `{n,m}` or applied to char classes — linear time, no ReDoS.\n *\n * @internal\n */\nconst BUILTIN_PATTERNS: readonly RegExp[] = [\n // T5.4: 30+ vendor prefixes (was 12 pre-T5.4). Order matters — more\n // specific prefixes precede generic ones (e.g., sk-ant-admin01 before\n // sk-ant-, sk-proj- before sk-). PEM block deliberately first so its\n // multi-line span runs before any per-line patterns can fire.\n /-----BEGIN[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----[\\s\\S]+?-----END[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----/g,\n // JWT — exact 3-segment base64url. Dotted; the body floor of 4 chars per\n // segment matches the minimum legal payload while skipping `a.b.c` noise.\n /eyJ[A-Za-z0-9_-]{4,}\\.eyJ[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]{4,}/g,\n // Azure Storage SAS — match the sig= component (URL-encoded base64).\n /(?<=[?&]sig=)[A-Za-z0-9%+/]{20,}/g,\n // Anthropic\n /sk-ant-admin01-[A-Za-z0-9_-]{10,}/g, // Anthropic admin keys (must precede sk-ant-)\n /sk-ant-[A-Za-z0-9_-]{10,}/g, // Anthropic regular\n // OpenAI family + clones (sk- generic must come AFTER all sk-foo- variants)\n /sk-proj-[A-Za-z0-9_-]{10,}/g, // OpenAI project key (must precede sk- generic)\n /sk-[A-Za-z0-9_-]{10,}/g, // OpenAI / OpenRouter / DeepInfra / Together / DeepSeek\n // Provider prefixes (alphabetized for maintainability)\n /AIza[A-Za-z0-9_-]{35}/g, // Google API key\n /AKIA[A-Z0-9]{16}/g, // AWS access key\n /fw_[A-Za-z0-9]{20,}/g, // Fireworks\n /glpat-[A-Za-z0-9_-]{20}/g, // GitLab PAT\n /ghp_[A-Za-z0-9]{36}/g, // GitHub PAT classic\n /github_pat_[A-Za-z0-9_]{82}/g, // GitHub PAT fine-grained\n /gsk_[A-Za-z0-9]{20,}/g, // Groq\n /hf_[A-Za-z0-9]{20,}/g, // HuggingFace\n /\\bpa-[A-Za-z0-9_-]{20,}/g, // Voyage AI (word-boundary to skip CSS / kebab IDs)\n /pcsk_[A-Za-z0-9_-]{20,}/g, // Pinecone\n /pplx-[A-Za-z0-9_-]{20,}/g, // Perplexity\n /r8_[A-Za-z0-9_-]{20,}/g, // Replicate\n /rk_live_[A-Za-z0-9]{20,}/g, // Stripe restricted\n /sk_live_[A-Za-z0-9]{20,}/g, // Stripe secret\n /sntrys_[A-Za-z0-9]{40,}/g, // Sentry user auth\n /xai-[A-Za-z0-9_-]{20,}/g, // xAI (Grok)\n /xox[bpasr]-[A-Za-z0-9-]{10,}/g, //Slack tokens\n // Additional unique-prefix tokens with low false-positive risk\n /npm_[A-Za-z0-9]{36}/g, // npm access token\n /SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}/g, // SendGrid\n /\\bSK[A-Za-z0-9]{32}\\b/g, // Twilio API SID (word-boundary to skip CSS class noise)\n /\\bkey-[a-f0-9]{32}\\b/g, // Mailgun (hex-only narrows false positives)\n /MT[A-Za-z0-9_-]{23}\\.[A-Za-z0-9_-]{6}\\.[A-Za-z0-9_-]{27}/g, // Discord bot\n /\\b(?:sdk|mob)-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\b/g, // LaunchDarkly\n];\n\n// `Bearer <token>` matched as its own first-class pattern so PARAM_PATTERN\n// doesn't have to handle the unusual `Authorization: Bearer xxx` shape\n// (no `:` or `=` between \"Bearer\" and the value — bare whitespace).\nconst BEARER_PATTERN = /\\b(Bearer\\s+)([A-Za-z0-9_\\-.+/=]{8,})/g;\n\n// Parametric: matches `key=value` and `key: value` (with optional quote\n// between the key and the separator, to handle JSON: `\"api_key\": \"...\"`)\n// in URLs, query strings, JSON-like bodies, HTTP headers. Captures the\n// prefix so we keep it visible while masking the value.\n//\n// `authorization` deliberately excluded — BEARER_PATTERN handles the\n// common `Authorization: Bearer xxx` shape. Including it here causes\n// double-masking (\"Authorization: *** ***\") after Bearer fires.\n// T5.4: keyword set expanded from 6 → 16 to cover the OAuth / JWT / generic\n// credential vocabulary surfaced by DR6 finding #4. `authorization`,\n// `auth`, `bearer` stay excluded — BEARER_PATTERN handles the\n// `Authorization: Bearer xxx` shape and including these here would\n// re-catch the post-BUILTIN-masked form (D71 prefix-preservation\n// contract) and double-mask to `***`.\n//\n// Value class includes `.` so JWT / `.env` / dotted base64url values\n// match; the callback skips already-masked values (containing the\n// `...` D71 separator) to preserve the BUILTIN prefix-mask result.\nconst PARAM_PATTERN =\n /(\\b(?:access_token|api_key|api-key|client_secret|credential|credentials|id_token|jwt|password|private_key|refresh_token|secret|service_account|session_token|token|x-api-key)\\b[\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_\\-.+/]+)/gi;\n\nconst _extraPatterns: RegExp[] = [];\n\n/**\n * Add a user-defined redaction pattern. Additive — never removes builtins.\n * Throws if the regex lacks the `/g` flag (without `/g`, `.replace` only\n * substitutes the first match and the rest leaks).\n *\n * @internal — exposed publicly via `Security.addPattern` in `src/security.ts`.\n */\nexport function addPattern(re: RegExp): void {\n if (!re.global) {\n throw new Error(\"Security.addPattern: regex must have /g flag for replace-all semantics\");\n }\n _extraPatterns.push(re);\n}\n\n/**\n * Two-bucket masking (D71):\n * - tokens shorter than 18 chars → fully masked as `***`\n * - tokens >= 18 chars → keep first 6 + `...` + last 4\n *\n * Rationale: long tokens are unique per-account; prefix+suffix preserves\n * debuggability without revealing the secret middle.\n *\n * @internal\n */\nexport function maskToken(token: string): string {\n if (token.length < 18) return \"***\";\n return `${token.slice(0, 6)}...${token.slice(-4)}`;\n}\n\n// issue #117 — the EXACT shape of a `maskToken` output (`slice(0,6)+\"...\"+slice(-4)`\n// = 6 chars, literal `...`, 4 chars). Used to detect a value PARAM_PATTERN would\n// otherwise re-mask, WITHOUT skipping a raw secret that merely contains `...`.\nconst MASK_SHAPE = /^.{6}\\.\\.\\..{4}$/s;\n\n/**\n * Redact known credential patterns from `text`. Default behavior masks\n * builtins + extras + parametric `key=value` sinks.\n *\n * With `{ codeFile: true }` (D72), skips PARAM_PATTERN to avoid mangling\n * `.env.example`, schema JSON, or test fixtures that legitimately contain\n * prefix-like strings.\n *\n * Returns the redacted string. Coerces non-strings via JSON.stringify;\n * EC-7 fix (edge-case review): wraps in try/catch so circular references\n * never propagate — returns sentinel `\"[unredactable: circular]\"`.\n *\n * @internal\n */\n// Coerce arbitrary input to a string for redaction. Returns `null`\n// sentinel when the value is null/undefined/non-stringifiable, so the\n// caller can short-circuit with `\"\"`. EC-7 fix: circular refs go through\n// the try/catch and produce the sentinel marker, never throwing.\nfunction coerceToString(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n if (typeof value === \"object\") {\n try {\n const s = JSON.stringify(value);\n return s === undefined ? null : s;\n } catch {\n return \"[unredactable: circular]\";\n }\n }\n return String(value);\n}\n\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n const coerced = coerceToString(text);\n if (coerced === null) return \"\";\n if (!REDACT_ENABLED) return coerced;\n\n let s = coerced;\n for (const re of BUILTIN_PATTERNS) {\n s = s.replace(re, (m) => maskToken(m));\n }\n for (const re of _extraPatterns) {\n s = s.replace(re, (m) => maskToken(m));\n }\n if (!opts?.codeFile) {\n // Bearer first (preserves \"Bearer \" prefix, masks the token after).\n // Must run before PARAM_PATTERN so the bare-whitespace shape doesn't\n // get mis-handled as a value.\n s = s.replace(BEARER_PATTERN, (_, prefix: string) => `${prefix}***`);\n // T5.4: skip if value already contains the D71 bucket-mask separator\n // (`...`) — BUILTIN ran first and produced a prefix-preserved mask;\n // re-masking would lose the prefix and degrade debuggability.\n s = s.replace(PARAM_PATTERN, (whole, prefix: string, value: string) => {\n // issue #117 — skip ONLY when the value is already a mask that a BUILTIN\n // pattern produced (maskToken's exact `6chars...4chars` shape), so we don't\n // re-mask and lose the prefix. The old `value.includes(\"...\")` was too broad:\n // a REAL secret that happens to contain `...` (e.g. `L_-cxw-.2UI_..._`) was\n // skipped and LEAKED. The mask shape is exact (maskToken: slice(0,6)+\"...\"+\n // slice(-4)), so a raw secret with `...` elsewhere is now masked.\n if (MASK_SHAPE.test(value)) return whole;\n return `${prefix}***`;\n });\n }\n return s;\n}\n\n/**\n * Test-only helper exported for `_test-reset.ts`. NOT included in the\n * `index.ts` barrel — vitest setup imports the dedicated module via\n * explicit path to discourage production callers.\n *\n * @internal\n */\nexport function _resetForTests(opts: { enabled?: boolean; clearExtras?: boolean }): void {\n if (opts.enabled !== undefined) REDACT_ENABLED = opts.enabled;\n if (opts.clearExtras === true) _extraPatterns.length = 0;\n}\n\n/**\n * T5.4 — Test-only count of BUILTIN_PATTERNS. Exposed so the count-floor\n * assertion can run without re-deriving the array shape in test land.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__BUILTIN_PATTERN_COUNT(): number {\n return BUILTIN_PATTERNS.length;\n}\n"]}
|