@theokit/sdk 4.63.0 → 4.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/a2a/index.cjs +2 -2
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent-WK7MKIMH.cjs +66 -0
  5. package/dist/{agent-5KYMG63I.cjs.map → agent-WK7MKIMH.cjs.map} +1 -1
  6. package/dist/agent-YWMBM7LX.js +57 -0
  7. package/dist/{agent-536OOESZ.js.map → agent-YWMBM7LX.js.map} +1 -1
  8. package/dist/agent-session-store-6EL5NPA4.cjs +24 -0
  9. package/dist/{agent-session-store-WAKLOKWK.cjs.map → agent-session-store-6EL5NPA4.cjs.map} +1 -1
  10. package/dist/agent-session-store-OPGRB4XM.js +7 -0
  11. package/dist/{agent-session-store-G2BMUZQV.js.map → agent-session-store-OPGRB4XM.js.map} +1 -1
  12. package/dist/auth/index.cjs +18 -18
  13. package/dist/auth/index.js +6 -6
  14. package/dist/{batch-ND32UKZS.cjs → batch-BXYTW2DP.cjs} +27 -27
  15. package/dist/{batch-ND32UKZS.cjs.map → batch-BXYTW2DP.cjs.map} +1 -1
  16. package/dist/{batch-2TGJMNCJ.js → batch-L4ZXS46M.js} +10 -10
  17. package/dist/{batch-2TGJMNCJ.js.map → batch-L4ZXS46M.js.map} +1 -1
  18. package/dist/{chunk-VF7EWVDG.js → chunk-2GUYQR5P.js} +3 -3
  19. package/dist/{chunk-VF7EWVDG.js.map → chunk-2GUYQR5P.js.map} +1 -1
  20. package/dist/{chunk-J2UROOIG.cjs → chunk-2HVF2WJY.cjs} +8 -8
  21. package/dist/{chunk-J2UROOIG.cjs.map → chunk-2HVF2WJY.cjs.map} +1 -1
  22. package/dist/{chunk-44MBDIHG.js → chunk-2QDYBS2A.js} +3 -3
  23. package/dist/{chunk-44MBDIHG.js.map → chunk-2QDYBS2A.js.map} +1 -1
  24. package/dist/{chunk-NGESVVJN.cjs → chunk-3FFAEAUJ.cjs} +17 -17
  25. package/dist/{chunk-NGESVVJN.cjs.map → chunk-3FFAEAUJ.cjs.map} +1 -1
  26. package/dist/{chunk-GWC3HADL.cjs → chunk-3NSS2OIZ.cjs} +4 -4
  27. package/dist/{chunk-GWC3HADL.cjs.map → chunk-3NSS2OIZ.cjs.map} +1 -1
  28. package/dist/{chunk-CV7XMBHP.js → chunk-3O42QOMJ.js} +3 -3
  29. package/dist/{chunk-CV7XMBHP.js.map → chunk-3O42QOMJ.js.map} +1 -1
  30. package/dist/{chunk-IWBGCBR6.cjs → chunk-4CLOXP6H.cjs} +4 -4
  31. package/dist/{chunk-IWBGCBR6.cjs.map → chunk-4CLOXP6H.cjs.map} +1 -1
  32. package/dist/{chunk-YEXA3PGR.js → chunk-4FFBAUFS.js} +5 -5
  33. package/dist/{chunk-YEXA3PGR.js.map → chunk-4FFBAUFS.js.map} +1 -1
  34. package/dist/{chunk-HY57ULY2.cjs → chunk-4PYZ5AX3.cjs} +5 -5
  35. package/dist/{chunk-HY57ULY2.cjs.map → chunk-4PYZ5AX3.cjs.map} +1 -1
  36. package/dist/{chunk-OC4NTGMN.js → chunk-4QZSA2HJ.js} +3 -3
  37. package/dist/{chunk-OC4NTGMN.js.map → chunk-4QZSA2HJ.js.map} +1 -1
  38. package/dist/{chunk-K3FW2XZD.cjs → chunk-4ZHTIJNE.cjs} +9 -9
  39. package/dist/{chunk-K3FW2XZD.cjs.map → chunk-4ZHTIJNE.cjs.map} +1 -1
  40. package/dist/{chunk-BUIK7GUA.cjs → chunk-5HEG4CQH.cjs} +8 -8
  41. package/dist/{chunk-BUIK7GUA.cjs.map → chunk-5HEG4CQH.cjs.map} +1 -1
  42. package/dist/{chunk-NXH4GPAQ.cjs → chunk-5VB22SYX.cjs} +7 -7
  43. package/dist/{chunk-NXH4GPAQ.cjs.map → chunk-5VB22SYX.cjs.map} +1 -1
  44. package/dist/{chunk-5USCYPPI.cjs → chunk-6HKGLTJI.cjs} +8 -8
  45. package/dist/{chunk-5USCYPPI.cjs.map → chunk-6HKGLTJI.cjs.map} +1 -1
  46. package/dist/{chunk-EHJEZAOO.cjs → chunk-6RKUO7AW.cjs} +32 -32
  47. package/dist/{chunk-EHJEZAOO.cjs.map → chunk-6RKUO7AW.cjs.map} +1 -1
  48. package/dist/{chunk-5JLFFPCH.js → chunk-7YGCPMGB.js} +4 -4
  49. package/dist/{chunk-5JLFFPCH.js.map → chunk-7YGCPMGB.js.map} +1 -1
  50. package/dist/{chunk-SUKXXLWD.js → chunk-A46SWMIF.js} +6 -6
  51. package/dist/{chunk-SUKXXLWD.js.map → chunk-A46SWMIF.js.map} +1 -1
  52. package/dist/{chunk-F7AQV62G.js → chunk-A4JVILQU.js} +5 -5
  53. package/dist/{chunk-F7AQV62G.js.map → chunk-A4JVILQU.js.map} +1 -1
  54. package/dist/{chunk-44JAAH4X.js → chunk-B3IMEBOA.js} +3 -3
  55. package/dist/{chunk-44JAAH4X.js.map → chunk-B3IMEBOA.js.map} +1 -1
  56. package/dist/{chunk-QDED6YO6.cjs → chunk-B4EOJWOY.cjs} +5 -5
  57. package/dist/{chunk-QDED6YO6.cjs.map → chunk-B4EOJWOY.cjs.map} +1 -1
  58. package/dist/{chunk-YJDH3CKG.js → chunk-BP46RJ5X.js} +5 -5
  59. package/dist/{chunk-YJDH3CKG.js.map → chunk-BP46RJ5X.js.map} +1 -1
  60. package/dist/{chunk-QRSUA2CV.js → chunk-BU4KFWXF.js} +3 -3
  61. package/dist/{chunk-QRSUA2CV.js.map → chunk-BU4KFWXF.js.map} +1 -1
  62. package/dist/{chunk-MG3SOM3M.js → chunk-BVJJ3DRV.js} +6 -6
  63. package/dist/{chunk-MG3SOM3M.js.map → chunk-BVJJ3DRV.js.map} +1 -1
  64. package/dist/{chunk-AQLGBKNT.js → chunk-BZRFXJHA.js} +3 -3
  65. package/dist/{chunk-AQLGBKNT.js.map → chunk-BZRFXJHA.js.map} +1 -1
  66. package/dist/{chunk-UQGQFBRL.js → chunk-C3NT3PVE.js} +3 -3
  67. package/dist/{chunk-UQGQFBRL.js.map → chunk-C3NT3PVE.js.map} +1 -1
  68. package/dist/{chunk-UC3HT2S4.js → chunk-C72AZW7J.js} +3 -3
  69. package/dist/{chunk-UC3HT2S4.js.map → chunk-C72AZW7J.js.map} +1 -1
  70. package/dist/{chunk-WNTAPVU5.cjs → chunk-CQBXOJ6U.cjs} +13 -13
  71. package/dist/{chunk-WNTAPVU5.cjs.map → chunk-CQBXOJ6U.cjs.map} +1 -1
  72. package/dist/{chunk-T7XEKOVW.js → chunk-D4CUGAKZ.js} +3 -3
  73. package/dist/{chunk-T7XEKOVW.js.map → chunk-D4CUGAKZ.js.map} +1 -1
  74. package/dist/{chunk-R6TA2DRJ.js → chunk-DKD3MH6A.js} +6 -6
  75. package/dist/{chunk-R6TA2DRJ.js.map → chunk-DKD3MH6A.js.map} +1 -1
  76. package/dist/{chunk-YXGAW7BB.js → chunk-DN2PACRI.js} +10 -10
  77. package/dist/{chunk-YXGAW7BB.js.map → chunk-DN2PACRI.js.map} +1 -1
  78. package/dist/{chunk-XSX2UU6Y.cjs → chunk-DXGZ2NUG.cjs} +10 -10
  79. package/dist/{chunk-XSX2UU6Y.cjs.map → chunk-DXGZ2NUG.cjs.map} +1 -1
  80. package/dist/{chunk-NUKRL3I6.cjs → chunk-EG4QM7ZJ.cjs} +18 -2
  81. package/dist/chunk-EG4QM7ZJ.cjs.map +1 -0
  82. package/dist/{chunk-C7QPML3L.js → chunk-GEEXBYFL.js} +9 -9
  83. package/dist/{chunk-C7QPML3L.js.map → chunk-GEEXBYFL.js.map} +1 -1
  84. package/dist/{chunk-A4VHSE56.cjs → chunk-GKEFRLU7.cjs} +6 -6
  85. package/dist/{chunk-A4VHSE56.cjs.map → chunk-GKEFRLU7.cjs.map} +1 -1
  86. package/dist/{chunk-NIRE5CNO.cjs → chunk-HCZD23VS.cjs} +13 -13
  87. package/dist/{chunk-NIRE5CNO.cjs.map → chunk-HCZD23VS.cjs.map} +1 -1
  88. package/dist/{chunk-IRCJ7EHV.cjs → chunk-HOXVQ5FR.cjs} +14 -14
  89. package/dist/{chunk-IRCJ7EHV.cjs.map → chunk-HOXVQ5FR.cjs.map} +1 -1
  90. package/dist/{chunk-QARJGQSA.js → chunk-HS7AVXTF.js} +3 -3
  91. package/dist/{chunk-QARJGQSA.js.map → chunk-HS7AVXTF.js.map} +1 -1
  92. package/dist/{chunk-4I55V454.cjs → chunk-I6HGWHPU.cjs} +4 -4
  93. package/dist/{chunk-4I55V454.cjs.map → chunk-I6HGWHPU.cjs.map} +1 -1
  94. package/dist/{chunk-T73NA43R.js → chunk-IPYYKCRC.js} +3 -3
  95. package/dist/{chunk-T73NA43R.js.map → chunk-IPYYKCRC.js.map} +1 -1
  96. package/dist/{chunk-UUP3MUZ6.cjs → chunk-ITYQ6VBP.cjs} +18 -18
  97. package/dist/{chunk-UUP3MUZ6.cjs.map → chunk-ITYQ6VBP.cjs.map} +1 -1
  98. package/dist/chunk-JPBKYL3B.cjs +18 -0
  99. package/dist/{chunk-6HTXPPHK.cjs.map → chunk-JPBKYL3B.cjs.map} +1 -1
  100. package/dist/{chunk-MZ2FGBLZ.js → chunk-K5OJUYSZ.js} +4 -4
  101. package/dist/{chunk-MZ2FGBLZ.js.map → chunk-K5OJUYSZ.js.map} +1 -1
  102. package/dist/{chunk-CHKH5452.js → chunk-KIH6IZ43.js} +60 -45
  103. package/dist/chunk-KIH6IZ43.js.map +1 -0
  104. package/dist/{chunk-EI2Q7SJ5.cjs → chunk-KQ7TS7WW.cjs} +10 -10
  105. package/dist/{chunk-EI2Q7SJ5.cjs.map → chunk-KQ7TS7WW.cjs.map} +1 -1
  106. package/dist/{chunk-RUDY2GTT.js → chunk-KQRW2GPZ.js} +5 -5
  107. package/dist/{chunk-RUDY2GTT.js.map → chunk-KQRW2GPZ.js.map} +1 -1
  108. package/dist/{chunk-P5LCASTC.cjs → chunk-KYAJINUI.cjs} +125 -125
  109. package/dist/{chunk-P5LCASTC.cjs.map → chunk-KYAJINUI.cjs.map} +1 -1
  110. package/dist/{chunk-AMFXSENK.js → chunk-LWGSI6M3.js} +4 -4
  111. package/dist/{chunk-AMFXSENK.js.map → chunk-LWGSI6M3.js.map} +1 -1
  112. package/dist/{chunk-ZHPWGIUX.js → chunk-LXI4XZEC.js} +5 -5
  113. package/dist/{chunk-ZHPWGIUX.js.map → chunk-LXI4XZEC.js.map} +1 -1
  114. package/dist/{chunk-AG5JPQIY.js → chunk-LXQ6HKPS.js} +3 -3
  115. package/dist/{chunk-AG5JPQIY.js.map → chunk-LXQ6HKPS.js.map} +1 -1
  116. package/dist/{chunk-ROYPRJH4.cjs → chunk-LYRDF5TQ.cjs} +9 -9
  117. package/dist/{chunk-ROYPRJH4.cjs.map → chunk-LYRDF5TQ.cjs.map} +1 -1
  118. package/dist/{chunk-G24KZRSA.js → chunk-N2U4AZGB.js} +3 -3
  119. package/dist/{chunk-G24KZRSA.js.map → chunk-N2U4AZGB.js.map} +1 -1
  120. package/dist/{chunk-4ERPXIVB.js → chunk-O73J46PV.js} +5 -5
  121. package/dist/{chunk-4ERPXIVB.js.map → chunk-O73J46PV.js.map} +1 -1
  122. package/dist/{chunk-F3YZMOAU.cjs → chunk-O7DK5PBJ.cjs} +4 -4
  123. package/dist/{chunk-F3YZMOAU.cjs.map → chunk-O7DK5PBJ.cjs.map} +1 -1
  124. package/dist/{chunk-Z4BCLVTI.cjs → chunk-O7LZFG6O.cjs} +5 -5
  125. package/dist/{chunk-Z4BCLVTI.cjs.map → chunk-O7LZFG6O.cjs.map} +1 -1
  126. package/dist/{chunk-3YJNUKYN.cjs → chunk-OHLDPWTA.cjs} +15 -15
  127. package/dist/{chunk-3YJNUKYN.cjs.map → chunk-OHLDPWTA.cjs.map} +1 -1
  128. package/dist/{chunk-FUL2I7G5.js → chunk-OSEG74VJ.js} +8 -8
  129. package/dist/{chunk-FUL2I7G5.js.map → chunk-OSEG74VJ.js.map} +1 -1
  130. package/dist/{chunk-UCBJBJ27.js → chunk-PUAEFLYK.js} +4 -4
  131. package/dist/{chunk-UCBJBJ27.js.map → chunk-PUAEFLYK.js.map} +1 -1
  132. package/dist/{chunk-CASUEY42.cjs → chunk-Q7LPTOD6.cjs} +24 -24
  133. package/dist/{chunk-CASUEY42.cjs.map → chunk-Q7LPTOD6.cjs.map} +1 -1
  134. package/dist/{chunk-2C72DXQF.cjs → chunk-RFMBZPOW.cjs} +9 -9
  135. package/dist/{chunk-2C72DXQF.cjs.map → chunk-RFMBZPOW.cjs.map} +1 -1
  136. package/dist/{chunk-NLTVXLGT.js → chunk-RFXWMRFC.js} +3 -3
  137. package/dist/{chunk-NLTVXLGT.js.map → chunk-RFXWMRFC.js.map} +1 -1
  138. package/dist/{chunk-2DG7KW4L.cjs → chunk-RMWTPV3M.cjs} +8 -8
  139. package/dist/{chunk-2DG7KW4L.cjs.map → chunk-RMWTPV3M.cjs.map} +1 -1
  140. package/dist/{chunk-P6A3M6VD.cjs → chunk-SZVR77EJ.cjs} +10 -10
  141. package/dist/{chunk-P6A3M6VD.cjs.map → chunk-SZVR77EJ.cjs.map} +1 -1
  142. package/dist/{chunk-3E77SX4H.js → chunk-TAZVKYWJ.js} +3 -3
  143. package/dist/{chunk-3E77SX4H.js.map → chunk-TAZVKYWJ.js.map} +1 -1
  144. package/dist/{chunk-WKRSH2VR.js → chunk-U6IFHFWK.js} +3 -3
  145. package/dist/{chunk-WKRSH2VR.js.map → chunk-U6IFHFWK.js.map} +1 -1
  146. package/dist/{chunk-I6TGFUCO.cjs → chunk-UALX2J2Q.cjs} +4 -4
  147. package/dist/{chunk-I6TGFUCO.cjs.map → chunk-UALX2J2Q.cjs.map} +1 -1
  148. package/dist/{chunk-XN7NOENA.js → chunk-UBDMVMBZ.js} +5 -5
  149. package/dist/{chunk-XN7NOENA.js.map → chunk-UBDMVMBZ.js.map} +1 -1
  150. package/dist/{chunk-YTR3RBUZ.js → chunk-UEXIJTLC.js} +4 -4
  151. package/dist/{chunk-YTR3RBUZ.js.map → chunk-UEXIJTLC.js.map} +1 -1
  152. package/dist/{chunk-DQKERTND.cjs → chunk-UGT7GK7I.cjs} +11 -11
  153. package/dist/{chunk-DQKERTND.cjs.map → chunk-UGT7GK7I.cjs.map} +1 -1
  154. package/dist/{chunk-FKMUFNQE.js → chunk-UMP6OJIM.js} +4 -4
  155. package/dist/{chunk-FKMUFNQE.js.map → chunk-UMP6OJIM.js.map} +1 -1
  156. package/dist/{chunk-AEOZTXVW.js → chunk-UNYXQ4M5.js} +3 -3
  157. package/dist/{chunk-AEOZTXVW.js.map → chunk-UNYXQ4M5.js.map} +1 -1
  158. package/dist/{chunk-2BDH744Z.js → chunk-UTSRIDKZ.js} +3 -3
  159. package/dist/{chunk-2BDH744Z.js.map → chunk-UTSRIDKZ.js.map} +1 -1
  160. package/dist/{chunk-2ADR2GSO.cjs → chunk-UU36SHFY.cjs} +5 -5
  161. package/dist/{chunk-2ADR2GSO.cjs.map → chunk-UU36SHFY.cjs.map} +1 -1
  162. package/dist/{chunk-R3UPQFKK.cjs → chunk-V2BOS4WF.cjs} +9 -9
  163. package/dist/{chunk-R3UPQFKK.cjs.map → chunk-V2BOS4WF.cjs.map} +1 -1
  164. package/dist/{chunk-Q4CMI2LP.js → chunk-WLQNMXQE.js} +5 -5
  165. package/dist/{chunk-Q4CMI2LP.js.map → chunk-WLQNMXQE.js.map} +1 -1
  166. package/dist/{chunk-XWL6O3SW.cjs → chunk-WNO3C3N2.cjs} +4 -4
  167. package/dist/{chunk-XWL6O3SW.cjs.map → chunk-WNO3C3N2.cjs.map} +1 -1
  168. package/dist/{chunk-T7O6K6PX.js → chunk-XEQ3TM66.js} +18 -3
  169. package/dist/chunk-XEQ3TM66.js.map +1 -0
  170. package/dist/{chunk-BVZW2B5V.cjs → chunk-XJCXEKMD.cjs} +4 -4
  171. package/dist/{chunk-BVZW2B5V.cjs.map → chunk-XJCXEKMD.cjs.map} +1 -1
  172. package/dist/{chunk-JTB5Q42C.cjs → chunk-XL7Q7HB2.cjs} +4 -4
  173. package/dist/{chunk-JTB5Q42C.cjs.map → chunk-XL7Q7HB2.cjs.map} +1 -1
  174. package/dist/{chunk-LW7G5DYW.js → chunk-XO4SOZN6.js} +4 -4
  175. package/dist/{chunk-LW7G5DYW.js.map → chunk-XO4SOZN6.js.map} +1 -1
  176. package/dist/{chunk-CQGYNZ3K.cjs → chunk-XWTLIGO3.cjs} +4 -4
  177. package/dist/{chunk-CQGYNZ3K.cjs.map → chunk-XWTLIGO3.cjs.map} +1 -1
  178. package/dist/{chunk-6SBW4QR2.cjs → chunk-YML4ME27.cjs} +11 -11
  179. package/dist/{chunk-6SBW4QR2.cjs.map → chunk-YML4ME27.cjs.map} +1 -1
  180. package/dist/{chunk-P6H23T43.cjs → chunk-ZCIRZE37.cjs} +11 -11
  181. package/dist/{chunk-P6H23T43.cjs.map → chunk-ZCIRZE37.cjs.map} +1 -1
  182. package/dist/{chunk-QI7WE46I.cjs → chunk-ZLQSWSJ2.cjs} +11 -11
  183. package/dist/{chunk-QI7WE46I.cjs.map → chunk-ZLQSWSJ2.cjs.map} +1 -1
  184. package/dist/{chunk-NLXOGBRJ.cjs → chunk-ZMRD5DZQ.cjs} +338 -323
  185. package/dist/chunk-ZMRD5DZQ.cjs.map +1 -0
  186. package/dist/{chunk-ILCGLTSA.cjs → chunk-ZSWPZ23K.cjs} +4 -4
  187. package/dist/{chunk-ILCGLTSA.cjs.map → chunk-ZSWPZ23K.cjs.map} +1 -1
  188. package/dist/{chunk-IDCKSLYH.js → chunk-ZZMZWBR6.js} +3 -3
  189. package/dist/{chunk-IDCKSLYH.js.map → chunk-ZZMZWBR6.js.map} +1 -1
  190. package/dist/compact-session-QV57KR66.cjs +59 -0
  191. package/dist/{compact-session-GJXJD73F.cjs.map → compact-session-QV57KR66.cjs.map} +1 -1
  192. package/dist/compact-session-RIGOWC4Y.js +22 -0
  193. package/dist/{compact-session-TSMQOIHO.js.map → compact-session-RIGOWC4Y.js.map} +1 -1
  194. package/dist/compaction.cjs +17 -17
  195. package/dist/compaction.js +4 -4
  196. package/dist/concurrency.cjs +7 -7
  197. package/dist/concurrency.js +5 -5
  198. package/dist/context-AGQ3DIZU.cjs +24 -0
  199. package/dist/{context-LCKNH2XI.cjs.map → context-AGQ3DIZU.cjs.map} +1 -1
  200. package/dist/context-GQRFBCLP.js +7 -0
  201. package/dist/{context-MZSKGKYR.js.map → context-GQRFBCLP.js.map} +1 -1
  202. package/dist/cron.cjs +36 -36
  203. package/dist/cron.js +35 -35
  204. package/dist/errors.cjs +22 -22
  205. package/dist/errors.js +3 -3
  206. package/dist/eval.cjs +41 -41
  207. package/dist/eval.js +35 -35
  208. package/dist/{executor-ZERJ3DGN.cjs → executor-6CYCA7MI.cjs} +25 -25
  209. package/dist/{executor-ZERJ3DGN.cjs.map → executor-6CYCA7MI.cjs.map} +1 -1
  210. package/dist/{executor-BMEHFOXZ.js → executor-QSEC3MRH.js} +8 -8
  211. package/dist/{executor-BMEHFOXZ.js.map → executor-QSEC3MRH.js.map} +1 -1
  212. package/dist/filesystem/index.cjs +8 -8
  213. package/dist/filesystem/index.js +4 -4
  214. package/dist/fs-session-store-4PIHT5UX.cjs +20 -0
  215. package/dist/{fs-session-store-XZ7ZTB3A.cjs.map → fs-session-store-4PIHT5UX.cjs.map} +1 -1
  216. package/dist/fs-session-store-NM6YSTE2.js +11 -0
  217. package/dist/{fs-session-store-4BHGIWRE.js.map → fs-session-store-NM6YSTE2.js.map} +1 -1
  218. package/dist/generate-object-GUNAUVBX.js +8 -0
  219. package/dist/{generate-object-N5MDZUJI.js.map → generate-object-GUNAUVBX.js.map} +1 -1
  220. package/dist/generate-object-R7HTMW7F.cjs +21 -0
  221. package/dist/{generate-object-PGSP5U7N.cjs.map → generate-object-R7HTMW7F.cjs.map} +1 -1
  222. package/dist/index-manager-RBDHP3PM.js +17 -0
  223. package/dist/{index-manager-ACEQG3IJ.js.map → index-manager-RBDHP3PM.js.map} +1 -1
  224. package/dist/index-manager-UZBF22BJ.cjs +26 -0
  225. package/dist/{index-manager-6TEEIWM7.cjs.map → index-manager-UZBF22BJ.cjs.map} +1 -1
  226. package/dist/index.cjs +139 -139
  227. package/dist/index.js +50 -50
  228. package/dist/{inject-session-ZCQUB3IT.js → inject-session-DAR7OUCW.js} +8 -8
  229. package/dist/{inject-session-ZCQUB3IT.js.map → inject-session-DAR7OUCW.js.map} +1 -1
  230. package/dist/{inject-session-PPSO2IDD.cjs → inject-session-WQKMC3GR.cjs} +10 -10
  231. package/dist/{inject-session-PPSO2IDD.cjs.map → inject-session-WQKMC3GR.cjs.map} +1 -1
  232. package/dist/internal/memory/adapters/index.cjs +9 -9
  233. package/dist/internal/memory/adapters/index.js +8 -8
  234. package/dist/internal/memory/storage/index.cjs +39 -39
  235. package/dist/internal/memory/storage/index.js +10 -10
  236. package/dist/internal/persistence/index.cjs +21 -21
  237. package/dist/internal/persistence/index.js +7 -7
  238. package/dist/internal/security/index.cjs +14 -14
  239. package/dist/internal/security/index.js +4 -4
  240. package/dist/judge-call-LAHMBJ57.cjs +23 -0
  241. package/dist/{judge-call-EGYRC2RE.cjs.map → judge-call-LAHMBJ57.cjs.map} +1 -1
  242. package/dist/judge-call-LVXABPS3.js +6 -0
  243. package/dist/{judge-call-DWHAJATE.js.map → judge-call-LVXABPS3.js.map} +1 -1
  244. package/dist/mcp-auth.cjs +15 -15
  245. package/dist/mcp-auth.js +5 -5
  246. package/dist/models.cjs +22 -22
  247. package/dist/models.js +7 -7
  248. package/dist/path-safety.cjs +11 -11
  249. package/dist/path-safety.js +4 -4
  250. package/dist/persistence.cjs +28 -28
  251. package/dist/persistence.js +9 -9
  252. package/dist/project.cjs +6 -6
  253. package/dist/project.js +4 -4
  254. package/dist/providers.cjs +9 -9
  255. package/dist/providers.js +7 -7
  256. package/dist/registry-75W33OGL.js +10 -0
  257. package/dist/{registry-VFP3WWQP.js.map → registry-75W33OGL.js.map} +1 -1
  258. package/dist/registry-V7BDQ6QB.cjs +47 -0
  259. package/dist/{registry-VFKX7WOP.cjs.map → registry-V7BDQ6QB.cjs.map} +1 -1
  260. package/dist/retry.cjs +5 -5
  261. package/dist/retry.js +4 -4
  262. package/dist/sandbox/index.cjs +7 -7
  263. package/dist/sandbox/index.js +3 -3
  264. package/dist/server/errors-envelope.cjs +15 -15
  265. package/dist/server/errors-envelope.js +4 -4
  266. package/dist/session-transcript-6WNITKRE.cjs +63 -0
  267. package/dist/{session-transcript-HF5GEU5M.cjs.map → session-transcript-6WNITKRE.cjs.map} +1 -1
  268. package/dist/session-transcript-XAEKW6P7.js +6 -0
  269. package/dist/{session-transcript-P462ZRHX.js.map → session-transcript-XAEKW6P7.js.map} +1 -1
  270. package/dist/skills.cjs +8 -8
  271. package/dist/skills.js +6 -6
  272. package/dist/stream-object-UF4QRQRU.js +8 -0
  273. package/dist/{stream-object-L57K4OFS.js.map → stream-object-UF4QRQRU.js.map} +1 -1
  274. package/dist/stream-object-ZJTQNKY3.cjs +21 -0
  275. package/dist/{stream-object-BUCF5PHO.cjs.map → stream-object-ZJTQNKY3.cjs.map} +1 -1
  276. package/dist/subagents-loader-CRT5LLL3.js +8 -0
  277. package/dist/{subagents-loader-6ATCDEKN.js.map → subagents-loader-CRT5LLL3.js.map} +1 -1
  278. package/dist/subagents-loader-YEUFFPAL.cjs +17 -0
  279. package/dist/{subagents-loader-X5QKODCL.cjs.map → subagents-loader-YEUFFPAL.cjs.map} +1 -1
  280. package/dist/subagents-loader.cjs +7 -7
  281. package/dist/subagents-loader.js +5 -5
  282. package/dist/subscription/index.cjs +4 -4
  283. package/dist/subscription/index.js +3 -3
  284. package/dist/task-store.cjs +8 -8
  285. package/dist/task-store.js +5 -5
  286. package/dist/workflow.cjs +28 -28
  287. package/dist/workflow.js +7 -7
  288. package/package.json +1 -1
  289. package/dist/agent-536OOESZ.js +0 -57
  290. package/dist/agent-5KYMG63I.cjs +0 -66
  291. package/dist/agent-session-store-G2BMUZQV.js +0 -7
  292. package/dist/agent-session-store-WAKLOKWK.cjs +0 -24
  293. package/dist/chunk-6HTXPPHK.cjs +0 -18
  294. package/dist/chunk-CHKH5452.js.map +0 -1
  295. package/dist/chunk-NLXOGBRJ.cjs.map +0 -1
  296. package/dist/chunk-NUKRL3I6.cjs.map +0 -1
  297. package/dist/chunk-T7O6K6PX.js.map +0 -1
  298. package/dist/compact-session-GJXJD73F.cjs +0 -59
  299. package/dist/compact-session-TSMQOIHO.js +0 -22
  300. package/dist/context-LCKNH2XI.cjs +0 -24
  301. package/dist/context-MZSKGKYR.js +0 -7
  302. package/dist/fs-session-store-4BHGIWRE.js +0 -11
  303. package/dist/fs-session-store-XZ7ZTB3A.cjs +0 -20
  304. package/dist/generate-object-N5MDZUJI.js +0 -8
  305. package/dist/generate-object-PGSP5U7N.cjs +0 -21
  306. package/dist/index-manager-6TEEIWM7.cjs +0 -26
  307. package/dist/index-manager-ACEQG3IJ.js +0 -17
  308. package/dist/judge-call-DWHAJATE.js +0 -6
  309. package/dist/judge-call-EGYRC2RE.cjs +0 -23
  310. package/dist/registry-VFKX7WOP.cjs +0 -47
  311. package/dist/registry-VFP3WWQP.js +0 -10
  312. package/dist/session-transcript-HF5GEU5M.cjs +0 -63
  313. package/dist/session-transcript-P462ZRHX.js +0 -6
  314. package/dist/stream-object-BUCF5PHO.cjs +0 -21
  315. package/dist/stream-object-L57K4OFS.js +0 -8
  316. package/dist/subagents-loader-6ATCDEKN.js +0 -8
  317. package/dist/subagents-loader-X5QKODCL.cjs +0 -17
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":[],"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,GAAW,QAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,C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OAAO,OAAO,CAAA;AACzB;AAOO,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-YEXA3PGR.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 oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\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 forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`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 // risky. Tracked in 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\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\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
+ {"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":[],"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,GAAW,QAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,QAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAO,QAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,OAAO,MAAM,CAAA;AACtB,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AACF;AAeA,SAAS,kBAAkB,OAAA,EAAuB;AAChD,EAAA,MAAM,MAAA,GAAS,cAAc,EAAA,EAAI,OAAO,EAAE,KAAA,CAAM,CAAA,GAAI,OAAA,CAAQ,MAAA,GAAS,CAAC,CAAA;AACtE,EAAA,KAAA,MAAW,CAAA,I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a,GAAA,CAAI,GAAG,CAAA,EAAG;AAC3B,EAAA,YAAA,CAAa,IAAI,GAAG,CAAA;AAEpB,EAAA,MAAM,SAAA,GAAY,MAAM,mBAAA,CAAoB,GAAA,CAAI,OAAO,OAAO,CAAA;AAC9D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAM5B,EAAA,QAAA,CAAS,GAAA,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;AAkBO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,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-4FFBAUFS.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 oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\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 forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`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 // risky. Tracked in 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\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
3
+ var chunk4ZHTIJNE_cjs = require('./chunk-4ZHTIJNE.cjs');
4
4
 
