@theokit/sdk 4.40.0 → 4.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/README.md +2 -2
- package/dist/agent-35MGOZVH.js +46 -0
- package/dist/{agent-MSR3DHO4.js.map → agent-35MGOZVH.js.map} +1 -1
- package/dist/agent-6C2ODKFU.cjs +55 -0
- package/dist/{agent-OOXJJD6A.cjs.map → agent-6C2ODKFU.cjs.map} +1 -1
- package/dist/{agent-BzZwYFiw.d.ts → agent-BiCINq25.d.ts} +2 -2
- package/dist/{agent-DxEL4fHh.d.cts → agent-Zta1kvGH.d.cts} +2 -2
- package/dist/agent-session-store-EPUERCUU.cjs +23 -0
- package/dist/{agent-session-store-RHTLZ5OX.cjs.map → agent-session-store-EPUERCUU.cjs.map} +1 -1
- package/dist/agent-session-store-TXP5ZVOD.js +6 -0
- package/dist/{agent-session-store-EGTTYSKS.js.map → agent-session-store-TXP5ZVOD.js.map} +1 -1
- package/dist/auth/index.cjs +19 -15
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +4 -4
- package/dist/{batch-WX2HLXX2.js → batch-OUF4N2TM.js} +9 -9
- package/dist/{batch-WX2HLXX2.js.map → batch-OUF4N2TM.js.map} +1 -1
- package/dist/{batch-FO2KZN7W.cjs → batch-URTEXK77.cjs} +26 -26
- package/dist/{batch-FO2KZN7W.cjs.map → batch-URTEXK77.cjs.map} +1 -1
- package/dist/{chunk-PDOLUFGY.cjs → chunk-27DYRARU.cjs} +4 -4
- package/dist/{chunk-PDOLUFGY.cjs.map → chunk-27DYRARU.cjs.map} +1 -1
- package/dist/{chunk-LYD3ALDT.js → chunk-2S6B5B2A.js} +5 -5
- package/dist/{chunk-LYD3ALDT.js.map → chunk-2S6B5B2A.js.map} +1 -1
- package/dist/{chunk-VTDQRUAJ.js → chunk-2WB6EIYW.js} +4 -4
- package/dist/{chunk-VTDQRUAJ.js.map → chunk-2WB6EIYW.js.map} +1 -1
- package/dist/{chunk-3CAQCFVZ.js → chunk-35NFZ7QB.js} +3 -3
- package/dist/{chunk-3CAQCFVZ.js.map → chunk-35NFZ7QB.js.map} +1 -1
- package/dist/{chunk-HCRCNI7A.js → chunk-3KY7MHR4.js} +3 -3
- package/dist/{chunk-HCRCNI7A.js.map → chunk-3KY7MHR4.js.map} +1 -1
- package/dist/{chunk-BURYFNOM.cjs → chunk-4JBHSLQO.cjs} +2 -2
- package/dist/chunk-4JBHSLQO.cjs.map +1 -0
- package/dist/{chunk-V7CA3CX5.cjs → chunk-4JRRFRV4.cjs} +5 -4
- package/dist/chunk-4JRRFRV4.cjs.map +1 -0
- package/dist/{chunk-5KOW3GLE.js → chunk-4QEC4CCS.js} +2 -2
- package/dist/chunk-4QEC4CCS.js.map +1 -0
- package/dist/{chunk-ALDFVGQQ.cjs → chunk-57KX5WTP.cjs} +9 -9
- package/dist/{chunk-ALDFVGQQ.cjs.map → chunk-57KX5WTP.cjs.map} +1 -1
- package/dist/{chunk-CJHBSSAF.cjs → chunk-64TJCXY5.cjs} +15 -15
- package/dist/{chunk-CJHBSSAF.cjs.map → chunk-64TJCXY5.cjs.map} +1 -1
- package/dist/{chunk-IEKSEAIV.js → chunk-6FSQ3CHQ.js} +3 -3
- package/dist/{chunk-IEKSEAIV.js.map → chunk-6FSQ3CHQ.js.map} +1 -1
- package/dist/{chunk-ZVQJHY4Y.cjs → chunk-6W4U2G3J.cjs} +5 -5
- package/dist/{chunk-ZVQJHY4Y.cjs.map → chunk-6W4U2G3J.cjs.map} +1 -1
- package/dist/{chunk-FMDZZRYE.cjs → chunk-6X2HUT4A.cjs} +8 -8
- package/dist/{chunk-FMDZZRYE.cjs.map → chunk-6X2HUT4A.cjs.map} +1 -1
- package/dist/{chunk-X2LDDKFM.cjs → chunk-7PESI6YD.cjs} +10 -10
- package/dist/{chunk-X2LDDKFM.cjs.map → chunk-7PESI6YD.cjs.map} +1 -1
- package/dist/{chunk-EYUZZXHZ.js → chunk-AF4BBKIF.js} +4 -4
- package/dist/chunk-AF4BBKIF.js.map +1 -0
- package/dist/{chunk-7GFX45DD.js → chunk-AM2CNBKE.js} +2 -2
- package/dist/chunk-AM2CNBKE.js.map +1 -0
- package/dist/{chunk-XKGOIGTJ.js → chunk-AZ6FKDQR.js} +3 -3
- package/dist/{chunk-XKGOIGTJ.js.map → chunk-AZ6FKDQR.js.map} +1 -1
- package/dist/{chunk-WPZTYOUX.cjs → chunk-BBZYXVLZ.cjs} +2 -2
- package/dist/chunk-BBZYXVLZ.cjs.map +1 -0
- package/dist/{chunk-2UBBO2MD.js → chunk-BHWHE453.js} +5 -5
- package/dist/{chunk-2UBBO2MD.js.map → chunk-BHWHE453.js.map} +1 -1
- package/dist/{chunk-LY4KEOOY.cjs → chunk-BRHRQOJA.cjs} +4 -4
- package/dist/{chunk-LY4KEOOY.cjs.map → chunk-BRHRQOJA.cjs.map} +1 -1
- package/dist/{chunk-4H2QARXM.cjs → chunk-BV42CCRP.cjs} +7 -7
- package/dist/{chunk-4H2QARXM.cjs.map → chunk-BV42CCRP.cjs.map} +1 -1
- package/dist/{chunk-ZRQZOJ3N.js → chunk-DCKIS53K.js} +52 -51
- package/dist/chunk-DCKIS53K.js.map +1 -0
- package/dist/{chunk-SKWVAQAY.js → chunk-DEZ75ET5.js} +3 -3
- package/dist/{chunk-SKWVAQAY.js.map → chunk-DEZ75ET5.js.map} +1 -1
- package/dist/{chunk-WJOLIPEM.js → chunk-EON4YTR6.js} +8 -8
- package/dist/{chunk-WJOLIPEM.js.map → chunk-EON4YTR6.js.map} +1 -1
- package/dist/{chunk-MI3OKONE.js → chunk-F4RUADRC.js} +3 -3
- package/dist/{chunk-MI3OKONE.js.map → chunk-F4RUADRC.js.map} +1 -1
- package/dist/{chunk-BVGJXMSB.cjs → chunk-F5DSDDBY.cjs} +312 -311
- package/dist/chunk-F5DSDDBY.cjs.map +1 -0
- package/dist/{chunk-SEWAPWAF.cjs → chunk-FMIKUGF2.cjs} +124 -124
- package/dist/chunk-FMIKUGF2.cjs.map +1 -0
- package/dist/{chunk-XZ7PO2FM.js → chunk-FRQ6F44U.js} +4 -4
- package/dist/{chunk-XZ7PO2FM.js.map → chunk-FRQ6F44U.js.map} +1 -1
- package/dist/{chunk-3LK3ZDL5.cjs → chunk-FZ4YMZA3.cjs} +5 -5
- package/dist/{chunk-3LK3ZDL5.cjs.map → chunk-FZ4YMZA3.cjs.map} +1 -1
- package/dist/{chunk-MM2JKFQV.cjs → chunk-GC44RATP.cjs} +10 -10
- package/dist/{chunk-MM2JKFQV.cjs.map → chunk-GC44RATP.cjs.map} +1 -1
- package/dist/{chunk-LNTQRD23.cjs → chunk-GH52NOCL.cjs} +26 -26
- package/dist/chunk-GH52NOCL.cjs.map +1 -0
- package/dist/{chunk-T6KFGMNY.cjs → chunk-GLEKLAUW.cjs} +12 -12
- package/dist/chunk-GLEKLAUW.cjs.map +1 -0
- package/dist/{chunk-UIPTINIF.js → chunk-GNMPCZNN.js} +6 -6
- package/dist/chunk-GNMPCZNN.js.map +1 -0
- package/dist/{chunk-K6TWHNT4.cjs → chunk-HECR7KF5.cjs} +11 -11
- package/dist/{chunk-K6TWHNT4.cjs.map → chunk-HECR7KF5.cjs.map} +1 -1
- package/dist/{chunk-NHXPQN44.js → chunk-HK4HRLWE.js} +3 -3
- package/dist/{chunk-NHXPQN44.js.map → chunk-HK4HRLWE.js.map} +1 -1
- package/dist/{chunk-LWVKI75U.js → chunk-HKSSM5RK.js} +3 -3
- package/dist/{chunk-LWVKI75U.js.map → chunk-HKSSM5RK.js.map} +1 -1
- package/dist/{chunk-ELYGL52R.cjs → chunk-HLNLYLNN.cjs} +4 -4
- package/dist/{chunk-ELYGL52R.cjs.map → chunk-HLNLYLNN.cjs.map} +1 -1
- package/dist/{chunk-ONVIALVV.js → chunk-IMX5YODO.js} +15 -15
- package/dist/chunk-IMX5YODO.js.map +1 -0
- package/dist/{chunk-C64E2EJS.js → chunk-J5RW43IR.js} +4 -4
- package/dist/{chunk-C64E2EJS.js.map → chunk-J5RW43IR.js.map} +1 -1
- package/dist/{chunk-4E3HLSYE.cjs → chunk-JA4FEA5Z.cjs} +4 -4
- package/dist/{chunk-4E3HLSYE.cjs.map → chunk-JA4FEA5Z.cjs.map} +1 -1
- package/dist/{chunk-EJNFZET4.cjs → chunk-JO76RWCA.cjs} +11 -11
- package/dist/{chunk-EJNFZET4.cjs.map → chunk-JO76RWCA.cjs.map} +1 -1
- package/dist/{chunk-QMIG7TKG.cjs → chunk-KCQUYQ3V.cjs} +17 -17
- package/dist/chunk-KCQUYQ3V.cjs.map +1 -0
- package/dist/{chunk-AKMPQJPX.js → chunk-L4JFQCG4.js} +5 -5
- package/dist/chunk-L4JFQCG4.js.map +1 -0
- package/dist/{chunk-HJMFPIRM.js → chunk-LLE7HPRI.js} +5 -5
- package/dist/{chunk-HJMFPIRM.js.map → chunk-LLE7HPRI.js.map} +1 -1
- package/dist/{chunk-4H2DCO6P.js → chunk-LXKNENHK.js} +3 -3
- package/dist/{chunk-4H2DCO6P.js.map → chunk-LXKNENHK.js.map} +1 -1
- package/dist/{chunk-PY7G7YWK.cjs → chunk-MMZX557L.cjs} +5 -5
- package/dist/{chunk-PY7G7YWK.cjs.map → chunk-MMZX557L.cjs.map} +1 -1
- package/dist/{chunk-VQ33XLC6.js → chunk-MRKSSN36.js} +3 -3
- package/dist/{chunk-VQ33XLC6.js.map → chunk-MRKSSN36.js.map} +1 -1
- package/dist/{chunk-33B2BSME.cjs → chunk-NETYW4V3.cjs} +13 -5
- package/dist/chunk-NETYW4V3.cjs.map +1 -0
- package/dist/{chunk-OVGNXGCK.cjs → chunk-NNNUQELM.cjs} +9 -9
- package/dist/{chunk-OVGNXGCK.cjs.map → chunk-NNNUQELM.cjs.map} +1 -1
- package/dist/{chunk-BM7VYZED.js → chunk-NOM2YWFP.js} +5 -5
- package/dist/{chunk-BM7VYZED.js.map → chunk-NOM2YWFP.js.map} +1 -1
- package/dist/{chunk-WMWZAJMJ.cjs → chunk-NRA36JKG.cjs} +11 -11
- package/dist/{chunk-WMWZAJMJ.cjs.map → chunk-NRA36JKG.cjs.map} +1 -1
- package/dist/{chunk-4HKAZRTC.js → chunk-O3IZ7JEL.js} +3 -3
- package/dist/{chunk-4HKAZRTC.js.map → chunk-O3IZ7JEL.js.map} +1 -1
- package/dist/{chunk-RHQJX3EI.cjs → chunk-OEFFPR2S.cjs} +4 -4
- package/dist/{chunk-RHQJX3EI.cjs.map → chunk-OEFFPR2S.cjs.map} +1 -1
- package/dist/{chunk-4GGXF7YM.js → chunk-OLLOUAUJ.js} +3 -3
- package/dist/{chunk-4GGXF7YM.js.map → chunk-OLLOUAUJ.js.map} +1 -1
- package/dist/{chunk-RA2UZBYP.js → chunk-PAV4ZPSW.js} +3 -3
- package/dist/{chunk-RA2UZBYP.js.map → chunk-PAV4ZPSW.js.map} +1 -1
- package/dist/{chunk-RNCN2TTP.js → chunk-PBML2FHN.js} +2 -2
- package/dist/{chunk-A76OFN2B.cjs.map → chunk-PBML2FHN.js.map} +1 -1
- package/dist/{chunk-XRKFWV7K.js → chunk-PYM5OUL4.js} +5 -5
- package/dist/{chunk-XRKFWV7K.js.map → chunk-PYM5OUL4.js.map} +1 -1
- package/dist/{chunk-F4SQTWVR.js → chunk-Q4DTGCSD.js} +3 -3
- package/dist/{chunk-F4SQTWVR.js.map → chunk-Q4DTGCSD.js.map} +1 -1
- package/dist/{chunk-S7OEXQMI.cjs → chunk-R3CKCRK3.cjs} +4 -4
- package/dist/{chunk-S7OEXQMI.cjs.map → chunk-R3CKCRK3.cjs.map} +1 -1
- package/dist/{chunk-5COPO3H4.cjs → chunk-RBQYHEZD.cjs} +4 -4
- package/dist/{chunk-5COPO3H4.cjs.map → chunk-RBQYHEZD.cjs.map} +1 -1
- package/dist/{chunk-KRPEPZQY.js → chunk-RJBHWM6D.js} +7 -7
- package/dist/chunk-RJBHWM6D.js.map +1 -0
- package/dist/{chunk-U53AYSHS.cjs → chunk-S4Q5OMIK.cjs} +11 -11
- package/dist/{chunk-U53AYSHS.cjs.map → chunk-S4Q5OMIK.cjs.map} +1 -1
- package/dist/{chunk-FUP3ZA5T.js → chunk-SNKY3C2L.js} +4 -4
- package/dist/{chunk-FUP3ZA5T.js.map → chunk-SNKY3C2L.js.map} +1 -1
- package/dist/{chunk-BBMN4O6E.js → chunk-TJRPNBY5.js} +4 -4
- package/dist/{chunk-BBMN4O6E.js.map → chunk-TJRPNBY5.js.map} +1 -1
- package/dist/{chunk-27E4EMR6.cjs → chunk-UJMEWGO6.cjs} +4 -4
- package/dist/{chunk-27E4EMR6.cjs.map → chunk-UJMEWGO6.cjs.map} +1 -1
- package/dist/{chunk-X627TO3A.js → chunk-UTYCG4RB.js} +12 -12
- package/dist/chunk-UTYCG4RB.js.map +1 -0
- package/dist/{chunk-5XPKYDK7.js → chunk-VQFSEKU5.js} +12 -5
- package/dist/chunk-VQFSEKU5.js.map +1 -0
- package/dist/{chunk-NJVV5OAV.cjs → chunk-WCXOKGOQ.cjs} +8 -8
- package/dist/chunk-WCXOKGOQ.cjs.map +1 -0
- package/dist/{chunk-PIBXDEZM.cjs → chunk-WIGJGFH4.cjs} +5 -5
- package/dist/{chunk-PIBXDEZM.cjs.map → chunk-WIGJGFH4.cjs.map} +1 -1
- package/dist/{chunk-LOTWA65Z.cjs → chunk-X2YQP452.cjs} +11 -11
- package/dist/{chunk-LOTWA65Z.cjs.map → chunk-X2YQP452.cjs.map} +1 -1
- package/dist/{chunk-ZAKTZ5B4.cjs → chunk-XA3TSBAH.cjs} +8 -8
- package/dist/{chunk-ZAKTZ5B4.cjs.map → chunk-XA3TSBAH.cjs.map} +1 -1
- package/dist/{chunk-H2V6CXM7.cjs → chunk-XR4LPBXH.cjs} +9 -9
- package/dist/{chunk-H2V6CXM7.cjs.map → chunk-XR4LPBXH.cjs.map} +1 -1
- package/dist/{chunk-6AE4QTSF.cjs → chunk-Y33IGXCJ.cjs} +24 -24
- package/dist/{chunk-6AE4QTSF.cjs.map → chunk-Y33IGXCJ.cjs.map} +1 -1
- package/dist/{chunk-E7WWIX34.cjs → chunk-YULF6FPB.cjs} +8 -8
- package/dist/{chunk-E7WWIX34.cjs.map → chunk-YULF6FPB.cjs.map} +1 -1
- package/dist/{chunk-23HI77BZ.js → chunk-Z6N6SDNR.js} +4 -4
- package/dist/chunk-Z6N6SDNR.js.map +1 -0
- package/dist/{chunk-A76OFN2B.cjs → chunk-ZHPET3LZ.cjs} +2 -2
- package/dist/chunk-ZHPET3LZ.cjs.map +1 -0
- package/dist/{chunk-5VKUZ26Q.js → chunk-ZNW2TXLO.js} +3 -3
- package/dist/{chunk-5VKUZ26Q.js.map → chunk-ZNW2TXLO.js.map} +1 -1
- package/dist/{chunk-N4JNY5DT.cjs → chunk-ZO2L5U6F.cjs} +32 -32
- package/dist/chunk-ZO2L5U6F.cjs.map +1 -0
- package/dist/{chunk-RMCHJZNZ.js → chunk-ZS6SLELQ.js} +4 -4
- package/dist/{chunk-RMCHJZNZ.js.map → chunk-ZS6SLELQ.js.map} +1 -1
- package/dist/{chunk-7PBAJ2WA.js → chunk-ZTEAJAE6.js} +3 -3
- package/dist/{chunk-7PBAJ2WA.js.map → chunk-ZTEAJAE6.js.map} +1 -1
- package/dist/compact-session-65XCKO6H.js +18 -0
- package/dist/{compact-session-AZU2LEAE.js.map → compact-session-65XCKO6H.js.map} +1 -1
- package/dist/compact-session-OU6SRPVJ.cjs +55 -0
- package/dist/{compact-session-TRCEYCPG.cjs.map → compact-session-OU6SRPVJ.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-2G4375BZ.cjs +22 -0
- package/dist/{context-DNFT4B5D.cjs.map → context-2G4375BZ.cjs.map} +1 -1
- package/dist/context-GSQYVVMJ.js +5 -0
- package/dist/{context-LYE6TJL5.js.map → context-GSQYVVMJ.js.map} +1 -1
- package/dist/{cron-BGR0HOz9.d.cts → cron-DgHJnMAK.d.cts} +2 -2
- package/dist/{cron-CDAIWCrL.d.ts → cron-DyWQsEG6.d.ts} +2 -2
- package/dist/cron.cjs +33 -33
- package/dist/cron.d.cts +3 -3
- package/dist/cron.d.ts +3 -3
- package/dist/cron.js +32 -32
- package/dist/{errors-DxQe4_Qy.d.ts → errors-BSoXcl3F.d.cts} +3 -3
- package/dist/{errors-L1bxHHO0.d.cts → errors-CHllybaU.d.ts} +3 -3
- package/dist/errors.cjs +21 -21
- package/dist/errors.d.cts +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/eval.cjs +43 -43
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +33 -33
- package/dist/eval.js.map +1 -1
- package/dist/{executor-TQ3FSZ7F.cjs → executor-CB75B5BH.cjs} +24 -24
- package/dist/{executor-TQ3FSZ7F.cjs.map → executor-CB75B5BH.cjs.map} +1 -1
- package/dist/{executor-PCRX3533.js → executor-VQLTQY53.js} +7 -7
- package/dist/{executor-PCRX3533.js.map → executor-VQLTQY53.js.map} +1 -1
- package/dist/filesystem/index.cjs +7 -7
- package/dist/filesystem/index.js +3 -3
- package/dist/fs-session-store-MAZV5FXJ.cjs +19 -0
- package/dist/{fs-session-store-KRZZIG3O.cjs.map → fs-session-store-MAZV5FXJ.cjs.map} +1 -1
- package/dist/fs-session-store-ZNUYZHYI.js +10 -0
- package/dist/{fs-session-store-I6GUIFRO.js.map → fs-session-store-ZNUYZHYI.js.map} +1 -1
- package/dist/generate-object-6PWGH5DZ.cjs +20 -0
- package/dist/{generate-object-QILSGTEJ.cjs.map → generate-object-6PWGH5DZ.cjs.map} +1 -1
- package/dist/generate-object-IXMJ7FUX.js +7 -0
- package/dist/{generate-object-DLHT5RXH.js.map → generate-object-IXMJ7FUX.js.map} +1 -1
- package/dist/index-manager-X5IPG2JL.js +11 -0
- package/dist/{index-manager-SXF3FAQV.js.map → index-manager-X5IPG2JL.js.map} +1 -1
- package/dist/index-manager-YFFEPISE.cjs +20 -0
- package/dist/{index-manager-LEMQ73A7.cjs.map → index-manager-YFFEPISE.cjs.map} +1 -1
- package/dist/index.cjs +139 -139
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +53 -53
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-BVSERZCI.cjs → inject-session-DDC36KKP.cjs} +11 -11
- package/dist/{inject-session-BVSERZCI.cjs.map → inject-session-DDC36KKP.cjs.map} +1 -1
- package/dist/{inject-session-E75EP3LL.js → inject-session-UBM4KVSV.js} +8 -8
- package/dist/{inject-session-E75EP3LL.js.map → inject-session-UBM4KVSV.js.map} +1 -1
- package/dist/internal/auth/credential-store.d.ts +13 -0
- package/dist/internal/diagnostics.d.ts +2 -2
- package/dist/internal/error-mappers/anthropic.d.ts +1 -1
- package/dist/internal/eval/code-runner.d.ts +1 -1
- package/dist/internal/global-singleton.d.ts +1 -1
- package/dist/internal/judge/judge-call.d.ts +1 -1
- package/dist/internal/memory/adapters/index.cjs +8 -8
- package/dist/internal/memory/adapters/index.js +7 -7
- package/dist/internal/memory/embedding-adapter.d.ts +1 -1
- package/dist/internal/memory/memory-index.d.ts +1 -1
- package/dist/internal/persistence/atomic-write.d.cts +14 -1
- package/dist/internal/persistence/atomic-write.d.ts +14 -1
- package/dist/internal/persistence/index.cjs +25 -25
- package/dist/internal/persistence/index.js +6 -6
- package/dist/internal/persistence/jsonl.d.cts +2 -2
- package/dist/internal/persistence/jsonl.d.ts +2 -2
- package/dist/internal/persistence/session-artifacts.d.cts +27 -0
- package/dist/internal/persistence/session-artifacts.d.ts +27 -0
- package/dist/internal/persistence/session-transcript.d.cts +1 -1
- package/dist/internal/persistence/session-transcript.d.ts +1 -1
- package/dist/internal/runtime/lifecycle/env-policy.d.ts +1 -1
- package/dist/internal/security/index.cjs +13 -13
- package/dist/internal/security/index.js +3 -3
- package/dist/internal/session/agent-session.d.ts +1 -1
- package/dist/internal/session/compact-session.d.ts +1 -1
- package/dist/internal/session/session-cache.d.ts +1 -1
- package/dist/judge-call-3QZO5H5N.js +5 -0
- package/dist/{judge-call-NPRU7JIQ.js.map → judge-call-3QZO5H5N.js.map} +1 -1
- package/dist/judge-call-J5EETJL3.cjs +22 -0
- package/dist/{judge-call-AIT3EULV.cjs.map → judge-call-J5EETJL3.cjs.map} +1 -1
- package/dist/models.cjs +20 -20
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +5 -5
- 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 +44 -30
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.d.cts +4 -3
- package/dist/persistence.d.ts +4 -3
- package/dist/persistence.js +22 -12
- package/dist/persistence.js.map +1 -1
- package/dist/project.cjs +5 -5
- package/dist/project.js +3 -3
- package/dist/registry-KB3TS6BM.cjs +46 -0
- package/dist/{registry-VKDFTK6L.cjs.map → registry-KB3TS6BM.cjs.map} +1 -1
- package/dist/registry-PPFMCM4A.js +9 -0
- package/dist/{registry-AXQXPLFH.js.map → registry-PPFMCM4A.js.map} +1 -1
- package/dist/retry.cjs +4 -4
- package/dist/retry.js +3 -3
- package/dist/{run-XXnwwGOT.d.ts → run-C8FBAC8o.d.cts} +21 -2
- package/dist/{run-XXnwwGOT.d.cts → run-C8FBAC8o.d.ts} +21 -2
- package/dist/{run-until-BK56WG4P.js → run-until-HEQOUVU6.js} +2 -2
- package/dist/run-until-HEQOUVU6.js.map +1 -0
- package/dist/{run-until-L5KQD3PV.cjs → run-until-U2B5FJJI.cjs} +2 -2
- package/dist/run-until-U2B5FJJI.cjs.map +1 -0
- package/dist/sandbox/bwrap.d.cts +15 -1
- package/dist/sandbox/bwrap.d.ts +15 -1
- package/dist/sandbox/index.cjs +39 -24
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.d.cts +1 -1
- package/dist/sandbox/index.d.ts +1 -1
- package/dist/sandbox/index.js +24 -10
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/provision.d.cts +1 -1
- package/dist/sandbox/provision.d.ts +1 -1
- package/dist/server/errors-envelope.cjs +14 -14
- package/dist/server/errors-envelope.d.cts +3 -3
- package/dist/server/errors-envelope.d.ts +3 -3
- package/dist/server/errors-envelope.js +3 -3
- package/dist/session-transcript-7FWTO4BK.js +5 -0
- package/dist/{session-transcript-X3UMSVL2.js.map → session-transcript-7FWTO4BK.js.map} +1 -1
- package/dist/session-transcript-FYRKWRWV.cjs +50 -0
- package/dist/{session-transcript-SLQRKQ72.cjs.map → session-transcript-FYRKWRWV.cjs.map} +1 -1
- package/dist/skills.cjs +7 -7
- package/dist/skills.js +5 -5
- package/dist/stream-object-3R3HZPQN.cjs +20 -0
- package/dist/{stream-object-3HEUGMQY.cjs.map → stream-object-3R3HZPQN.cjs.map} +1 -1
- package/dist/stream-object-NPJXDZXO.js +7 -0
- package/dist/{stream-object-VWYW7FJ2.js.map → stream-object-NPJXDZXO.js.map} +1 -1
- package/dist/subagents-loader-5KQVYUNS.js +6 -0
- package/dist/{subagents-loader-QUIK6GMV.js.map → subagents-loader-5KQVYUNS.js.map} +1 -1
- package/dist/subagents-loader-FDXPBBRA.cjs +15 -0
- package/dist/{subagents-loader-F52ARQ62.cjs.map → subagents-loader-FDXPBBRA.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +15 -15
- package/dist/subagents-loader.cjs.map +1 -1
- package/dist/subagents-loader.d.cts +2 -2
- package/dist/subagents-loader.d.ts +2 -2
- package/dist/subagents-loader.js +14 -14
- package/dist/subagents-loader.js.map +1 -1
- 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/run-events.d.ts +20 -1
- package/dist/types/session-record.d.ts +1 -1
- package/dist/types/usage.d.ts +1 -1
- package/dist/workflow.cjs +27 -27
- package/dist/workflow.js +6 -6
- package/docs/error-codes.md +22 -0
- package/docs/harness-capability-map.md +22 -0
- package/package.json +1 -1
- package/dist/agent-MSR3DHO4.js +0 -46
- package/dist/agent-OOXJJD6A.cjs +0 -55
- package/dist/agent-session-store-EGTTYSKS.js +0 -6
- package/dist/agent-session-store-RHTLZ5OX.cjs +0 -23
- package/dist/chunk-23HI77BZ.js.map +0 -1
- package/dist/chunk-33B2BSME.cjs.map +0 -1
- package/dist/chunk-5KOW3GLE.js.map +0 -1
- package/dist/chunk-5XPKYDK7.js.map +0 -1
- package/dist/chunk-7GFX45DD.js.map +0 -1
- package/dist/chunk-AKMPQJPX.js.map +0 -1
- package/dist/chunk-BURYFNOM.cjs.map +0 -1
- package/dist/chunk-BVGJXMSB.cjs.map +0 -1
- package/dist/chunk-EYUZZXHZ.js.map +0 -1
- package/dist/chunk-KRPEPZQY.js.map +0 -1
- package/dist/chunk-LNTQRD23.cjs.map +0 -1
- package/dist/chunk-N4JNY5DT.cjs.map +0 -1
- package/dist/chunk-NJVV5OAV.cjs.map +0 -1
- package/dist/chunk-ONVIALVV.js.map +0 -1
- package/dist/chunk-QMIG7TKG.cjs.map +0 -1
- package/dist/chunk-RNCN2TTP.js.map +0 -1
- package/dist/chunk-SEWAPWAF.cjs.map +0 -1
- package/dist/chunk-T6KFGMNY.cjs.map +0 -1
- package/dist/chunk-UIPTINIF.js.map +0 -1
- package/dist/chunk-V7CA3CX5.cjs.map +0 -1
- package/dist/chunk-WPZTYOUX.cjs.map +0 -1
- package/dist/chunk-X627TO3A.js.map +0 -1
- package/dist/chunk-ZRQZOJ3N.js.map +0 -1
- package/dist/compact-session-AZU2LEAE.js +0 -18
- package/dist/compact-session-TRCEYCPG.cjs +0 -55
- package/dist/context-DNFT4B5D.cjs +0 -22
- package/dist/context-LYE6TJL5.js +0 -5
- package/dist/fs-session-store-I6GUIFRO.js +0 -10
- package/dist/fs-session-store-KRZZIG3O.cjs +0 -19
- package/dist/generate-object-DLHT5RXH.js +0 -7
- package/dist/generate-object-QILSGTEJ.cjs +0 -20
- package/dist/index-manager-LEMQ73A7.cjs +0 -20
- package/dist/index-manager-SXF3FAQV.js +0 -11
- package/dist/judge-call-AIT3EULV.cjs +0 -22
- package/dist/judge-call-NPRU7JIQ.js +0 -5
- package/dist/registry-AXQXPLFH.js +0 -9
- package/dist/registry-VKDFTK6L.cjs +0 -46
- package/dist/run-until-BK56WG4P.js.map +0 -1
- package/dist/run-until-L5KQD3PV.cjs.map +0 -1
- package/dist/session-transcript-SLQRKQ72.cjs +0 -50
- package/dist/session-transcript-X3UMSVL2.js +0 -5
- package/dist/stream-object-3HEUGMQY.cjs +0 -20
- package/dist/stream-object-VWYW7FJ2.js +0 -7
- package/dist/subagents-loader-F52ARQ62.cjs +0 -15
- package/dist/subagents-loader-QUIK6GMV.js +0 -6
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAWA,0BAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAAA,0BAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAOA,0BAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,UAAA,GAAaA,0BAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AAC1C,IAA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A;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-N4JNY5DT.cjs","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const maisAntiga = sessions.keys().next().value;\n if (maisAntiga === undefined) return;\n sessions.delete(maisAntiga);\n esquecerEscrituracao(maisAntiga);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction esquecerEscrituracao(agentId: string): void {\n const sufixo = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(sufixo)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(sufixo)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(sufixo)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` limpava **dois** dos quatro mapas (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // arriscado. Rastreado em usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/session-transcript.ts"],"names":["redactSecrets","randomUUID","join","homedir","path","mkdir","dirname","replaceFileAtomic","readFile"],"mappings":";;;;;;;;;AAkDO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA;AACzC;AAGO,SAAS,cAAc,EAAA,EAAoB;AA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Y,OAAO,GAAA,CAAI,IAAA,KAAS,WAAW,GAAA,GAAM,KAAA,CAAA;AAAA,EAC9E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGA,eAAsB,eAAe,IAAA,EAAwC;AAC3E,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAMI,iBAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACnC,SAAS,KAAA,EAAO;AACd,IAAA,IAAK,KAAA,CAAgC,IAAA,KAAS,QAAA,EAAU,OAAO,EAAC;AAChE,IAAA,MAAM,KAAA;AAAA,EACR;AACA,EAAA,OAAO,GAAA,CACJ,KAAA,CAAM,IAAI,CAAA,CACV,GAAA,CAAI,eAAe,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAA0B,CAAA,KAAM,MAAS,CAAA;AACtD","file":"chunk-NJVV5OAV.cjs","sourcesContent":["/**\n * SE40 — native session transcript (Claude-Code-compatible on-disk shape, theokit-native names).\n *\n * The theokit session format IS the Claude Code record shape (a `uuid`/`parentUuid` DAG of records with\n * structured `text`/`tool_use`/`tool_result`/`thinking` blocks) — so the ecosystem's read-side tools\n * parse our sessions AND, pointed at `~/.claude`, the Claude Code CLI can `--continue` them. This module\n * is the PURE core: append-per-turn record builders + the DAG reader that rebuilds `LlmMessage[]` for\n * resume. File I/O + loop wiring + append-only compaction live in the FS store.\n *\n * Reader mirrors `claude-code-log` dag.py: leaf = a uuid never used as a parentUuid; walk parentUuid to a\n * root (cycle-break); dedup a uuid across sessions keeping the earliest; a `compact_boundary` root\n * terminates the walk so a resume-after-compaction replays only the post-boundary continuation.\n *\n * referencia: knowledge-base/references/claude-code-log/claude_code_log/dag.py + models.py\n */\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport type { SessionRecord, TranscriptBlock } from \"../../types/session-record.js\";\nimport type { LlmContentPart, LlmMessage, LlmToolResultPart } from \"../llm/types.js\";\nimport { redactSecrets } from \"../security/redact.js\";\nimport { replaceFileAtomic } from \"./atomic-write.js\";\n\n// The `SessionRecord` contract now lives in the domain `types/` layer (SE46 DIP\n// direction). Re-exported here so existing importers of this DAG-core module\n// keep resolving the same name.\nexport type { SessionRecord } from \"../../types/session-record.js\";\n\nexport interface SessionTranscriptOptions {\n cwd: string;\n sessionId: string;\n model: string;\n version?: string;\n}\n\nexport interface AssistantTurn {\n text?: string;\n thinking?: string;\n /**\n * theokit#122 — the provider's signature for the thinking block. Written into the `thinking`\n * record block (`Block` already declared `signature?`), so a resumed session can replay the block\n * exactly as the provider issued it.\n */\n thinkingSignature?: string;\n toolCalls?: Array<{ id: string; name: string; input: Record<string, unknown> }>;\n}\n\n/** Claude Code path convention: cwd with every non-alphanumeric replaced by `-`. */\nexport function encodeProjectDir(cwd: string): string {\n return cwd.replace(/[^a-zA-Z0-9]/g, \"-\");\n}\n\n/** Make a caller-supplied session id safe as a path component (no traversal). */\nexport function safeSessionId(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, \"-\");\n}\n\nconst red = (s: string): string => redactSecrets(s);\n\n/** Deep-redact a structured value (tool input) preserving object shape. */\nfunction redactValue(value: unknown): unknown {\n try {\n return JSON.parse(redactSecrets(JSON.stringify(value ?? null)));\n } catch {\n return redactSecrets(String(value));\n }\n}\n\n// M94 — it was `Record<string, unknown>`. The published type describes the same shape this file\n// has always produced; the local alias now points at it so writer and reader cannot\n// diverge silently.\ntype Block = TranscriptBlock;\n\n/**\n * Builds a session transcript append-by-append, maintaining the `parentUuid` chain. Each turn mints a\n * fresh `uuid` and parents on the previous record; `appendCompactBoundary` starts a NEW ROOT.\n */\nexport class SessionTranscript {\n #records: SessionRecord[] = [];\n #last: string | null = null;\n #opts: SessionTranscriptOptions;\n\n constructor(opts: SessionTranscriptOptions) {\n this.#opts = opts;\n }\n\n /**\n * Seed a transcript from records already on disk so a subsequent append parents\n * on the existing DAG leaf (the last record in file order). Prior records are\n * re-emitted verbatim by {@link records}, so the whole file rewrites atomically\n * as one append-only line set — never shrinking (SE40 compaction is append-only).\n */\n static fromRecords(\n prior: readonly SessionRecord[],\n opts: SessionTranscriptOptions,\n ): SessionTranscript {\n const t = new SessionTranscript(opts);\n t.#records = [...prior];\n t.#last = prior.length > 0 ? (prior[prior.length - 1]?.uuid ?? null) : null;\n return t;\n }\n\n #push(\n rec: Omit<SessionRecord, \"uuid\" | \"parentUuid\" | \"sessionId\" | \"timestamp\">,\n ): SessionRecord {\n const full: SessionRecord = {\n ...rec,\n uuid: randomUUID(),\n parentUuid: this.#last,\n sessionId: this.#opts.sessionId,\n timestamp: new Date().toISOString(),\n isSidechain: false,\n userType: \"external\",\n cwd: this.#opts.cwd,\n version: this.#opts.version ?? \"1.0.0-theokit\",\n };\n this.#records.push(full);\n this.#last = full.uuid;\n return full;\n }\n\n appendUserTurn(text: string): SessionRecord {\n return this.#push({\n type: \"user\",\n message: { role: \"user\", content: [{ type: \"text\", text: red(text) }] },\n });\n }\n\n appendAssistantTurn(turn: AssistantTurn): SessionRecord {\n const content: Block[] = [];\n if (turn.thinking) {\n // theokit#122 — the signature is computed by the provider over the ORIGINAL text, so it is\n // only valid while the text is byte-identical. Redaction rewrites the text; keeping the\n // signature next to a masked body persists a pair that Anthropic rejects with\n // `400 \"thinking blocks cannot be modified\"` — the very failure this issue exists to remove.\n //\n // So redaction WINS and the signature is dropped. The block survives as display-only history\n // (`thinkingToWireBlock` already refuses to replay an unsigned block), which loses one block\n // of context; keeping a signature that cannot verify would lose the whole turn.\n //\n // The signature itself is never redacted — it is an opaque provider token with no user\n // content — but that was only half the reasoning the first version of this fix wrote down.\n const redactedThinking = red(turn.thinking);\n const signatureStillValid =\n turn.thinkingSignature !== undefined && redactedThinking === turn.thinking;\n content.push({\n type: \"thinking\",\n thinking: redactedThinking,\n ...(signatureStillValid ? { signature: turn.thinkingSignature } : {}),\n });\n }\n if (turn.text) content.push({ type: \"text\", text: red(turn.text) });\n for (const c of turn.toolCalls ?? []) {\n content.push({ type: \"tool_use\", id: c.id, name: c.name, input: redactValue(c.input) });\n }\n return this.#push({\n type: \"assistant\",\n message: {\n id: randomUUID(),\n type: \"message\",\n role: \"assistant\",\n model: this.#opts.model,\n content,\n },\n });\n }\n\n appendToolResults(\n results: Array<{ toolUseId: string; content: string; isError?: boolean }>,\n ): SessionRecord {\n const content: Block[] = results.map((r) => ({\n type: \"tool_result\",\n tool_use_id: r.toolUseId,\n content: red(r.content),\n is_error: r.isError === true,\n }));\n return this.#push({ type: \"user\", message: { role: \"user\", content } });\n }\n\n /** Append-only compaction: a `compact_boundary` system record becomes a NEW ROOT (parentUuid null). */\n appendCompactBoundary(meta: { preTokens: number; trigger: string }): SessionRecord {\n const rec: SessionRecord = {\n type: \"system\",\n uuid: randomUUID(),\n parentUuid: null,\n sessionId: this.#opts.sessionId,\n timestamp: new Date().toISOString(),\n subtype: \"compact_boundary\",\n compactMetadata: meta,\n isSidechain: false,\n userType: \"external\",\n cwd: this.#opts.cwd,\n version: this.#opts.version ?? \"1.0.0-theokit\",\n };\n this.#records.push(rec);\n this.#last = rec.uuid;\n return rec;\n }\n\n records(): readonly SessionRecord[] {\n return this.#records;\n }\n}\n\n// ─── Reader (DAG → LlmMessage[]) ──────────────────────────────────────────────────────────────────\n\n/** Earliest timestamp seen per session id. */\nfunction sessionFirstTimestamps(records: readonly SessionRecord[]): Map<string, string> {\n const first = new Map<string, string>();\n for (const r of records) {\n const cur = first.get(r.sessionId);\n if (cur === undefined || r.timestamp < cur) first.set(r.sessionId, r.timestamp);\n }\n return first;\n}\n\n/** Dedup a uuid across sessions: keep the record whose session's earliest timestamp is smallest. */\nfunction dedupByUuid(records: readonly SessionRecord[]): Map<string, SessionRecord> {\n const firstTs = sessionFirstTimestamps(records);\n const byUuid = new Map<string, SessionRecord>();\n for (const r of records) {\n const existing = byUuid.get(r.uuid);\n const wins =\n existing === undefined ||\n (firstTs.get(r.sessionId) ?? \"\") < (firstTs.get(existing.sessionId) ?? \"\");\n if (wins) byUuid.set(r.uuid, r);\n }\n return byUuid;\n}\n\n/**\n * Map one structured block to an `LlmContentPart`.\n *\n * theokit#122 — thinking blocks used to be DROPPED here, which is why an extended-thinking session\n * could not be resumed: the block never made it back into the replayed messages, so the provider saw\n * a conversation whose assistant turn had lost its thinking. They are now reconstructed with their\n * signature; the Anthropic wire re-serializes signed blocks and skips unsigned ones.\n */\nfunction thinkingBlockToPart(b: Extract<Block, { type: \"thinking\" }>): LlmContentPart {\n return {\n type: \"thinking\",\n text: String(b.thinking ?? \"\"),\n ...(b.signature !== undefined ? { signature: String(b.signature) } : {}),\n };\n}\n\nfunction blockToPart(b: Block): LlmContentPart | undefined {\n if (b.type === \"text\") return { type: \"text\", text: String(b.text ?? \"\") };\n if (b.type === \"thinking\") return thinkingBlockToPart(b);\n if (b.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: String(b.id),\n name: String(b.name),\n input: (b.input as Record<string, unknown>) ?? {},\n };\n }\n if (b.type === \"tool_result\") {\n const tr: LlmToolResultPart = {\n type: \"tool_result\",\n toolUseId: String(b.tool_use_id),\n content: typeof b.content === \"string\" ? b.content : JSON.stringify(b.content),\n isError: b.is_error === true,\n };\n return tr;\n }\n return undefined;\n}\n\n/** Map one record to an LlmMessage; `undefined` for non-conversational (system) records. */\nfunction recordToMessage(rec: SessionRecord): LlmMessage | undefined {\n if (rec.type !== \"user\" && rec.type !== \"assistant\") return undefined;\n const blocks = rec.message?.content ?? [];\n const parts = blocks.map(blockToPart).filter((p): p is LlmContentPart => p !== undefined);\n return { role: rec.type, content: parts };\n}\n\n/** The most-recent leaf: the LAST record (in input order) whose uuid is never used as a parentUuid. */\nfunction findLatestLeaf(\n records: readonly SessionRecord[],\n byUuid: Map<string, SessionRecord>,\n parents: Set<string>,\n): SessionRecord | undefined {\n let leaf: SessionRecord | undefined;\n for (const r of records) {\n if (byUuid.get(r.uuid) === r && !parents.has(r.uuid)) leaf = r;\n }\n return leaf;\n}\n\n/** Walk parentUuid from a leaf to a root (cycle-safe), returning root→leaf order. */\nfunction walkToRoot(leaf: SessionRecord, byUuid: Map<string, SessionRecord>): SessionRecord[] {\n const chain: SessionRecord[] = [];\n const seen = new Set<string>();\n let cur: SessionRecord | undefined = leaf;\n while (cur !== undefined && !seen.has(cur.uuid)) {\n seen.add(cur.uuid);\n chain.push(cur);\n cur = cur.parentUuid !== null ? byUuid.get(cur.parentUuid) : undefined;\n }\n return chain.reverse();\n}\n\n/**\n * Rebuild the resumable `LlmMessage[]` from transcript records: dedup → find the most-recent leaf →\n * walk `parentUuid` to a root (a `compact_boundary` root terminates the walk) → map to LlmMessages.\n * Returns them in root→leaf (chronological replay) order.\n */\nexport function reconstructMessages(records: readonly SessionRecord[]): LlmMessage[] {\n const byUuid = dedupByUuid(records);\n const parents = new Set<string>();\n for (const r of byUuid.values()) if (r.parentUuid) parents.add(r.parentUuid);\n const leaf = findLatestLeaf(records, byUuid, parents);\n if (leaf === undefined) return [];\n\n const msgs: LlmMessage[] = [];\n for (const rec of walkToRoot(leaf, byUuid)) {\n const m = recordToMessage(rec);\n if (m !== undefined) msgs.push(m);\n }\n return msgs;\n}\n\n// ─── File I/O (the on-disk Claude layout) ─────────────────────────────────────────────────────────\n\n/**\n * Raiz do estado de transcript.\n *\n * `THEOKIT_HOME` wins; the fallback is `~/.theokit`. Home-anchored on purpose, and NOT\n * `paths.ts`'s `getTheokitHome(cwd)`: that one falls back to `<cwd>/.theokit`, and switching\n * by it would move the transcript of everyone who does **not** set the variable. The sibling with the\n * right shape is `catalog-source-models-dev.ts` (M94 ADR-2).\n *\n * Before M94 this function ignored the env var, so whoever set it had their state split in\n * two silently — sessions stayed in `~/.theokit` while the rest of the SDK migrated.\n */\nexport function transcriptRoot(): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) return override;\n return join(homedir(), \".theokit\");\n}\n\n/** @deprecated Use {@link transcriptRoot}. Kept as an alias — same value. */\nexport function defaultBaseDir(): string {\n return transcriptRoot();\n}\n\n/**\n * Expand a leading `~` / `~/` to the user's home dir. `node:path` does NOT expand `~`, so a\n * `baseDir: \"~/.claude\"` (the documented Claude Code CLI interop path) would otherwise resolve to a\n * literal `./~/.claude` under cwd and the CLI would never find the session. Absolute or relative\n * paths without a leading tilde pass through untouched.\n */\nexport function expandTilde(p: string): string {\n if (p === \"~\") return homedir();\n if (p.startsWith(\"~/\")) return join(homedir(), p.slice(2));\n return p;\n}\n\n/** The `.jsonl` path for a session: `<baseDir>/projects/<encoded-cwd>/<safe-sessionId>.jsonl`. */\nexport function transcriptPath(baseDir: string, cwd: string, sessionId: string): string {\n return join(baseDir, \"projects\", encodeProjectDir(cwd), `${safeSessionId(sessionId)}.jsonl`);\n}\n\n/** Write records as one JSONL line each (atomic; parent dir created). Returns the path. */\nexport async function writeTranscript(\n path: string,\n records: readonly SessionRecord[],\n): Promise<string> {\n await mkdir(dirname(path), { recursive: true });\n const body = records.map((r) => JSON.stringify(r)).join(\"\\n\");\n await replaceFileAtomic(path, records.length > 0 ? `${body}\\n` : \"\");\n return path;\n}\n\n/** Parse one JSONL line to a record; `undefined` for blank/torn/invalid lines (skipped on read). */\nfunction parseRecordLine(line: string): SessionRecord | undefined {\n const trimmed = line.trim();\n if (trimmed.length === 0) return undefined;\n try {\n const rec = JSON.parse(trimmed) as SessionRecord;\n return typeof rec.uuid === \"string\" && typeof rec.type === \"string\" ? rec : undefined;\n } catch {\n return undefined; // a torn last line (crash mid-write) — the rest of the DAG still reconstructs\n }\n}\n\n/** Parse a transcript `.jsonl` into records; a missing file yields `[]`; malformed lines are skipped. */\nexport async function readTranscript(path: string): Promise<SessionRecord[]> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw cause;\n }\n return raw\n .split(\"\\n\")\n .map(parseRecordLine)\n .filter((r): r is Session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AAA,CAAI,SAAS,SAAS,CAAA;AACjC;AAQA,eAAsB,kBAAA,GAAoC;AACxD,EAAA,OAAO,aAAA,CAAc,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAEO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-ONVIALVV.js","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const maisAntiga = sessions.keys().next().value;\n if (maisAntiga === undefined) return;\n sessions.delete(maisAntiga);\n esquecerEscrituracao(maisAntiga);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction esquecerEscrituracao(agentId: string): void {\n const sufixo = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(sufixo)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(sufixo)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(sufixo)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` limpava **dois** dos quatro mapas (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // arriscado. Rastreado em usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/run-events.ts","../src/internal/task/ring-buffer.ts","../src/internal/task/subscribe.ts","../src/internal/task/task-run-event-bridge.ts","../src/internal/task/telemetry.ts","../src/internal/task/registry.ts"],"names":["subscribe","isValidTaskId","TaskNotFoundError","getTracer","noopSpan","AsyncLocalStorage","InMemoryTaskStore","getTaskStoreFor","createSemaphore","diag","randomUUID","InvalidTaskIdError"],"mappings":";;;;;;;;;;;AAiJO,SAAS,YAAA,CAAa,MAAgC,KAAA,EAAuB;AAClF,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,KAAK,CAAA;AAAA,EACZ,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;AC9IO,IAAM,aAAN,MAAoB;AAAA,EAIzB,YAA6B,GAAA,EAAa;AAAb,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,GAAG,CAAA,IAAK,MAAM,CAAA,EAAG;AACrC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,oDAAA,EAAuD,GAAG,CAAA,CAAE,CAAA;AAAA,IAC9E;AAAA,EACF;AAAA,EAJ6B,GAAA;AAAA,EAHZ,MAAW,EAAC;AAAA,EACrB,SAAA,GAAY,KAAA;AAAA,EAQpB,KAAK,IAAA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O,IAAA;AAAA,EACT,CAAA;AAAA,EACA,gBAAA,EAAkB,CAAC,EAAA,EAAI,EAAA,KAAO;AAC5B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAE,CAAA;AACpC,IAAA,GAAA,EAAK,OAAO,EAAE,CAAA;AACd,IAAA,IAAI,GAAA,KAAQ,UAAa,GAAA,CAAI,IAAA,KAAS,GAAG,KAAA,CAAM,WAAA,CAAY,OAAO,EAAE,CAAA;AAAA,EACtE;AACF,CAAC","file":"chunk-QMIG7TKG.cjs","sourcesContent":["/**\n * SE2 — typed runtime EVENT stream, ADDITIVE to the `SDKMessage` content stream.\n *\n * `Run.stream()` yields `SDKMessage`s (the conversation content). `RunEvent`s are\n * out-of-band runtime-OBSERVABILITY signals — the model's content is unaffected —\n * delivered opt-in via `SendOptions.onRunEvent`. Discriminate on `type`. Mirrors\n * the Anthropic `SDKMessage`-union approach (rate-limit, permission-denied, task\n * lifecycle, compaction boundary).\n *\n * The union is the forward-compatible CONTRACT (discriminate exhaustively). The\n * runtime EMITS every variant end-to-end: `tool_progress` + `permission_denied`\n * (agent-loop tool-dispatch seam), `rate_limit` (pool-aware LLM client 429 retry),\n * `compact_boundary` (session auto-compaction), and `task_*` (opt-in bridge from a\n * `Task.submit({ onRunEvent })` task's lifecycle). A consumer switching on `type`\n * sees the real signal.\n *\n * @public\n */\nexport type RunEvent =\n | RunToolProgressEvent\n | RunRateLimitEvent\n | RunPermissionDeniedEvent\n | RunTaskStartedEvent\n | RunTaskUpdatedEvent\n | RunTaskCompletedEvent\n | RunCompactBoundaryEvent\n | RunCompactionFallbackEvent\n | RunTripwireEvent\n | RunCompletionCheckEvent;\n\n/**\n * SE24 — a guardrail processor called `abort()`; the run stops with a tripwire.\n * Delivered via {@link SendOptions.onRunEvent} (mirrors the `RunResult.tripwire`\n * surfaced on `wait()`).\n */\nexport interface RunTripwireEvent {\n readonly type: \"tripwire\";\n readonly reason: string;\n readonly processorId: string;\n}\n\n/** A tool call is being dispatched (before its result). */\nexport interface RunToolProgressEvent {\n readonly type: \"tool_progress\";\n readonly toolName: string;\n readonly toolCallId: string;\n}\n\n/** The provider returned a rate-limit (HTTP 429); the loop will back off + retry. */\nexport interface RunRateLimitEvent {\n readonly type: \"rate_limit\";\n /** Retry attempt number (1-based) about to be delayed. */\n readonly attempt: number;\n /** Delay in ms before the retry, when the provider/policy supplied one. */\n readonly retryAfterMs?: number;\n}\n\n/**\n * A tool call was DENIED before dispatch — by the permission gate/plugin (SE1),\n * an operator file-hook `preToolUse`, or the fork tool-whitelist. `source`\n * discriminates which. `toolCallId` joins the event to the tool-call log.\n */\nexport interface RunPermissionDeniedEvent {\n readonly type: \"permission_denied\";\n readonly toolName: string;\n readonly toolCallId: string;\n /** Which layer blocked the call. */\n readonly source: \"plugin\" | \"file_hook\" | \"fork_whitelist\";\n /** The rejection message surfaced to the model. */\n readonly message: string;\n}\n\n/** A background task/subagent started. */\nexport interface RunTaskStartedEvent {\n readonly type: \"task_started\";\n readonly taskId: string;\n readonly description?: string;\n}\n\n/** A background task/subagent changed state. */\nexport interface RunTaskUpdatedEvent {\n readonly type: \"task_updated\";\n readonly taskId: string;\n readonly status: string;\n}\n\n/** A background task/subagent finished. */\nexport interface RunTaskCompletedEvent {\n readonly type: \"task_completed\";\n readonly taskId: string;\n readonly status: \"completed\" | \"failed\" | \"stopped\";\n}\n\n/**\n * SE34 — the per-send completion check (`isTaskComplete`) produced a verdict.\n * Emitted once, after a finished run's reply is judged against\n * {@link SendOptions.completionCheck}. Distinct from `task_completed` (which is\n * background-task/subagent lifecycle). Mirrors {@link RunResult.completionCheck}.\n */\nexport interface RunCompletionCheckEvent {\n readonly type: \"completion_check\";\n readonly complete: boolean;\n readonly reason: string;\n}\n\n/** The conversation crossed a compaction boundary (history was summarized). */\nexport interface RunCompactBoundaryEvent {\n readonly type: \"compact_boundary\";\n readonly trigger: \"manual\" | \"auto\";\n /** Token count before compaction, when known. */\n readonly preTokens?: number;\n}\n\n/**\n * M77 — auto-compaction is budgeting against a FLOOR, because neither the catalog nor the caller\n * supplied a context window for this model.\n *\n * The prior behaviour was to disable auto-compaction entirely and write one line to stderr per\n * process. That is fail-OPEN: the conversation grows until the provider rejects it. This event exists\n * so a surface can say \"I am running without a real budget\" instead of the user discovering it at the\n * moment of failure.\n *\n * Not emitted when the window came from the catalog (the normal path) or from an explicit caller\n * override (the caller already knows).\n */\nexport interface RunCompactionFallbackEvent {\n readonly type: \"compaction_fallback\";\n /** The model whose window is unknown — what the user needs to fix in configuration. */\n readonly model: string;\n /** The floor being budgeted against, after the safety margin. */\n readonly window: number;\n}\n\n/**\n * SE2 — the opt-in sink for {@link RunEvent}s. Supplied via `SendOptions.onRunEvent`.\n * Synchronous + best-effort: a throwing sink must never break the run (the emitter\n * try-catches it), so keep it fast (push to a queue, don't await).\n */\nexport type RunEventSink = (event: RunEvent) => void;\n\n/**\n * SE2 — emit a {@link RunEvent} to an optional sink, swallowing any sink error so\n * observability can never break the run (fail-safe, mirrors the EventBus EC-2\n * contract). No-op when the sink is absent.\n */\nexport function emitRunEvent(sink: RunEventSink | undefined, event: RunEvent): void {\n if (sink === undefined) return;\n try {\n sink(event);\n } catch {\n // best-effort: an observability sink must never break the run.\n }\n}\n","/**\n * Bounded FIFO ring buffer for late-attach replay (ADR D372).\n *\n * Push always succeeds; when the buffer is at capacity the oldest\n * entry is dropped and the `truncated` flag flips to `true`. Drain\n * returns a snapshot + the current truncated flag.\n *\n * @internal\n */\n\nexport class RingBuffer<T> {\n private readonly buf: T[] = [];\n private truncated = false;\n\n constructor(private readonly cap: number) {\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);\n }\n }\n\n push(item: T): void {\n if (this.buf.length >= this.cap) {\n this.buf.shift();\n this.truncated = true;\n }\n this.buf.push(item);\n }\n\n drain(): { readonly items: readonly T[]; readonly truncated: boolean } {\n return { items: this.buf.slice(), truncated: this.truncated };\n }\n\n size(): number {\n return this.buf.length;\n }\n\n wasTruncated(): boolean {\n return this.truncated;\n }\n}\n","/**\n * `subscribe(id)` — emits the per-task event stream (D372 ring buffer\n * + live tail). The returned AsyncIterable implements `return()` for\n * leak-free cleanup (EC-10).\n *\n * @internal\n */\n\nimport { TaskNotFoundError } from \"../../errors.js\";\nimport { isValidTaskId, type TaskEvent } from \"../../types/task.js\";\nimport type { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface SubscribeDeps {\n getBuffer(id: string): RingBuffer<TaskEvent> | undefined;\n getOrCreateSubscriberSet(id: string): Set<(e: TaskEvent) => void>;\n removeSubscriber(id: string, cb: (e: TaskEvent) => void): void;\n}\n\nfunction isTerminalEvent(event: TaskEvent): boolean {\n return event.type === \"finished\" || event.type === \"errored\" || event.type === \"cancelled\";\n}\n\nfunction drainBuffered(buffer: RingBuffer<TaskEvent>): TaskEvent[] {\n const { items, truncated } = buffer.drain();\n const queue = items.slice();\n if (truncated && queue.length > 0) {\n const first = queue[0];\n if (first !== undefined && first.type === \"submitted\") {\n queue[0] = { ...first, truncated: true } satisfies TaskEvent;\n }\n }\n return queue;\n}\n\nclass TaskIterator implements AsyncIterator<TaskEvent> {\n private readonly queue: TaskEvent[];\n private pendingResolve?: (v: IteratorResult<TaskEvent>) => void;\n private done = false;\n private readonly callback: (e: TaskEvent) => void;\n\n constructor(\n buffer: RingBuffer<TaskEvent>,\n private readonly id: string,\n private readonly deps: SubscribeDeps,\n ) {\n this.queue = drainBuffered(buffer);\n this.callback = (e) => this.deliver(e);\n deps.getOrCreateSubscriberSet(id).add(this.callback);\n }\n\n private deliver(e: TaskEvent): void {\n if (this.done) return;\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: e, done: false });\n } else {\n this.queue.push(e);\n }\n }\n\n private cleanup(): void {\n if (this.done) return;\n this.done = true;\n this.deps.removeSubscriber(this.id, this.callback);\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: undefined, done: true });\n }\n }\n\n private dequeue(): IteratorResult<TaskEvent> | undefined {\n const event = this.queue.shift();\n if (event === undefined) return undefined;\n if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());\n return { value: event, done: false };\n }\n\n next(): Promise<IteratorResult<TaskEvent>> {\n if (this.done) return Promise.resolve({ value: undefined, done: true });\n const queued = this.dequeue();\n if (queued !== undefined) return Promise.resolve(queued);\n return new Promise((resolve) => {\n this.pendingResolve = resolve;\n });\n }\n\n return(): Promise<IteratorResult<TaskEvent>> {\n this.cleanup();\n return Promise.resolve({ value: undefined, done: true });\n }\n}\n\nexport function buildSubscribe(deps: SubscribeDeps) {\n return function subscribe(id: string): AsyncIterable<TaskEvent> {\n if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);\n const buffer = deps.getBuffer(id);\n if (buffer === undefined) throw new TaskNotFoundError(id);\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TaskEvent> {\n return new TaskIterator(buffer, id, deps);\n },\n };\n };\n}\n","/**\n * SE2 — the `TaskEvent` → `task_*` RunEvent bridge for the opt-in `onRunEvent`\n * sink. Extracted from `registry.ts` (a pure, self-contained mapping) to keep\n * the registry within the G8 LoC budget and give the bridge one home.\n *\n * @internal\n */\n\nimport type { RunEvent } from \"../../types/run-events.js\";\nimport type { TaskEvent, TaskKind } from \"../../types/task.js\";\n\n/** Map a `TaskEvent` to a `task_*` RunEvent, or `undefined` when it has no counterpart. */\nexport function taskEventToRunEvent(\n event: TaskEvent,\n taskId: string,\n kind: TaskKind,\n): RunEvent | undefined {\n switch (event.type) {\n case \"started\":\n return { type: \"task_started\", taskId, description: kind };\n case \"progress\":\n return { type: \"task_updated\", taskId, status: \"progress\" };\n case \"finished\":\n return { type: \"task_completed\", taskId, status: \"completed\" };\n case \"errored\":\n return { type: \"task_completed\", taskId, status: \"failed\" };\n case \"cancelled\":\n return { type: \"task_completed\", taskId, status: \"stopped\" };\n default:\n return undefined; // `submitted` (queued) has no RunEvent counterpart\n }\n}\n","/**\n * OTel telemetry for the Task registry (ADR D371).\n *\n * Spans:\n * - `task.submit` — short-lived span around the submit + insert.\n * - `task.transition` — per state transition (attrs: from / to).\n * - `task.cancel` — invoked from `Task.cancel` or via cancelRequested honor.\n *\n * Uses the existing tracer seam (D34); when OTel is absent, every helper\n * returns the shared no-op span. No new peer deps.\n *\n * @internal\n */\n\nimport { getTracer, noopSpan, type SpanLike } from \"../telemetry/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/task\";\n\nexport function startTaskSubmitSpan(info: { taskId: string; kind: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.submit\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.kind\": info.kind,\n },\n });\n}\n\nexport function startTaskTransitionSpan(info: {\n taskId: string;\n from: string;\n to: string;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.transition\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.state.from\": info.from,\n \"task.state.to\": info.to,\n },\n });\n}\n\nexport function startTaskCancelSpan(info: {\n taskId: string;\n reason?: string;\n via: \"api\" | \"cancelRequested\";\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.cancel\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.cancel.via\": info.via,\n ...(info.reason !== undefined ? { \"task.cancel.reason\": info.reason } : {}),\n },\n });\n}\n","/**\n * `TaskRegistry` — the singleton coordinating Task submit/list/get/cancel/\n * subscribe. Wraps the pluggable `TaskStore` (D364), the `AsyncSemaphore`\n * (D135 / D369) and a per-task `RingBuffer<TaskEvent>` (D372) for\n * late-attach replay.\n *\n * Edge cases absorbed:\n * - EC-3: work-fn invocation goes through `Promise.resolve().then(...)`\n * so synchronous throws become rejected promises.\n * - EC-4: pre-aborted signal short-circuits to `cancelled` without\n * acquiring a semaphore slot.\n * - EC-7: cross-process cancel via the `cancelRequested` flag on\n * `TaskHandle`. Registry polls at start + each progress event.\n * - EC-9: store-update failures are caught + logged; the event is\n * still emitted so subscribers always observe a terminal event.\n * - EC-10: subscribe iterator implements `return()` for leak-free\n * cleanup.\n * - EC-11: reentrant submit (work-fn calling `Task.submit`) uses an\n * ALS marker to bypass the semaphore queue, avoiding deadlock under\n * low concurrency caps.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport {\n isValidTaskId,\n type TaskCancelResult,\n type TaskEvent,\n type TaskFilter,\n type TaskHandle,\n type TaskKind,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type AsyncSemaphore, createSemaphore } from \"../runtime/concurrency/async-semaphore.js\";\nimport { RingBuffer } from \"./ring-buffer.js\";\nimport { getTaskStoreFor, InMemoryTaskStore, type TaskStore } from \"./store.js\";\nimport { buildSubscribe } from \"./subscribe.js\";\nimport { taskEventToRunEvent } from \"./task-run-event-bridge.js\";\nimport { startTaskCancelSpan, startTaskSubmitSpan, startTaskTransitionSpan } from \"./telemetry.js\";\n\nconst DEFAULT_CONCURRENCY = 8;\nconst DEFAULT_RETENTION_MS = 60 * 60 * 1000;\nconst EVICTION_INTERVAL_MS = 5 * 60 * 1000;\nconst RING_CAP = 64;\n\n/** EC-11 — ALS flag indicating we are inside a task work-fn. Reentrant submits bypass the semaphore. */\nconst reentryAls = new AsyncLocalStorage<boolean>();\n\nexport interface TaskRegistryOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\ntype WorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\ninterface InternalState {\n readonly store: TaskStore;\n readonly semaphore: AsyncSemaphore;\n readonly aborters: Map<string, AbortController>;\n readonly buffers: Map<string, RingBuffer<TaskEvent>>;\n readonly subscribers: Map<string, Set<(e: TaskEvent) => void>>;\n retentionMs: number;\n evictTimer?: NodeJS.Timeout;\n firstSubmitSeen: boolean;\n}\n\nfunction buildState(opts: TaskRegistryOptions): InternalState {\n const store = opts.store === undefined ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);\n return {\n store,\n semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),\n aborters: new Map(),\n buffers: new Map(),\n subscribers: new Map(),\n retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,\n firstSubmitSeen: false,\n };\n}\n\nlet state: InternalState = buildState({});\n\nexport function __resetTaskRegistryForTests(): void {\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState({});\n}\n\nexport function __getSubscribersCountForTests(taskId: string): number {\n return state.subscribers.get(taskId)?.size ?? 0;\n}\n\nexport function configure(opts: TaskRegistryOptions): void {\n if (state.firstSubmitSeen) {\n diag(\n \"[task] configure() ignored — registry already in use; reset via __resetTaskRegistryForTests()\\n\",\n );\n return;\n }\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState(opts);\n}\n\nfunction emitToSubscribers(taskId: string, event: TaskEvent): void {\n const buffer = state.buffers.get(taskId);\n if (buffer !== undefined) buffer.push(event);\n const subs = state.subscribers.get(taskId);\n if (subs === undefined) return;\n for (const cb of subs) {\n try {\n cb(event);\n } catch (err) {\n diag(`[task] subscriber threw: ${(err as Error).message}\\n`);\n }\n }\n}\n\nasync function safeUpdate(\n taskId: string,\n mutate: (h: TaskHandle) => TaskHandle,\n): Promise<TaskHandle | undefined> {\n try {\n return await state.store.update(taskId, mutate);\n } catch (err) {\n // EC-9: store failure should not swallow the event.\n diag(`[task] store.update failed for ${taskId}: ${(err as Error).message}\\n`);\n return undefined;\n }\n}\n\nfunction startEvictTimerIfNeeded(): void {\n if (state.evictTimer !== undefined) return;\n state.evictTimer = setInterval(() => {\n const cutoff = Date.now() - state.retentionMs;\n void state.store\n .evictTerminalOlderThan(cutoff)\n .then((count) => {\n if (count === 0) return;\n // Also drop buffers + subscribers for evicted tasks. We don't\n // know which ones were dropped — clean up any task whose store\n // entry is gone.\n for (const id of state.buffers.keys()) {\n void state.store.get(id).then((h) => {\n if (h === undefined) {\n state.buffers.delete(id);\n state.subscribers.delete(id);\n state.aborters.delete(id);\n }\n });\n }\n })\n .catch(() => {\n /* swallow timer errors */\n });\n }, EVICTION_INTERVAL_MS).unref();\n}\n\nfunction buildSubmittedEvent(handle: TaskHandle): TaskEvent {\n return {\n type: \"submitted\",\n taskId: handle.id,\n kind: handle.kind,\n submittedAt: handle.submittedAt,\n ...(handle.meta !== undefined ? { meta: handle.meta } : {}),\n };\n}\n\nasync function shortCircuitAborted(handle: TaskHandle, signal: AbortSignal): Promise<TaskHandle> {\n // EC-4: pre-aborted signal — skip queue/semaphore.\n const cancelled: TaskHandle = {\n ...handle,\n state: \"cancelled\",\n cancelledAt: Date.now(),\n };\n await state.store.insert(cancelled);\n state.buffers.set(handle.id, new RingBuffer(RING_CAP));\n emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));\n emitToSubscribers(handle.id, {\n type: \"cancelled\",\n taskId: handle.id,\n cancelledAt: cancelled.cancelledAt ?? Date.now(),\n reason: signal.reason instanceof Error ? signal.reason.message : \"pre-aborted\",\n });\n return cancelled;\n}\n\nasync function transition<T extends TaskState>(\n taskId: string,\n next: T,\n patch: Partial<TaskHandle>,\n): Promise<void> {\n const before = await state.store.get(taskId);\n const span = startTaskTransitionSpan({\n taskId,\n from: before?.state ?? \"unknown\",\n to: next,\n });\n try {\n await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));\n } finally {\n span.end();\n }\n}\n\ninterface SubmitInternal<T> {\n readonly kind: TaskKind;\n readonly work: WorkFn<T>;\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n readonly signal?: AbortSignal;\n /** When true (adapter-internal), the validator allows reserved prefixes. */\n readonly allowReservedPrefix?: boolean;\n /** SE2 — forward this task's lifecycle to the run-event sink as `task_*` RunEvents. */\n readonly onRunEvent?: import(\"../../types/run-events.js\").RunEventSink;\n}\n\nasync function buildAndInsertQueued(\n internal: SubmitInternal<unknown>,\n resolvedId: string,\n): Promise<TaskHandle> {\n const submittedAt = Date.now();\n const handle: TaskHandle = {\n id: resolvedId,\n kind: internal.kind,\n state: \"queued\",\n submittedAt,\n ...(internal.meta !== undefined ? { meta: internal.meta } : {}),\n };\n await state.store.insert(handle);\n state.buffers.set(resolvedId, new RingBuffer(RING_CAP));\n emitToSubscribers(resolvedId, buildSubmittedEvent(handle));\n return handle;\n}\n\nfunction resolveIdInternal(internal: SubmitInternal<unknown>): string {\n if (internal.id === undefined) return randomUUID();\n if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {\n throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);\n }\n return internal.id;\n}\n\nasync function runWorkAndFinalize<T>(\n taskId: string,\n aborter: AbortController,\n work: WorkFn<T>,\n): Promise<void> {\n const ctx: TaskWorkContext = {\n signal: aborter.signal,\n emit(payload) {\n // EC-7: check cancelRequested at every progress checkpoint.\n void checkCancelRequestedAt(taskId, aborter);\n emitToSubscribers(taskId, {\n type: \"progress\",\n taskId,\n at: Date.now(),\n payload,\n });\n },\n };\n\n try {\n const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const finishedAt = Date.now();\n await transition(taskId, \"finished\", { finishedAt, result });\n emitToSubscribers(taskId, { type: \"finished\", taskId, finishedAt, result });\n } catch (err) {\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const erroredAt = Date.now();\n const error =\n err instanceof Error\n ? { code: (err as { code?: string }).code ?? \"work_threw\", message: err.message }\n : { code: \"work_threw\", message: String(err) };\n await transition(taskId, \"error\", { erroredAt, error });\n emitToSubscribers(taskId, { type: \"errored\", taskId, erroredAt, error });\n }\n}\n\nasync function checkCancelRequestedAt(taskId: string, aborter: AbortController): Promise<void> {\n if (aborter.signal.aborted) return;\n try {\n const handle = await state.store.get(taskId);\n if (handle?.cancelRequested === true) {\n aborter.abort(\"cancelRequested\");\n }\n } catch {\n /* ignore — best-effort poll */\n }\n}\n\nasync function acquireSlot(): Promise<() => void> {\n if (reentryAls.getStore() === true) {\n // EC-11: reentrant submit bypasses the queue.\n return () => {\n /* no-op */\n };\n }\n return state.semaphore.acquire();\n}\n\n/**\n * Submit a task. Validates id (D368, EC-5 via allowReservedPrefix),\n * handles pre-aborted signals (EC-4), enforces single-flight by id\n * (D367), runs work under semaphore (D369/EC-11 reentrant bypass),\n * and produces the canonical event stream (D366).\n */\nexport async function submit<T>(internal: SubmitInternal<T>): Promise<TaskHandle> {\n state.firstSubmitSeen = true;\n startEvictTimerIfNeeded();\n\n const resolvedId = resolveIdInternal(internal);\n // SE2 — bridge the task lifecycle to the caller's run-event sink (opt-in).\n if (internal.onRunEvent !== undefined) {\n const sink = internal.onRunEvent;\n const kind = internal.kind;\n const subs = state.subscribers.get(resolvedId) ?? new Set();\n subs.add((e: TaskEvent) => {\n const runEvent = taskEventToRunEvent(e, resolvedId, kind);\n if (runEvent !== undefined) emitRunEvent(sink, runEvent);\n });\n state.subscribers.set(resolvedId, subs);\n }\n const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });\n\n // D367 single-flight.\n const existing = await state.store.get(resolvedId);\n if (existing !== undefined) {\n submitSpan.end();\n return existing;\n }\n\n const queuedHandle = await buildAndInsertQueued(internal, resolvedId);\n submitSpan.end();\n\n // EC-4: pre-aborted signal — short-circuit.\n if (internal.signal?.aborted === true) {\n return shortCircuitAborted(queuedHandle, internal.signal);\n }\n\n const aborter = new AbortController();\n state.aborters.set(resolvedId, aborter);\n if (internal.signal !== undefined) {\n internal.signal.addEventListener(\"abort\", () => aborter.abort(internal.signal?.reason), {\n once: true,\n });\n }\n\n // Fire and forget the actual run; the returned handle is the queued one.\n const release = await acquireSlot();\n void (async () => {\n try {\n // Check cancelRequested before starting (EC-7).\n await checkCancelRequestedAt(resolvedId, aborter);\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(resolvedId, \"cancelled\", { cancelledAt });\n emitToSubscribers(resolvedId, { type: \"cancelled\", taskId: resolvedId, cancelledAt });\n return;\n }\n const startedAt = Date.now();\n await transition(resolvedId, \"running\", { startedAt });\n emitToSubscribers(resolvedId, { type: \"started\", taskId: resolvedId, startedAt });\n await runWorkAndFinalize(resolvedId, aborter, internal.work as WorkFn<unknown>);\n } finally {\n release();\n state.aborters.delete(resolvedId);\n }\n })();\n\n return queuedHandle;\n}\n\nexport async function list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return state.store.list(filter);\n}\n\nexport async function get(id: string): Promise<TaskHandle | undefined> {\n if (!isValidTaskId(id, true)) return undefined;\n return state.store.get(id);\n}\n\nexport async function cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };\n const handle = await state.store.get(id);\n if (handle === undefined) return { cancelled: false, alreadyTerminal: false };\n if (handle.state === \"finished\" || handle.state === \"error\" || handle.state === \"cancelled\") {\n return { cancelled: false, alreadyTerminal: true };\n }\n const span = startTaskCancelSpan({\n taskId: id,\n ...(reason !== undefined ? { reason } : {}),\n via: \"api\",\n });\n try {\n return await cancelInternal(id, handle.state, reason);\n } finally {\n span.end();\n }\n}\n\nasync function cancelInternal(\n id: string,\n currentState: TaskState,\n reason?: string,\n): Promise<TaskCancelResult> {\n if (currentState === \"queued\") {\n const cancelledAt = Date.now();\n await transition(id, \"cancelled\", { cancelledAt });\n emitToSubscribers(id, {\n type: \"cancelled\",\n taskId: id,\n cancelledAt,\n ...(reason !== undefined ? { reason } : {}),\n });\n state.aborters.delete(id);\n return { cancelled: true, alreadyTerminal: false };\n }\n // running: trigger AbortController; runWorkAndFinalize handles the transition.\n const aborter = state.aborters.get(id);\n if (aborter !== undefined) aborter.abort(reason ?? \"cancelled\");\n return { cancelled: true, alreadyTerminal: false };\n}\n\nexport const subscribe = buildSubscribe({\n getBuffer: (id) => state.buffers.get(id),\n getOrCreateSubscriberSet: (id) => {\n let subs = state.subscribers.get(id);\n if (subs === undefined) {\n subs = new Set();\n state.subscribers.set(id, subs);\n }\n return subs;\n },\n removeSubscriber: (id, cb) => {\n const set = state.subscribers.get(id);\n set?.delete(cb);\n if (set !== undefined && set.size === 0) state.subscribers.delete(id);\n },\n});\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/diagnostics.ts","../src/internal/security/redact.ts"],"names":[],"mappings":";AAoEA,IAAM,SAAA,mBAAY,MAAA,CAAO,GAAA,CAAI,iCAAiC,CAAA;AAI9D,SAAS,WAAA,GAA2C;AAClD,EAAA,OAAQ,WAAqC,SAAS,CAAA;AACxD;AASO,SAAS,mBAAmB,IAAA,EAAyC;AAC1E,EAAC,UAAA,CAAqC,SAAS,CAAA,GAAI,IAAA;AACrD;AAQO,SAAS,KAAK,OAAA,EAAuB;AAG1C,EAAA,MAAM,OAAO,WAAA,EAAY;AACzB,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,OAAO,CAAA;AAAA,EACd,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;AC/EA,IAAI,iBAA0B,WAAA,EAAY;AAE1C,SAAS,WAAA,GAAuB;AAC9B,EAAA,MAAM,GAAA,GAAM,QAAQ,GAAA,CAAI,sBAAA;AAC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CAAQ,EAAA,EAAI,CAAC,CAAA,KAAM,SAAA,CAAU,CAAC,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,KAAA,MAAW,MAAM,cAAA,EAAgB;AAC/B,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,EAAA,EAAI,CAAC,CAAA,KAAM,SAAA,CAAU,CAAC,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,CAAC,MAAM,QAAA,EAAU;AAInB,IAAA,CAAA,GAAI,CAAA,CAAE,QAAQ,cAAA,EAAgB,CAAC,GAAG,MAAA,KAAmB,CAAA,EAAG,MAAM,CAAA,GAAA,CAAK,CAAA;AAInE,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,aAAA,EAAe,CAAC,KAAA,EAAO,QAAgB,KAAA,KAAkB;AAOrE,MAAA,IAAI,UAAA,CAAW,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AACnC,MAAA,OAAO,GAAG,MAAM,CAAA,GAAA,CAAA;AAAA,IAClB,CAAC,CAAA;AAAA,EACH;AACA,EAAA,OAAO,CAAA;AACT","file":"chunk-RNCN2TTP.js","sourcesContent":["/**\n * The library's single diagnostics channel — silent by default (#147).\n *\n * ## O problema\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 * ## O contrato\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","import { diag } from \"../diagnostics.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 const raw = process.env.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"]}
|