5
5
  // src/internal/runtime/retry/with-retry.ts
6
6
  function defaultSleep(ms, signal) {
@@ -23,14 +23,14 @@ function defaultSleep(ms, signal) {
23
23
  function resolveRetryOptions(options) {
24
24
  const retries = options?.retries ?? 3;
25
25
  if (!Number.isInteger(retries) || retries < 0) {
26
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
26
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
27
27
  `withRetry: retries must be a non-negative integer, got ${retries}`,
28
28
  { code: "invalid_retry_config" }
29
29
  );
30
30
  }
31
31
  return {
32
32
  retries,
33
- isRetryable: options?.isRetryable ?? chunkK3FW2XZD_cjs.isTransientError,
33
+ isRetryable: options?.isRetryable ?? chunk4ZHTIJNE_cjs.isTransientError,
34
34
  initialDelayMs: options?.initialDelayMs ?? 100,
35
35
  maxDelayMs: options?.maxDelayMs ?? 3e4,
36
36
  backoffMultiplier: options?.backoffMultiplier ?? 2,
@@ -67,5 +67,5 @@ var Retry = class {
67
67
  };
68
68
 
69
69
  exports.Retry = Retry;
70
- //# sourceMappingURL=chunk-HY57ULY2.cjs.map
71
- //# sourceMappingURL=chunk-HY57ULY2.cjs.map
70
+ //# sourceMappingURL=chunk-4PYZ5AX3.cjs.map
71
+ //# sourceMappingURL=chunk-4PYZ5AX3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/retry/with-retry.ts","../src/retry.ts"],"names":["ConfigurationError","isTransientError"],"mappings":";;;;;AAkCA,SAAS,YAAA,CAAa,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC5C,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,MAAA,CAAO,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AACvF,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,CAAO,MAA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AAA,MAAM,GAAA,GAAM,oBAAoB,OAAO,CAAA;AACvC,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,WAAS;AACP,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,OAAA,IAAW,IAAI,OAAA,IAAW,CAAC,IAAI,WAAA,CAAY,GAAG,GAAG,MAAM,GAAA;AAC3D,MAAA,MAAM,IAAI,KAAA,CAAM,SAAA,CAAU,KAAK,OAAO,CAAA,EAAG,IAAI,MAAM,CAAA;AACnD,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF;AACF;;;AC3FO,IAAM,QAAN,MAAY;AAAA,EACT,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,MAAA,CAAU,EAAA,EAAsB,OAAA,EAAoC;AACzE,IAAA,OAAO,SAAA,CAAU,IAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-HY57ULY2.cjs","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/runtime/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — `Retry.create` replaces `withRetry` (ADR 0015 / ADR-P2). NOTE: `withRetry` is an\n * EXECUTOR, not a constructor — `Retry.create(fn, opts)` RUNS `fn` with retry and resolves to\n * its result (`Promise<T>`), not a `Retry` instance. The `.create` name is the uniformity\n * mandate; the executor semantics are the documented, accepted awkwardness. @public\n */\nexport class Retry {\n private constructor() {}\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/retry/with-retry.ts","../src/retry.ts"],"names":["ConfigurationError","isTransientError"],"mappings":";;;;;AAkCA,SAAS,YAAA,CAAa,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC5C,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA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YAAA;AAAA,IACzB,QAAQ,OAAA,EAAS;AAAA,GACnB;AACF;AAGA,SAAS,SAAA,CAAU,KAAoB,OAAA,EAAyB;AAC9D,EAAA,MAAM,OAAA,GAAU,KAAK,GAAA,CAAI,GAAA,CAAI,YAAY,GAAA,CAAI,cAAA,GAAiB,GAAA,CAAI,iBAAA,IAAqB,OAAO,CAAA;AAC9F,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,KAAQ,OAAO,CAAA;AACvC;AAWA,eAAsB,SAAA,CAAa,IAAsB,OAAA,EAAoC;AAC3F,EAAA,MAAM,GAAA,GAAM,oBAAoB,OAAO,CAAA;AACvC,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,WAAS;AACP,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,OAAA,IAAW,IAAI,OAAA,IAAW,CAAC,IAAI,WAAA,CAAY,GAAG,GAAG,MAAM,GAAA;AAC3D,MAAA,MAAM,IAAI,KAAA,CAAM,SAAA,CAAU,KAAK,OAAO,CAAA,EAAG,IAAI,MAAM,CAAA;AACnD,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF;AACF;;;AC3FO,IAAM,QAAN,MAAY;AAAA,EACT,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,MAAA,CAAU,EAAA,EAAsB,OAAA,EAAoC;AACzE,IAAA,OAAO,SAAA,CAAU,IAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-4PYZ5AX3.cjs","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/runtime/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — `Retry.create` replaces `withRetry` (ADR 0015 / ADR-P2). NOTE: `withRetry` is an\n * EXECUTOR, not a constructor — `Retry.create(fn, opts)` RUNS `fn` with retry and resolves to\n * its result (`Promise<T>`), not a `Retry` instance. The `.create` name is the uniformity\n * mandate; the executor semantics are the documented, accepted awkwardness. @public\n */\nexport class Retry {\n private constructor() {}\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ConfigurationError } from './chunk-IDCKSLYH.js';
1
+ import { ConfigurationError } from './chunk-ZZMZWBR6.js';
2
2
 
3
3
  // src/internal/runtime/concurrency/async-semaphore.ts
4
4
  function createSemaphore(permits) {
@@ -39,5 +39,5 @@ function createSemaphore(permits) {
39
39
  }
40
40
 
41
41
  export { createSemaphore };
42
- //# sourceMappingURL=chunk-OC4NTGMN.js.map
43
- //# sourceMappingURL=chunk-OC4NTGMN.js.map
42
+ //# sourceMappingURL=chunk-4QZSA2HJ.js.map
43
+ //# sourceMappingURL=chunk-4QZSA2HJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/concurrency/async-semaphore.ts"],"names":[],"mappings":";;;AA2BO,SAAS,gBAAgB,OAAA,EAAiC;AAC/D,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,IAAK,UAAU,CAAA,EAAG;AAC7C,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,4DAA4D,OAAO,CAAA,CAAA;AAAA,MACnE,EAAE,MAAM,qBAAA;AAAsB,KAChC;AAAA,EACF;AACA,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,MAAM,QAA2B,EAAC;AAElC,EAAA,SAAS,QAAA,GAAiB;AACxB,IAAA,IAAI,MAAA,GAAS,OAAA,IAAW,KAAA,CAAM,MAAA,GAAS,CAAA,EAAG;AACxC,MAAA,MAAM,OAAA,GAAU,MAAM,KAAA,EAAM;AAC5B,MAAA,IAAI,YAAY,MAAA,EAAW;AACzB,QAAA,MAAA,IAAU,CAAA;AACV,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,UAAU,MAAM,MAAA;AAAA,IAChB,OAAA,EAAS,MAAM,KAAA,CAAM,MAAA,GAAS,MAAA;AAAA,IAC9B,MAAM,OAAA,GAAU;AACd,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,QAAA,QAAA,EAAS;AAAA,MACX,CAAC,CAAA;AACD,MAAA,IAAI,QAAA,GAAW,KAAA;AACf,MAAA,OAAO,MAAM;AACX,QAAA,IAAI,QAAA,EAAU;AACd,QAAA,QAAA,GAAW,IAAA;AACX,QAAA,MAAA,IAAU,CAAA;AACV,QAAA,QAAA,EAAS;AAAA,MACX,CAAA;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-OC4NTGMN.js","sourcesContent":["/**\n * Async-aware counting semaphore (ADR D135).\n *\n * N-permit gate for cooperative concurrency control inside a single\n * Node process. Used by `Agent.batch` to bound parallel agent count\n * without pulling in `p-limit` or `p-queue` (~30 LoC in-house).\n *\n * Contract: `acquire()` returns a release function. Caller MUST call\n * release exactly once when done — typically in a `finally` block.\n * Release is idempotent (multiple calls are no-ops after the first)\n * for defense against caller bugs, but leaking the release function\n * permanently consumes one permit (EC-G — caller responsibility).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\nexport interface AsyncSemaphore {\n /** Acquire a permit. Returns the release function (call once). */\n acquire(): Promise<() => void>;\n /** Permits currently held in flight. */\n inFlight(): number;\n /** Total: in-flight + queued waiters. */\n pending(): number;\n}\n\nexport function createSemaphore(permits: number): AsyncSemaphore {\n if (!Number.isInteger(permits) || permits < 1) {\n throw new ConfigurationError(\n `async-semaphore: permits must be a positive integer, got ${permits}`,\n { code: \"invalid_concurrency\" },\n );\n }\n let active = 0;\n const queue: Array<() => void> = [];\n\n function tryGrant(): void {\n if (active < permits && queue.length > 0) {\n const resolve = queue.shift();\n if (resolve !== undefined) {\n active += 1;\n resolve();\n }\n }\n }\n\n return {\n inFlight: () => active,\n pending: () => queue.length + active,\n async acquire() {\n await new Promise<void>((resolve) => {\n queue.push(resolve);\n tryGrant();\n });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n active -= 1;\n tryGrant();\n };\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/concurrency/async-semaphore.ts"],"names":[],"mappings":";;;AA2BO,SAAS,gBAAgB,OAAA,EAAiC;AAC/D,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,IAAK,UAAU,CAAA,EAAG;AAC7C,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,4DAA4D,OAAO,CAAA,CAAA;AAAA,MACnE,EAAE,MAAM,qBAAA;AAAsB,KAChC;AAAA,EACF;AACA,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,MAAM,QAA2B,EAAC;AAElC,EAAA,SAAS,QAAA,GAAiB;AACxB,IAAA,IAAI,MAAA,GAAS,OAAA,IAAW,KAAA,CAAM,MAAA,GAAS,CAAA,EAAG;AACxC,MAAA,MAAM,OAAA,GAAU,MAAM,KAAA,EAAM;AAC5B,MAAA,IAAI,YAAY,MAAA,EAAW;AACzB,QAAA,MAAA,IAAU,CAAA;AACV,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,UAAU,MAAM,MAAA;AAAA,IAChB,OAAA,EAAS,MAAM,KAAA,CAAM,MAAA,GAAS,MAAA;AAAA,IAC9B,MAAM,OAAA,GAAU;AACd,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,QAAA,QAAA,EAAS;AAAA,MACX,CAAC,CAAA;AACD,MAAA,IAAI,QAAA,GAAW,KAAA;AACf,MAAA,OAAO,MAAM;AACX,QAAA,IAAI,QAAA,EAAU;AACd,QAAA,QAAA,GAAW,IAAA;AACX,QAAA,MAAA,IAAU,CAAA;AACV,QAAA,QAAA,EAAS;AAAA,MACX,CAAA;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-4QZSA2HJ.js","sourcesContent":["/**\n * Async-aware counting semaphore (ADR D135).\n *\n * N-permit gate for cooperative concurrency control inside a single\n * Node process. Used by `Agent.batch` to bound parallel agent count\n * without pulling in `p-limit` or `p-queue` (~30 LoC in-house).\n *\n * Contract: `acquire()` returns a release function. Caller MUST call\n * release exactly once when done — typically in a `finally` block.\n * Release is idempotent (multiple calls are no-ops after the first)\n * for defense against caller bugs, but leaking the release function\n * permanently consumes one permit (EC-G — caller responsibility).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\nexport interface AsyncSemaphore {\n /** Acquire a permit. Returns the release function (call once). */\n acquire(): Promise<() => void>;\n /** Permits currently held in flight. */\n inFlight(): number;\n /** Total: in-flight + queued waiters. */\n pending(): number;\n}\n\nexport function createSemaphore(permits: number): AsyncSemaphore {\n if (!Number.isInteger(permits) || permits < 1) {\n throw new ConfigurationError(\n `async-semaphore: permits must be a positive integer, got ${permits}`,\n { code: \"invalid_concurrency\" },\n );\n }\n let active = 0;\n const queue: Array<() => void> = [];\n\n function tryGrant(): void {\n if (active < permits && queue.length > 0) {\n const resolve = queue.shift();\n if (resolve !== undefined) {\n active += 1;\n resolve();\n }\n }\n }\n\n return {\n inFlight: () => active,\n pending: () => queue.length + active,\n async acquire() {\n await new Promise<void>((resolve) => {\n queue.push(resolve);\n tryGrant();\n });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n active -= 1;\n tryGrant();\n };\n },\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkJTB5Q42C_cjs = require('./chunk-JTB5Q42C.cjs');
3
+ var chunkXL7Q7HB2_cjs = require('./chunk-XL7Q7HB2.cjs');
4
4
 
5
5
  // src/internal/runtime/retry/default-retriable.ts
6
6
  function defaultRetriableForCode(code) {
@@ -148,11 +148,11 @@ var AgentRunError = class extends TheokitAgentError {
148
148
  get providerError() {
149
149
  const raw = this.metadata?.raw;
150
150
  if (raw === void 0) return void 0;
151
- if (typeof raw === "string") return chunkJTB5Q42C_cjs.redactSecrets(raw);
151
+ if (typeof raw === "string") return chunkXL7Q7HB2_cjs.redactSecrets(raw);
152
152
  try {
153
- return chunkJTB5Q42C_cjs.redactSecrets(JSON.stringify(raw));
153
+ return chunkXL7Q7HB2_cjs.redactSecrets(JSON.stringify(raw));
154
154
  } catch {
155
- return chunkJTB5Q42C_cjs.redactSecrets(String(raw));
155
+ return chunkXL7Q7HB2_cjs.redactSecrets(String(raw));
156
156
  }
157
157
  }
158
158
  /**
@@ -180,14 +180,14 @@ function addOptionalFields(json, err) {
180
180
  if (err.provider !== void 0) json.provider = err.provider;
181
181
  if (err.requestId !== void 0) json.requestId = err.requestId;
182
182
  if (err.conversationId !== void 0) json.conversationId = err.conversationId;
183
- if (err.raw !== void 0) json.raw = chunkJTB5Q42C_cjs.redactSecrets(err.raw);
183
+ if (err.raw !== void 0) json.raw = chunkXL7Q7HB2_cjs.redactSecrets(err.raw);
184
184
  }
185
185
  function sanitizeMetadata(meta) {
186
186
  if (meta === void 0) return void 0;
187
187
  const { raw, ...rest } = meta;
188
- const debugRaw = chunkJTB5Q42C_cjs.readEnv("THEOKIT_DEBUG_RAW_ERRORS") === "1";
188
+ const debugRaw = chunkXL7Q7HB2_cjs.readEnv("THEOKIT_DEBUG_RAW_ERRORS") === "1";
189
189
  if (debugRaw && raw !== void 0) {
190
- const redactedRaw = typeof raw === "string" ? chunkJTB5Q42C_cjs.redactSecrets(raw) : chunkJTB5Q42C_cjs.redactSecrets(safeStringify(raw));
190
+ const redactedRaw = typeof raw === "string" ? chunkXL7Q7HB2_cjs.redactSecrets(raw) : chunkXL7Q7HB2_cjs.redactSecrets(safeStringify(raw));
191
191
  return { ...rest, raw: redactedRaw };
192
192
  }
193
193
  return rest;
@@ -349,5 +349,5 @@ exports.UnsupportedRunOperationError = UnsupportedRunOperationError;
349
349
  exports.UnsupportedTaskOperationError = UnsupportedTaskOperationError;
350
350
  exports.coerceToKnownAgentRunErrorCode = coerceToKnownAgentRunErrorCode;
351
351
  exports.isTransientError = isTransientError;
352
- //# sourceMappingURL=chunk-K3FW2XZD.cjs.map
353
- //# sourceMappingURL=chunk-K3FW2XZD.cjs.map
352
+ //# sourceMappingURL=chunk-4ZHTIJNE.cjs.map
353
+ //# sourceMappingURL=chunk-4ZHTIJNE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/retry/default-retriable.ts","../src/errors.ts"],"names":["redactSecrets","readEnv"],"mappings":";;;;;AAUO,SAAS,wBAAwB,IAAA,EAAuB;AAC7D,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,YAAA;AAAA,IACL,KAAK,SAAA;AAAA,IACL,KAAK,cAAA;AAAA,IACL,KAAK,SAAA;AAAA,IACL,KAAK,sBAAA;AACH,MAAA,OAAO,IAAA;AAAA,IACT;AACE,MAAA,OAAO,KAAA;AAAA;AAEb;;;AC8CA,IAAM,2BAAA,uBAAkC,GAAA,CAAY;AAAA,EAClD,YAAA;AAAA,EACA,aAAA;AAAA,EACA,iBAAA;AAAA,EACA,SAAA;AAAA,EACA,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,oBAAA;AAAA,EACA,SAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAiBM,SAAS,+BAA+B,IAAA,EAAkD;AAC/F,EAAA,IAAI,IAAA,KAAS,MAAA,IAAa,2BAAA,CAA4B,GAAA,CAAI,IAAI,CAAA,EAAG;AAC/D,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO,SAAA;AACT;AAmCO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAe,mBAAA;AAAA,EACxB,WAAA;AAAA,EACA,IAA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S,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AACF;AAUO,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA,EACxB,OAAA;AAAA,EAET,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,CAAA,OAAA,EAAU,OAAO,CAAA,8DAAA,CAAA,EAAkE;AAAA,MACvF,WAAA,EAAa,KAAA;AAAA,MACb,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF;AAgBO,IAAM,+BAAA,GAAN,cAA8C,iBAAA,CAAkB;AAAA,EACnD,IAAA,GAAe,iCAAA;AAAA,EACxB,SAAA;AAAA,EAET,WAAA,CAAY,SAAA,EAAmB,OAAA,GAA+B,EAAC,EAAG;AAChE,IAAA,KAAA;AAAA,MACE,qBAAqB,SAAS,CAAA,4DAAA,CAAA;AAAA,MAC9B;AAAA,QACE,GAAG,OAAA;AAAA,QACH,WAAA,EAAa,KAAA;AAAA,QACb,IAAA,EAAM;AAAA;AACR,KACF;AACA,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AACF","file":"chunk-K3FW2XZD.cjs","sourcesContent":["/**\n * Default retryability verdict for an `AgentRunError` code.\n *\n * Extracted from `errors.ts` (G8 LoC budget — SRP). The parameter is typed\n * `string` (not the `AgentRunErrorCode` union) deliberately: this is a leaf\n * with NO import back into `errors.ts`, so it cannot form an import cycle. The\n * `default` branch makes the behavior identical to the typed switch.\n *\n * @internal\n */\nexport function defaultRetriableForCode(code: string): boolean {\n switch (code) {\n case \"rate_limit\":\n case \"timeout\":\n case \"server_error\":\n case \"network\":\n case \"provider_unreachable\":\n return true;\n default:\n return false;\n }\n}\n","import { readEnv } from \"./internal/env.js\";\nimport { defaultRetriableForCode } from \"./internal/runtime/retry/default-retriable.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\nimport type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"quota_exceeded\"\n | \"unknown\";\n\n/**\n * T1.1 — closed literal union for `AgentRunError.code`. The previous\n * `(string & {})` escape hatch let arbitrary strings slip into the type\n * surface and defeated exhaustive `switch (code)` discrimination. This is\n * the canonical closed form. `AgentRunErrorCode` is re-aliased below for\n * source-level back-compat.\n *\n * Superset of {@link ErrorCode}, extended with codes that do NOT originate from a\n * provider HTTP response (Production-Readiness #3, ADR D311):\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * Adding a new code: append the literal here AND audit every `switch (err.code)`\n * in callers. Type-checker enforces the audit via the `default: assertNever(code)`\n * convention.\n *\n * @public\n */\nexport type KnownAgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\";\n\n/**\n * Back-compat alias of {@link KnownAgentRunErrorCode}. Pre-T1.1 callers that\n * imported `AgentRunErrorCode` keep working; new code SHOULD prefer\n * `KnownAgentRunErrorCode` to make the closed-union intent explicit.\n *\n * @public\n */\nexport type AgentRunErrorCode = KnownAgentRunErrorCode;\n\n/** Snapshot of every known code at runtime — used by the boundary coercer. */\nconst KNOWN_AGENT_RUN_ERROR_CODES = new Set<string>([\n \"rate_limit\",\n \"auth_failed\",\n \"invalid_request\",\n \"timeout\",\n \"server_error\",\n \"context_too_long\",\n \"content_filtered\",\n \"model_unavailable\",\n \"network\",\n \"unknown\",\n \"quota_exceeded\",\n \"tool_runtime_error\",\n \"aborted\",\n \"invalid_model\",\n \"safety_blocked\",\n \"provider_unreachable\",\n]);\n\n/**\n * T1.1 boundary helper — coerce an arbitrary string (typically arriving from\n * a downstream `RunErrorDetail.code` or a deserialized cloud response) into a\n * `KnownAgentRunErrorCode`.\n *\n * A string that is not one of the known codes collapses to `\"unknown\"`, and so\n * does `undefined` — the parameter is optional precisely so a caller can forward\n * an absent `code` without a guard. The closed type contract therefore holds at\n * the boundary without forcing every caller to switch.\n *\n * This is the migration path the 4.x release notes point at for code that used\n * to rely on `AgentRunErrorCode` being an open string union.\n *\n * @public\n */\nexport function coerceToKnownAgentRunErrorCode(code: string | undefined): KnownAgentRunErrorCode {\n if (code !== undefined && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {\n return code as KnownAgentRunErrorCode;\n }\n return \"unknown\";\n}\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313 + T1.5: alias for `metadata.raw`. Provider response body for\n * debugging. T1.5 wraps the value in `redactSecrets` at the getter\n * boundary so secret-shaped substrings (`sk-...`, Bearer JWTs, etc.) are\n * stripped before reaching the caller. Available but NEVER serialized\n * into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n const raw = this.metadata?.raw;\n if (raw === undefined) return undefined;\n if (typeof raw === \"string\") return redactSecrets(raw);\n // Non-string raw (object/buffer) — stringify then redact.\n try {\n return redactSecrets(JSON.stringify(raw));\n } catch {\n return redactSecrets(String(raw));\n }\n }\n\n /**\n * T1.5 — sanitized JSON form. `metadata.raw` is OMITTED by default; opt\n * in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (redacted) raw\n * payload for diagnostics. Every other field stays accessible.\n *\n * The single env-var gate is read each call so operators can toggle at\n * runtime without restarting the process.\n */\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {\n name: this.name,\n message: this.message,\n isRetryable: this.isRetryable,\n };\n addOptionalFields(json, this);\n const safeMeta = sanitizeMetadata(this.metadata);\n if (safeMeta !== undefined) json.metadata = safeMeta;\n return json;\n }\n}\n\nfunction addOptionalFields(json: Record<string, unknown>, err: AgentRunError): void {\n if (err.code !== undefined) json.code = err.code;\n if (err.provider !== undefined) json.provider = err.provider;\n if (err.requestId !== undefined) json.requestId = err.requestId;\n if (err.conversationId !== undefined) json.conversationId = err.conversationId;\n if (err.raw !== undefined) json.raw = redactSecrets(err.raw);\n}\n\nfunction sanitizeMetadata(meta: ErrorMetadata | undefined): ErrorMetadata | undefined {\n if (meta === undefined) return undefined;\n const { raw, ...rest } = meta;\n const debugRaw = readEnv(\"THEOKIT_DEBUG_RAW_ERRORS\") === \"1\";\n if (debugRaw && raw !== undefined) {\n const redactedRaw =\n typeof raw === \"string\" ? redactSecrets(raw) : redactSecrets(safeStringify(raw));\n return { ...rest, raw: redactedRaw } as ErrorMetadata;\n }\n return rest as ErrorMetadata;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Is this error transient (worth retrying)?\n *\n * Returns the SDK's own retryability verdict: every {@link TheokitAgentError}\n * subclass computes `isRetryable` at construction (rate-limit / network /\n * credential-pool-exhausted are retryable; auth / configuration / unsupported\n * are not), so this predicate is a single source of truth rather than a\n * re-derivation. Non-SDK errors return `false` conservatively — wrap a foreign\n * error in the appropriate SDK error first if you want it considered transient.\n * It never inspects `err.message`.\n *\n * @example\n * try {\n * await agent.send(message, { throwOnError: true });\n * } catch (err) {\n * if (isTransientError(err)) return retryWithBackoff();\n * throw err;\n * }\n *\n * @public\n */\nexport function isTransientError(err: unknown): boolean {\n return err instanceof TheokitAgentError && err.isRetryable === true;\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. The caller catches a\n * typed error to retry after the window resets, or surfaces it to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * T1.6 — Thrown when a consumer calls `agent.send()` or any method\n * on an agent that has already been `dispose()`d. Pre-T1.6 this was\n * a generic `new Error(\"Agent has been disposed\")` — consumers\n * couldn't catch it without string-matching the message.\n *\n * @public\n */\nexport class AgentDisposedError extends TheokitAgentError {\n override readonly name: string = \"AgentDisposedError\";\n readonly agentId: string;\n\n constructor(agentId: string) {\n super(`Agent \"${agentId}\" has been disposed. Create a new agent or use Agent.resume().`, {\n isRetryable: false,\n code: \"agent_disposed\",\n });\n this.agentId = agentId;\n }\n}\n\n/**\n * Thrown when a budget operation is requested on a `CloudAgent` (D388). The cloud budget surface\n * waits for Theo PaaS GA, so the operation is not merely failing — it does not exist yet.\n *\n * Not retryable: `isRetryable` is `false`, and retrying cannot change the outcome until the\n * feature ships. Catch it by `instanceof`, or by `code === \"budget_op_unsupported\"` when the\n * error has crossed a serialization boundary that dropped the prototype. `operation` carries the\n * name that was refused and is interpolated into the message.\n *\n * The local agent does not raise this — the same call against a local agent runs the budget path\n * normally.\n *\n * @public\n */\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/retry/default-retriable.ts","../src/errors.ts"],"names":["redactSecrets","readEnv"],"mappings":";;;;;AAUO,SAAS,wBAAwB,IAAA,EAAuB;AAC7D,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,YAAA;AAAA,IACL,KAAK,SAAA;AAAA,IACL,KAAK,cAAA;AAAA,IACL,KAAK,SAAA;AAAA,IACL,KAAK,sBAAA;AACH,MAAA,OAAO,IAAA;AAAA,IACT;AACE,MAAA,OAAO,KAAA;AAAA;AAEb;;;AC8CA,IAAM,2BAAA,uBAAkC,GAAA,CAAY;AAAA,EAClD,YAAA;AAAA,EACA,aAAA;AAAA,EACA,iBAAA;AAAA,EACA,SAAA;AAAA,EACA,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,oBAAA;AAAA,EACA,SAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAiBM,SAAS,+BAA+B,IAAA,EAAkD;AAC/F,EAAA,IAAI,IAAA,KAAS,MAAA,IAAa,2BAAA,CAA4B,GAAA,CAAI,IAAI,CAAA,EAAG;AAC/D,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO,SAAA;AACT;AAmCO,IAAM,iBAAA,GAAN,cA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,KACF;AACA,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AACF;AAUO,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA,EACxB,OAAA;AAAA,EAET,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,CAAA,OAAA,EAAU,OAAO,CAAA,8DAAA,CAAA,EAAkE;AAAA,MACvF,WAAA,EAAa,KAAA;AAAA,MACb,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF;AAgBO,IAAM,+BAAA,GAAN,cAA8C,iBAAA,CAAkB;AAAA,EACnD,IAAA,GAAe,iCAAA;AAAA,EACxB,SAAA;AAAA,EAET,WAAA,CAAY,SAAA,EAAmB,OAAA,GAA+B,EAAC,EAAG;AAChE,IAAA,KAAA;AAAA,MACE,qBAAqB,SAAS,CAAA,4DAAA,CAAA;AAAA,MAC9B;AAAA,QACE,GAAG,OAAA;AAAA,QACH,WAAA,EAAa,KAAA;AAAA,QACb,IAAA,EAAM;AAAA;AACR,KACF;AACA,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AACF","file":"chunk-4ZHTIJNE.cjs","sourcesContent":["/**\n * Default retryability verdict for an `AgentRunError` code.\n *\n * Extracted from `errors.ts` (G8 LoC budget — SRP). The parameter is typed\n * `string` (not the `AgentRunErrorCode` union) deliberately: this is a leaf\n * with NO import back into `errors.ts`, so it cannot form an import cycle. The\n * `default` branch makes the behavior identical to the typed switch.\n *\n * @internal\n */\nexport function defaultRetriableForCode(code: string): boolean {\n switch (code) {\n case \"rate_limit\":\n case \"timeout\":\n case \"server_error\":\n case \"network\":\n case \"provider_unreachable\":\n return true;\n default:\n return false;\n }\n}\n","import { readEnv } from \"./internal/env.js\";\nimport { defaultRetriableForCode } from \"./internal/runtime/retry/default-retriable.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\nimport type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"quota_exceeded\"\n | \"unknown\";\n\n/**\n * T1.1 — closed literal union for `AgentRunError.code`. The previous\n * `(string & {})` escape hatch let arbitrary strings slip into the type\n * surface and defeated exhaustive `switch (code)` discrimination. This is\n * the canonical closed form. `AgentRunErrorCode` is re-aliased below for\n * source-level back-compat.\n *\n * Superset of {@link ErrorCode}, extended with codes that do NOT originate from a\n * provider HTTP response (Production-Readiness #3, ADR D311):\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * Adding a new code: append the literal here AND audit every `switch (err.code)`\n * in callers. Type-checker enforces the audit via the `default: assertNever(code)`\n * convention.\n *\n * @public\n */\nexport type KnownAgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\";\n\n/**\n * Back-compat alias of {@link KnownAgentRunErrorCode}. Pre-T1.1 callers that\n * imported `AgentRunErrorCode` keep working; new code SHOULD prefer\n * `KnownAgentRunErrorCode` to make the closed-union intent explicit.\n *\n * @public\n */\nexport type AgentRunErrorCode = KnownAgentRunErrorCode;\n\n/** Snapshot of every known code at runtime — used by the boundary coercer. */\nconst KNOWN_AGENT_RUN_ERROR_CODES = new Set<string>([\n \"rate_limit\",\n \"auth_failed\",\n \"invalid_request\",\n \"timeout\",\n \"server_error\",\n \"context_too_long\",\n \"content_filtered\",\n \"model_unavailable\",\n \"network\",\n \"unknown\",\n \"quota_exceeded\",\n \"tool_runtime_error\",\n \"aborted\",\n \"invalid_model\",\n \"safety_blocked\",\n \"provider_unreachable\",\n]);\n\n/**\n * T1.1 boundary helper — coerce an arbitrary string (typically arriving from\n * a downstream `RunErrorDetail.code` or a deserialized cloud response) into a\n * `KnownAgentRunErrorCode`.\n *\n * A string that is not one of the known codes collapses to `\"unknown\"`, and so\n * does `undefined` — the parameter is optional precisely so a caller can forward\n * an absent `code` without a guard. The closed type contract therefore holds at\n * the boundary without forcing every caller to switch.\n *\n * This is the migration path the 4.x release notes point at for code that used\n * to rely on `AgentRunErrorCode` being an open string union.\n *\n * @public\n */\nexport function coerceToKnownAgentRunErrorCode(code: string | undefined): KnownAgentRunErrorCode {\n if (code !== undefined && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {\n return code as KnownAgentRunErrorCode;\n }\n return \"unknown\";\n}\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313 + T1.5: alias for `metadata.raw`. Provider response body for\n * debugging. T1.5 wraps the value in `redactSecrets` at the getter\n * boundary so secret-shaped substrings (`sk-...`, Bearer JWTs, etc.) are\n * stripped before reaching the caller. Available but NEVER serialized\n * into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n const raw = this.metadata?.raw;\n if (raw === undefined) return undefined;\n if (typeof raw === \"string\") return redactSecrets(raw);\n // Non-string raw (object/buffer) — stringify then redact.\n try {\n return redactSecrets(JSON.stringify(raw));\n } catch {\n return redactSecrets(String(raw));\n }\n }\n\n /**\n * T1.5 — sanitized JSON form. `metadata.raw` is OMITTED by default; opt\n * in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (redacted) raw\n * payload for diagnostics. Every other field stays accessible.\n *\n * The single env-var gate is read each call so operators can toggle at\n * runtime without restarting the process.\n */\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {\n name: this.name,\n message: this.message,\n isRetryable: this.isRetryable,\n };\n addOptionalFields(json, this);\n const safeMeta = sanitizeMetadata(this.metadata);\n if (safeMeta !== undefined) json.metadata = safeMeta;\n return json;\n }\n}\n\nfunction addOptionalFields(json: Record<string, unknown>, err: AgentRunError): void {\n if (err.code !== undefined) json.code = err.code;\n if (err.provider !== undefined) json.provider = err.provider;\n if (err.requestId !== undefined) json.requestId = err.requestId;\n if (err.conversationId !== undefined) json.conversationId = err.conversationId;\n if (err.raw !== undefined) json.raw = redactSecrets(err.raw);\n}\n\nfunction sanitizeMetadata(meta: ErrorMetadata | undefined): ErrorMetadata | undefined {\n if (meta === undefined) return undefined;\n const { raw, ...rest } = meta;\n const debugRaw = readEnv(\"THEOKIT_DEBUG_RAW_ERRORS\") === \"1\";\n if (debugRaw && raw !== undefined) {\n const redactedRaw =\n typeof raw === \"string\" ? redactSecrets(raw) : redactSecrets(safeStringify(raw));\n return { ...rest, raw: redactedRaw } as ErrorMetadata;\n }\n return rest as ErrorMetadata;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Is this error transient (worth retrying)?\n *\n * Returns the SDK's own retryability verdict: every {@link TheokitAgentError}\n * subclass computes `isRetryable` at construction (rate-limit / network /\n * credential-pool-exhausted are retryable; auth / configuration / unsupported\n * are not), so this predicate is a single source of truth rather than a\n * re-derivation. Non-SDK errors return `false` conservatively — wrap a foreign\n * error in the appropriate SDK error first if you want it considered transient.\n * It never inspects `err.message`.\n *\n * @example\n * try {\n * await agent.send(message, { throwOnError: true });\n * } catch (err) {\n * if (isTransientError(err)) return retryWithBackoff();\n * throw err;\n * }\n *\n * @public\n */\nexport function isTransientError(err: unknown): boolean {\n return err instanceof TheokitAgentError && err.isRetryable === true;\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. The caller catches a\n * typed error to retry after the window resets, or surfaces it to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * T1.6 — Thrown when a consumer calls `agent.send()` or any method\n * on an agent that has already been `dispose()`d. Pre-T1.6 this was\n * a generic `new Error(\"Agent has been disposed\")` — consumers\n * couldn't catch it without string-matching the message.\n *\n * @public\n */\nexport class AgentDisposedError extends TheokitAgentError {\n override readonly name: string = \"AgentDisposedError\";\n readonly agentId: string;\n\n constructor(agentId: string) {\n super(`Agent \"${agentId}\" has been disposed. Create a new agent or use Agent.resume().`, {\n isRetryable: false,\n code: \"agent_disposed\",\n });\n this.agentId = agentId;\n }\n}\n\n/**\n * Thrown when a budget operation is requested on a `CloudAgent` (D388). The cloud budget surface\n * waits for Theo PaaS GA, so the operation is not merely failing — it does not exist yet.\n *\n * Not retryable: `isRetryable` is `false`, and retrying cannot change the outcome until the\n * feature ships. Catch it by `instanceof`, or by `code === \"budget_op_unsupported\"` when the\n * error has crossed a serialization boundary that dropped the prototype. `operation` carries the\n * name that was refused and is interpolated into the message.\n *\n * The local agent does not raise this — the same call against a local agent runs the budget path\n * normally.\n *\n * @public\n */\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkI6TGFUCO_cjs = require('./chunk-I6TGFUCO.cjs');
4
- var chunkJTB5Q42C_cjs = require('./chunk-JTB5Q42C.cjs');
3
+ var chunkUALX2J2Q_cjs = require('./chunk-UALX2J2Q.cjs');
4
+ var chunkXL7Q7HB2_cjs = require('./chunk-XL7Q7HB2.cjs');
5
5
  var crypto = require('crypto');
6
6
  var promises = require('fs/promises');
7
7
  var os = require('os');
@@ -13,12 +13,12 @@ function encodeProjectDir(cwd) {
13
13
  function safeSessionId(id) {
14
14
  return id.replace(/[^a-zA-Z0-9_-]/g, "-");
15
15
  }
16
- var red = (s) => chunkJTB5Q42C_cjs.redactSecrets(s);
16
+ var red = (s) => chunkXL7Q7HB2_cjs.redactSecrets(s);
17
17
  function redactValue(value) {
18
18
  try {
19
- return JSON.parse(chunkJTB5Q42C_cjs.redactSecrets(JSON.stringify(value ?? null)));
19
+ return JSON.parse(chunkXL7Q7HB2_cjs.redactSecrets(JSON.stringify(value ?? null)));
20
20
  } catch {
21
- return chunkJTB5Q42C_cjs.redactSecrets(String(value));
21
+ return chunkXL7Q7HB2_cjs.redactSecrets(String(value));
22
22
  }
23
23
  }
24
24
  var SessionTranscript = class _SessionTranscript {
@@ -240,7 +240,7 @@ function legacyTranscriptPath(baseDir, cwd, sessionId) {
240
240
  async function writeTranscript(path$1, records) {
241
241
  await promises.mkdir(path.dirname(path$1), { recursive: true });
242
242
  const body = records.map((r) => JSON.stringify(r)).join("\n");
243
- await chunkI6TGFUCO_cjs.replaceFileAtomic(path$1, records.length > 0 ? `${body}
243
+ await chunkUALX2J2Q_cjs.replaceFileAtomic(path$1, records.length > 0 ? `${body}
244
244
  ` : "");
245
245
  return path$1;
246
246
  }
@@ -278,5 +278,5 @@ exports.sessionUuidFor = sessionUuidFor;
278
278
  exports.transcriptPath = transcriptPath;
279
279
  exports.transcriptRoot = transcriptRoot;
280
280
  exports.writeTranscript = writeTranscript;
281
- //# sourceMappingURL=chunk-BUIK7GUA.cjs.map
282
- //# sourceMappingURL=chunk-BUIK7GUA.cjs.map
281
+ //# sourceMappingURL=chunk-5HEG4CQH.cjs.map
282
+ //# sourceMappingURL=chunk-5HEG4CQH.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-transcript.ts"],"names":["redactSecrets","randomUUID","join","homedir","createHash","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;AAChD,EAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAC1C;AAEA,IAAM,GAAA,GAAM,CAAC,CAAA,KAAsBA,+BAAA,CAAc,CAAC,CAAA;AAGlD,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAMA,+BAAA,CAAc,IAAA,CAAK,UAAU,KAAA,IAAS,IAAI,CAAC,CAAC,CAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAOA,+BAAA,CAAc,MAAA,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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-BUIK7GUA.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 * reference: knowledge-base/references/claude-code-log/claude_code_log/dag.py + models.py\n */\nimport { createHash, 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 * Root of the transcript state.\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/**\n * The fixed namespace for deriving a session UUID from an agent id (RFC 9562 § 5.8, version 8).\n *\n * A constant, because the derivation must be STABLE FOREVER: it is what lets the SDK find the\n * session it wrote last week without storing an id-to-filename map anywhere. Changing this value\n * orphans every transcript ever written.\n */\nconst SESSION_NAMESPACE = Buffer.from(\"b7a1f0c94e3d4a1b8f26d05c3a91e7d2\", \"hex\");\n\nconst UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Is this id already a canonical UUID, and therefore usable as a filename verbatim? */\nexport function isSessionUuid(id: string): boolean {\n return UUID_SHAPE.test(id);\n}\n\n/**\n * The transcript filename for an agent id — always a UUID.\n *\n * #400: the Claude Code CLI resumes a transcript ONLY when its basename is a UUID. Measured against\n * CLI 2.1.236: `<uuid>.jsonl` resumes; `agent-<uuid>.jsonl` and `billing-bot.jsonl` are both ignored,\n * with no error — the session simply is not offered. So a session written under a human-readable\n * agent id was invisible to `claude --continue`, which is the interoperability this project claims\n * as its difference from a proprietary session store.\n *\n * An id that is ALREADY a UUID passes through verbatim, so a transcript Claude Code wrote keeps its\n * own name and the two directions stay symmetric. Anything else is derived with a UUIDv8, which is\n * deterministic: the same agent id always yields the same filename, so nothing has to be persisted\n * to map one back to the other.\n *\n * A DERIVED name is version 8 — RFC 9562's slot for a UUID whose bits come from an\n * implementation-defined scheme, which is exactly what this is. The obvious alternative was v5, but\n * RFC 4122 fixes v5's hash to SHA-1, and reaching for SHA-1 in 2026 means either shipping a weak\n * primitive or arguing with every scanner that flags it, forever. v8 lets the hash be SHA-256 and\n * lets the version nibble say honestly that this is our scheme rather than a standard one.\n *\n * There is no security claim here either way — no secret, no signature, and nothing an attacker\n * gains by colliding two agent ids inside one consumer's own directory. The hash is a naming\n * function. The point of preferring SHA-256 is not that SHA-1 was exploitable here; it is that a\n * weak primitive in the tree costs a permanent argument with every scanner that sees it.\n *\n * The version nibble was measured, not assumed: CLI 2.1.236 resumes a v8-named transcript exactly as\n * it does a v4 one.\n */\nexport function sessionUuidFor(id: string): string {\n if (isSessionUuid(id)) return id.toLowerCase();\n const hash = createHash(\"sha256\")\n .update(Buffer.concat([SESSION_NAMESPACE, Buffer.from(id, \"utf8\")]))\n .digest();\n const bytes = Buffer.from(hash.subarray(0, 16));\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x80; // version 8 — RFC 9562 custom\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80; // RFC 9562 variant\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** The `.jsonl` path for a session: `<baseDir>/projects/<encoded-cwd>/<session-uuid>.jsonl`. */\nexport function transcriptPath(baseDir: string, cwd: string, sessionId: string): string {\n return join(baseDir, \"projects\", encodeProjectDir(cwd), `${sessionUuidFor(sessionId)}.jsonl`);\n}\n\n/**\n * The path this session used BEFORE #400 made transcript filenames UUIDs.\n *\n * Kept so an existing transcript is never orphaned: {@link FsSessionStore} prefers this file when it\n * exists, so history written under the old scheme keeps accumulating in the same file instead of\n * being silently abandoned for a fresh one under the new name.\n */\nexport function legacyTranscriptPath(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 SessionRecord => r !== undefined);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-transcript.ts"],"names":["redactSecrets","randomUUID","join","homedir","createHash","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;AAChD,EAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAC1C;AAEA,IAAM,GAAA,GAAM,CAAC,CAAA,KAAsBA,+BAAA,CAAc,CAAC,CAAA;AAGlD,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAMA,+BAAA,CAAc,IAAA,CAAK,UAAU,KAAA,IAAS,IAAI,CAAC,CAAC,CAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAOA,+BAAA,CAAc,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,EACpC;AACF;AAWO,IAAM,iBAAA,GAAN,MAAM,kBAAA,CAAkB;AAA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O;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-5HEG4CQH.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 * reference: knowledge-base/references/claude-code-log/claude_code_log/dag.py + models.py\n */\nimport { createHash, 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 * Root of the transcript state.\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/**\n * The fixed namespace for deriving a session UUID from an agent id (RFC 9562 § 5.8, version 8).\n *\n * A constant, because the derivation must be STABLE FOREVER: it is what lets the SDK find the\n * session it wrote last week without storing an id-to-filename map anywhere. Changing this value\n * orphans every transcript ever written.\n */\nconst SESSION_NAMESPACE = Buffer.from(\"b7a1f0c94e3d4a1b8f26d05c3a91e7d2\", \"hex\");\n\nconst UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Is this id already a canonical UUID, and therefore usable as a filename verbatim? */\nexport function isSessionUuid(id: string): boolean {\n return UUID_SHAPE.test(id);\n}\n\n/**\n * The transcript filename for an agent id — always a UUID.\n *\n * #400: the Claude Code CLI resumes a transcript ONLY when its basename is a UUID. Measured against\n * CLI 2.1.236: `<uuid>.jsonl` resumes; `agent-<uuid>.jsonl` and `billing-bot.jsonl` are both ignored,\n * with no error — the session simply is not offered. So a session written under a human-readable\n * agent id was invisible to `claude --continue`, which is the interoperability this project claims\n * as its difference from a proprietary session store.\n *\n * An id that is ALREADY a UUID passes through verbatim, so a transcript Claude Code wrote keeps its\n * own name and the two directions stay symmetric. Anything else is derived with a UUIDv8, which is\n * deterministic: the same agent id always yields the same filename, so nothing has to be persisted\n * to map one back to the other.\n *\n * A DERIVED name is version 8 — RFC 9562's slot for a UUID whose bits come from an\n * implementation-defined scheme, which is exactly what this is. The obvious alternative was v5, but\n * RFC 4122 fixes v5's hash to SHA-1, and reaching for SHA-1 in 2026 means either shipping a weak\n * primitive or arguing with every scanner that flags it, forever. v8 lets the hash be SHA-256 and\n * lets the version nibble say honestly that this is our scheme rather than a standard one.\n *\n * There is no security claim here either way — no secret, no signature, and nothing an attacker\n * gains by colliding two agent ids inside one consumer's own directory. The hash is a naming\n * function. The point of preferring SHA-256 is not that SHA-1 was exploitable here; it is that a\n * weak primitive in the tree costs a permanent argument with every scanner that sees it.\n *\n * The version nibble was measured, not assumed: CLI 2.1.236 resumes a v8-named transcript exactly as\n * it does a v4 one.\n */\nexport function sessionUuidFor(id: string): string {\n if (isSessionUuid(id)) return id.toLowerCase();\n const hash = createHash(\"sha256\")\n .update(Buffer.concat([SESSION_NAMESPACE, Buffer.from(id, \"utf8\")]))\n .digest();\n const bytes = Buffer.from(hash.subarray(0, 16));\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x80; // version 8 — RFC 9562 custom\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80; // RFC 9562 variant\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** The `.jsonl` path for a session: `<baseDir>/projects/<encoded-cwd>/<session-uuid>.jsonl`. */\nexport function transcriptPath(baseDir: string, cwd: string, sessionId: string): string {\n return join(baseDir, \"projects\", encodeProjectDir(cwd), `${sessionUuidFor(sessionId)}.jsonl`);\n}\n\n/**\n * The path this session used BEFORE #400 made transcript filenames UUIDs.\n *\n * Kept so an existing transcript is never orphaned: {@link FsSessionStore} prefers this file when it\n * exists, so history written under the old scheme keeps accumulating in the same file instead of\n * being silently abandoned for a fresh one under the new name.\n */\nexport function legacyTranscriptPath(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 SessionRecord => r !== undefined);\n}\n"]}