@theokit/sdk 4.63.0 → 4.63.2

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 +56 -0
  2. package/dist/a2a/index.cjs +2 -2
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent-2COLCVOJ.js +57 -0
  5. package/dist/{agent-536OOESZ.js.map → agent-2COLCVOJ.js.map} +1 -1
  6. package/dist/agent-EXAN5EYJ.cjs +66 -0
  7. package/dist/{agent-5KYMG63I.cjs.map → agent-EXAN5EYJ.cjs.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-AQLGBKNT.js → chunk-BZRFXJHA.js} +3 -3
  63. package/dist/{chunk-AQLGBKNT.js.map → chunk-BZRFXJHA.js.map} +1 -1
  64. package/dist/{chunk-UQGQFBRL.js → chunk-C3NT3PVE.js} +3 -3
  65. package/dist/{chunk-UQGQFBRL.js.map → chunk-C3NT3PVE.js.map} +1 -1
  66. package/dist/{chunk-UC3HT2S4.js → chunk-C72AZW7J.js} +3 -3
  67. package/dist/{chunk-UC3HT2S4.js.map → chunk-C72AZW7J.js.map} +1 -1
  68. package/dist/{chunk-WNTAPVU5.cjs → chunk-CQBXOJ6U.cjs} +13 -13
  69. package/dist/{chunk-WNTAPVU5.cjs.map → chunk-CQBXOJ6U.cjs.map} +1 -1
  70. package/dist/{chunk-T7XEKOVW.js → chunk-D4CUGAKZ.js} +3 -3
  71. package/dist/{chunk-T7XEKOVW.js.map → chunk-D4CUGAKZ.js.map} +1 -1
  72. package/dist/{chunk-R6TA2DRJ.js → chunk-DKD3MH6A.js} +6 -6
  73. package/dist/{chunk-R6TA2DRJ.js.map → chunk-DKD3MH6A.js.map} +1 -1
  74. package/dist/{chunk-NLXOGBRJ.cjs → chunk-DKK5QY4C.cjs} +358 -326
  75. package/dist/chunk-DKK5QY4C.cjs.map +1 -0
  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-EI2Q7SJ5.cjs → chunk-KQ7TS7WW.cjs} +10 -10
  103. package/dist/{chunk-EI2Q7SJ5.cjs.map → chunk-KQ7TS7WW.cjs.map} +1 -1
  104. package/dist/{chunk-RUDY2GTT.js → chunk-KQRW2GPZ.js} +5 -5
  105. package/dist/{chunk-RUDY2GTT.js.map → chunk-KQRW2GPZ.js.map} +1 -1
  106. package/dist/{chunk-P5LCASTC.cjs → chunk-KYAJINUI.cjs} +125 -125
  107. package/dist/{chunk-P5LCASTC.cjs.map → chunk-KYAJINUI.cjs.map} +1 -1
  108. package/dist/{chunk-AMFXSENK.js → chunk-LWGSI6M3.js} +4 -4
  109. package/dist/{chunk-AMFXSENK.js.map → chunk-LWGSI6M3.js.map} +1 -1
  110. package/dist/{chunk-ZHPWGIUX.js → chunk-LXI4XZEC.js} +5 -5
  111. package/dist/{chunk-ZHPWGIUX.js.map → chunk-LXI4XZEC.js.map} +1 -1
  112. package/dist/{chunk-AG5JPQIY.js → chunk-LXQ6HKPS.js} +3 -3
  113. package/dist/{chunk-AG5JPQIY.js.map → chunk-LXQ6HKPS.js.map} +1 -1
  114. package/dist/{chunk-ROYPRJH4.cjs → chunk-LYRDF5TQ.cjs} +9 -9
  115. package/dist/{chunk-ROYPRJH4.cjs.map → chunk-LYRDF5TQ.cjs.map} +1 -1
  116. package/dist/{chunk-G24KZRSA.js → chunk-N2U4AZGB.js} +3 -3
  117. package/dist/{chunk-G24KZRSA.js.map → chunk-N2U4AZGB.js.map} +1 -1
  118. package/dist/{chunk-4ERPXIVB.js → chunk-O73J46PV.js} +5 -5
  119. package/dist/{chunk-4ERPXIVB.js.map → chunk-O73J46PV.js.map} +1 -1
  120. package/dist/{chunk-F3YZMOAU.cjs → chunk-O7DK5PBJ.cjs} +4 -4
  121. package/dist/{chunk-F3YZMOAU.cjs.map → chunk-O7DK5PBJ.cjs.map} +1 -1
  122. package/dist/{chunk-Z4BCLVTI.cjs → chunk-O7LZFG6O.cjs} +5 -5
  123. package/dist/{chunk-Z4BCLVTI.cjs.map → chunk-O7LZFG6O.cjs.map} +1 -1
  124. package/dist/{chunk-3YJNUKYN.cjs → chunk-OHLDPWTA.cjs} +15 -15
  125. package/dist/{chunk-3YJNUKYN.cjs.map → chunk-OHLDPWTA.cjs.map} +1 -1
  126. package/dist/{chunk-FUL2I7G5.js → chunk-OSEG74VJ.js} +8 -8
  127. package/dist/{chunk-FUL2I7G5.js.map → chunk-OSEG74VJ.js.map} +1 -1
  128. package/dist/{chunk-UCBJBJ27.js → chunk-PUAEFLYK.js} +4 -4
  129. package/dist/{chunk-UCBJBJ27.js.map → chunk-PUAEFLYK.js.map} +1 -1
  130. package/dist/{chunk-2C72DXQF.cjs → chunk-RFMBZPOW.cjs} +9 -9
  131. package/dist/{chunk-2C72DXQF.cjs.map → chunk-RFMBZPOW.cjs.map} +1 -1
  132. package/dist/{chunk-NLTVXLGT.js → chunk-RFXWMRFC.js} +3 -3
  133. package/dist/{chunk-NLTVXLGT.js.map → chunk-RFXWMRFC.js.map} +1 -1
  134. package/dist/{chunk-MG3SOM3M.js → chunk-RMIWHYC7.js} +6 -6
  135. package/dist/{chunk-MG3SOM3M.js.map → chunk-RMIWHYC7.js.map} +1 -1
  136. package/dist/{chunk-2DG7KW4L.cjs → chunk-RMWTPV3M.cjs} +8 -8
  137. package/dist/{chunk-2DG7KW4L.cjs.map → chunk-RMWTPV3M.cjs.map} +1 -1
  138. package/dist/{chunk-P6A3M6VD.cjs → chunk-SZVR77EJ.cjs} +10 -10
  139. package/dist/{chunk-P6A3M6VD.cjs.map → chunk-SZVR77EJ.cjs.map} +1 -1
  140. package/dist/{chunk-3E77SX4H.js → chunk-TAZVKYWJ.js} +3 -3
  141. package/dist/{chunk-3E77SX4H.js.map → chunk-TAZVKYWJ.js.map} +1 -1
  142. package/dist/{chunk-WKRSH2VR.js → chunk-U6IFHFWK.js} +3 -3
  143. package/dist/{chunk-WKRSH2VR.js.map → chunk-U6IFHFWK.js.map} +1 -1
  144. package/dist/{chunk-I6TGFUCO.cjs → chunk-UALX2J2Q.cjs} +4 -4
  145. package/dist/{chunk-I6TGFUCO.cjs.map → chunk-UALX2J2Q.cjs.map} +1 -1
  146. package/dist/{chunk-XN7NOENA.js → chunk-UBDMVMBZ.js} +5 -5
  147. package/dist/{chunk-XN7NOENA.js.map → chunk-UBDMVMBZ.js.map} +1 -1
  148. package/dist/{chunk-YTR3RBUZ.js → chunk-UEXIJTLC.js} +4 -4
  149. package/dist/{chunk-YTR3RBUZ.js.map → chunk-UEXIJTLC.js.map} +1 -1
  150. package/dist/{chunk-DQKERTND.cjs → chunk-UGT7GK7I.cjs} +11 -11
  151. package/dist/{chunk-DQKERTND.cjs.map → chunk-UGT7GK7I.cjs.map} +1 -1
  152. package/dist/{chunk-FKMUFNQE.js → chunk-UMP6OJIM.js} +4 -4
  153. package/dist/{chunk-FKMUFNQE.js.map → chunk-UMP6OJIM.js.map} +1 -1
  154. package/dist/{chunk-AEOZTXVW.js → chunk-UNYXQ4M5.js} +3 -3
  155. package/dist/{chunk-AEOZTXVW.js.map → chunk-UNYXQ4M5.js.map} +1 -1
  156. package/dist/{chunk-2BDH744Z.js → chunk-UTSRIDKZ.js} +3 -3
  157. package/dist/{chunk-2BDH744Z.js.map → chunk-UTSRIDKZ.js.map} +1 -1
  158. package/dist/{chunk-2ADR2GSO.cjs → chunk-UU36SHFY.cjs} +5 -5
  159. package/dist/{chunk-2ADR2GSO.cjs.map → chunk-UU36SHFY.cjs.map} +1 -1
  160. package/dist/{chunk-R3UPQFKK.cjs → chunk-V2BOS4WF.cjs} +9 -9
  161. package/dist/{chunk-R3UPQFKK.cjs.map → chunk-V2BOS4WF.cjs.map} +1 -1
  162. package/dist/{chunk-CASUEY42.cjs → chunk-VX4SQ2LY.cjs} +24 -24
  163. package/dist/{chunk-CASUEY42.cjs.map → chunk-VX4SQ2LY.cjs.map} +1 -1
  164. package/dist/{chunk-CHKH5452.js → chunk-WHFUZMIC.js} +80 -48
  165. package/dist/chunk-WHFUZMIC.js.map +1 -0
  166. package/dist/{chunk-Q4CMI2LP.js → chunk-WLQNMXQE.js} +5 -5
  167. package/dist/{chunk-Q4CMI2LP.js.map → chunk-WLQNMXQE.js.map} +1 -1
  168. package/dist/{chunk-XWL6O3SW.cjs → chunk-WNO3C3N2.cjs} +4 -4
  169. package/dist/{chunk-XWL6O3SW.cjs.map → chunk-WNO3C3N2.cjs.map} +1 -1
  170. package/dist/{chunk-T7O6K6PX.js → chunk-XEQ3TM66.js} +18 -3
  171. package/dist/chunk-XEQ3TM66.js.map +1 -0
  172. package/dist/{chunk-BVZW2B5V.cjs → chunk-XJCXEKMD.cjs} +4 -4
  173. package/dist/{chunk-BVZW2B5V.cjs.map → chunk-XJCXEKMD.cjs.map} +1 -1
  174. package/dist/{chunk-JTB5Q42C.cjs → chunk-XL7Q7HB2.cjs} +4 -4
  175. package/dist/{chunk-JTB5Q42C.cjs.map → chunk-XL7Q7HB2.cjs.map} +1 -1
  176. package/dist/{chunk-LW7G5DYW.js → chunk-XO4SOZN6.js} +4 -4
  177. package/dist/{chunk-LW7G5DYW.js.map → chunk-XO4SOZN6.js.map} +1 -1
  178. package/dist/{chunk-CQGYNZ3K.cjs → chunk-XWTLIGO3.cjs} +4 -4
  179. package/dist/{chunk-CQGYNZ3K.cjs.map → chunk-XWTLIGO3.cjs.map} +1 -1
  180. package/dist/{chunk-6SBW4QR2.cjs → chunk-YML4ME27.cjs} +11 -11
  181. package/dist/{chunk-6SBW4QR2.cjs.map → chunk-YML4ME27.cjs.map} +1 -1
  182. package/dist/{chunk-P6H23T43.cjs → chunk-ZCIRZE37.cjs} +11 -11
  183. package/dist/{chunk-P6H23T43.cjs.map → chunk-ZCIRZE37.cjs.map} +1 -1
  184. package/dist/{chunk-QI7WE46I.cjs → chunk-ZLQSWSJ2.cjs} +11 -11
  185. package/dist/{chunk-QI7WE46I.cjs.map → chunk-ZLQSWSJ2.cjs.map} +1 -1
  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/structured-output-helpers.ts"],"names":[],"mappings":";;;;AAoBA,IAAI,OAAA;AAMG,SAAS,UAAA,GAAkC;AAChD,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAClC,EAAA,MAAM,CAAA,GAAI,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACvC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,EAAE,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AAE;AAC9D,EAAA,OAAO,EAAE,aAAa,CAAA,CAAE,WAAA,IAAe,GAAG,YAAA,EAAc,CAAA,CAAE,gBAAgB,CAAA,EAAE;AAC9E;AAMO,SAAS,gBAAgB,MAAA,EAAwB;AACtD,EAAA,OAAO,GAAG,MAAM;;AAAA,0FAAA,CAAA;AAClB;AAOO,SAAS,qBAAA,CACd,QACA,UAAA,EACA;AACA,EAAA,MAAM,IAAI,UAAA,EAAW;AAErB,EAAA,MAAM,aAAa,YAAA,CAAa,MAAA,EAAQ,EAAE,eAAA,EAAiB,OAAO,CAAA;AAClE,EAAA,OAAO;AAAA,IACL,CAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAY,UAAA,IAAc,CAAA;AAAA,IAC1B,YAAA,EAAc,EAAE,WAAA,EAAa,CAAA,EAAG,cAAc,CAAA;AAAE,GAClD;AACF;AAQA,eAAsB,yBAAA,CACpB,OACA,OAAA,EACe;AACf,EAAA,MAAM,MAAM,OAAA,EAAQ;AACpB,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,MAAM,OAAO,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-AEOZTXVW.js","sourcesContent":["import { createRequire } from \"node:module\";\nimport type { z as ZodNamespace, ZodType } from \"zod\";\nimport { ConfigurationError } from \"../errors.js\";\n\nimport type { AgentOptions, CustomTool, LocalOptions, ModelSelection } from \"../types/agent.js\";\nimport type { ProviderRoutingSettings } from \"../types/providers.js\";\nimport { toJsonSchema } from \"./zod/to-json-schema.js\";\n\n/**\n * Shared helpers for `Agent.generateObject` (ADR D33) and\n * `Agent.streamObject` (ADR D39). Both build a transient agent with a\n * single synthetic `output` tool whose handler captures the model's\n * structured response.\n *\n * Extracted from inline duplicates to keep jscpd quiet AND to keep the\n * two public APIs in lockstep.\n *\n * @internal\n */\n\nlet cachedZ: typeof ZodNamespace | undefined;\n\n/**\n * Load Zod via createRequire (it's an optional peer dep). Throws a typed\n * ConfigurationError if Zod isn't installed.\n */\nexport function requireZod(): typeof ZodNamespace {\n if (cachedZ !== undefined) return cachedZ;\n const r = createRequire(import.meta.url);\n let mod: { z?: typeof ZodNamespace } & typeof ZodNamespace;\n try {\n mod = r(\"zod\") as typeof mod;\n } catch (cause) {\n throw new ConfigurationError(\n \"Structured output requires the optional peer dependency `zod`. \" +\n 'Add `\"zod\": \"^3.25.0 || ^4.0.0\"` to your package.json and reinstall.',\n { code: \"zod_not_installed\", cause },\n );\n }\n cachedZ = (mod.z ?? mod) as typeof ZodNamespace;\n return cachedZ;\n}\n\n/**\n * Build the synthetic `output` tool used by both `generateObject` and\n * `streamObject`. The handler captures the raw input on first call only\n * (EC-D10 / EC-6: parallel tool use in Claude 3.5+ may invoke `output`\n * twice; later calls are ignored).\n */\nexport function makeOutputTool(\n jsonSchema: Record<string, unknown>,\n onCapture: (input: unknown) => string | Promise<string> | undefined,\n): CustomTool {\n return {\n name: \"output\",\n description: \"Call this tool with your final structured answer. Match the JSON schema exactly.\",\n inputSchema: jsonSchema,\n handler: (input) => {\n const out = onCapture(input);\n // Some callers throw a sentinel (generate-object) and never return.\n // Others return a string (stream-object). Anything else → empty string.\n if (typeof out === \"string\") return out;\n if (out instanceof Promise) return out;\n return \"\";\n },\n };\n}\n\n/**\n * Assemble the AgentOptions for the transient agent. Shared shape:\n * model + local + tools[output] + systemPrompt + apiKey.\n */\nexport function buildTransientAgentOptions(params: {\n // SE8 — accepts the bare-string shorthand; forwarded to AgentOptions.model\n // (normalized at Agent.create).\n model: string | ModelSelection;\n local: LocalOptions;\n outputTool: CustomTool;\n systemPrompt?: string;\n apiKey?: string;\n providers?: ProviderRoutingSettings;\n}): AgentOptions {\n return {\n model: params.model,\n local: params.local,\n tools: [params.outputTool],\n systemPrompt:\n params.systemPrompt ??\n \"You produce structured output by calling the `output` tool exactly once. Match the JSON schema.\",\n ...(params.apiKey !== undefined ? { apiKey: params.apiKey } : {}),\n ...(params.providers !== undefined ? { providers: params.providers } : {}),\n };\n}\n\n/**\n * Best-effort extraction of token usage from a run result. Local runtimes\n * may not expose it; default to zeros.\n */\nexport function extractUsage(result: unknown): { inputTokens: number; outputTokens: number } {\n const u = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;\n if (u === undefined) return { inputTokens: 0, outputTokens: 0 };\n return { inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0 };\n}\n\n/**\n * Build the user-message prompt that instructs the model to call the\n * `output` tool with a schema-matched structured answer.\n */\nexport function buildToolPrompt(prompt: string): string {\n return `${prompt}\\n\\nRespond by calling the \\`output\\` tool with the structured answer that matches the schema.`;\n}\n\n/**\n * One-shot setup shared by both `generateObject` and `streamObject`. Loads\n * Zod, computes the JSON schema, primes the captured-raw / usage / retry\n * state. Returns the values needed by the caller's loop.\n */\nexport function setupStructuredOutput<T extends ZodType>(\n schema: T,\n maxRetries: number | undefined,\n) {\n const z = requireZod();\n // Universal Zod 3+4 conversion (feature-detects native v4, falls back to lib on v3).\n const jsonSchema = toJsonSchema(schema, { unrepresentable: \"any\" });\n return {\n z,\n jsonSchema,\n maxRetries: maxRetries ?? 1,\n initialUsage: { inputTokens: 0, outputTokens: 0 },\n };\n}\n\n/**\n * Cleanup the transient agent after generateObject/streamObject finish.\n * Disposes AND hard-deletes from the registry so the count stays stable.\n *\n * @internal\n */\nexport async function disposeAndDeleteTransient(\n agent: { dispose: () => Promise<void>; agentId: string },\n deletor: (agentId: string) => Promise<void>,\n): Promise<void> {\n await agent.dispose();\n try {\n await deletor(agent.agentId);\n } catch {\n // Best-effort cleanup.\n }\n}\n\nvoid (null as unknown as ZodType); // satisfies unused-import check\n"]}
1
+ {"version":3,"sources":["../src/internal/structured-output-helpers.ts"],"names":[],"mappings":";;;;AAoBA,IAAI,OAAA;AAMG,SAAS,UAAA,GAAkC;AAChD,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAClC,EAAA,MAAM,CAAA,GAAI,aAAA,CAAc,MAAA,CAAA,IAA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KAAA;AAClF,EAAA,IAAI,MAAM,MAAA,EAAW,OAAO,EAAE,WAAA,EAAa,CAAA,EAAG,cAAc,CAAA,EAAE;AAC9D,EAAA,OAAO,EAAE,aAAa,CAAA,CAAE,WAAA,IAAe,GAAG,YAAA,EAAc,CAAA,CAAE,gBAAgB,CAAA,EAAE;AAC9E;AAMO,SAAS,gBAAgB,MAAA,EAAwB;AACtD,EAAA,OAAO,GAAG,MAAM;;AAAA,0FAAA,CAAA;AAClB;AAOO,SAAS,qBAAA,CACd,QACA,UAAA,EACA;AACA,EAAA,MAAM,IAAI,UAAA,EAAW;AAErB,EAAA,MAAM,aAAa,YAAA,CAAa,MAAA,EAAQ,EAAE,eAAA,EAAiB,OAAO,CAAA;AAClE,EAAA,OAAO;AAAA,IACL,CAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAY,UAAA,IAAc,CAAA;AAAA,IAC1B,YAAA,EAAc,EAAE,WAAA,EAAa,CAAA,EAAG,cAAc,CAAA;AAAE,GAClD;AACF;AAQA,eAAsB,yBAAA,CACpB,OACA,OAAA,EACe;AACf,EAAA,MAAM,MAAM,OAAA,EAAQ;AACpB,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,MAAM,OAAO,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-UNYXQ4M5.js","sourcesContent":["import { createRequire } from \"node:module\";\nimport type { z as ZodNamespace, ZodType } from \"zod\";\nimport { ConfigurationError } from \"../errors.js\";\n\nimport type { AgentOptions, CustomTool, LocalOptions, ModelSelection } from \"../types/agent.js\";\nimport type { ProviderRoutingSettings } from \"../types/providers.js\";\nimport { toJsonSchema } from \"./zod/to-json-schema.js\";\n\n/**\n * Shared helpers for `Agent.generateObject` (ADR D33) and\n * `Agent.streamObject` (ADR D39). Both build a transient agent with a\n * single synthetic `output` tool whose handler captures the model's\n * structured response.\n *\n * Extracted from inline duplicates to keep jscpd quiet AND to keep the\n * two public APIs in lockstep.\n *\n * @internal\n */\n\nlet cachedZ: typeof ZodNamespace | undefined;\n\n/**\n * Load Zod via createRequire (it's an optional peer dep). Throws a typed\n * ConfigurationError if Zod isn't installed.\n */\nexport function requireZod(): typeof ZodNamespace {\n if (cachedZ !== undefined) return cachedZ;\n const r = createRequire(import.meta.url);\n let mod: { z?: typeof ZodNamespace } & typeof ZodNamespace;\n try {\n mod = r(\"zod\") as typeof mod;\n } catch (cause) {\n throw new ConfigurationError(\n \"Structured output requires the optional peer dependency `zod`. \" +\n 'Add `\"zod\": \"^3.25.0 || ^4.0.0\"` to your package.json and reinstall.',\n { code: \"zod_not_installed\", cause },\n );\n }\n cachedZ = (mod.z ?? mod) as typeof ZodNamespace;\n return cachedZ;\n}\n\n/**\n * Build the synthetic `output` tool used by both `generateObject` and\n * `streamObject`. The handler captures the raw input on first call only\n * (EC-D10 / EC-6: parallel tool use in Claude 3.5+ may invoke `output`\n * twice; later calls are ignored).\n */\nexport function makeOutputTool(\n jsonSchema: Record<string, unknown>,\n onCapture: (input: unknown) => string | Promise<string> | undefined,\n): CustomTool {\n return {\n name: \"output\",\n description: \"Call this tool with your final structured answer. Match the JSON schema exactly.\",\n inputSchema: jsonSchema,\n handler: (input) => {\n const out = onCapture(input);\n // Some callers throw a sentinel (generate-object) and never return.\n // Others return a string (stream-object). Anything else → empty string.\n if (typeof out === \"string\") return out;\n if (out instanceof Promise) return out;\n return \"\";\n },\n };\n}\n\n/**\n * Assemble the AgentOptions for the transient agent. Shared shape:\n * model + local + tools[output] + systemPrompt + apiKey.\n */\nexport function buildTransientAgentOptions(params: {\n // SE8 — accepts the bare-string shorthand; forwarded to AgentOptions.model\n // (normalized at Agent.create).\n model: string | ModelSelection;\n local: LocalOptions;\n outputTool: CustomTool;\n systemPrompt?: string;\n apiKey?: string;\n providers?: ProviderRoutingSettings;\n}): AgentOptions {\n return {\n model: params.model,\n local: params.local,\n tools: [params.outputTool],\n systemPrompt:\n params.systemPrompt ??\n \"You produce structured output by calling the `output` tool exactly once. Match the JSON schema.\",\n ...(params.apiKey !== undefined ? { apiKey: params.apiKey } : {}),\n ...(params.providers !== undefined ? { providers: params.providers } : {}),\n };\n}\n\n/**\n * Best-effort extraction of token usage from a run result. Local runtimes\n * may not expose it; default to zeros.\n */\nexport function extractUsage(result: unknown): { inputTokens: number; outputTokens: number } {\n const u = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;\n if (u === undefined) return { inputTokens: 0, outputTokens: 0 };\n return { inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0 };\n}\n\n/**\n * Build the user-message prompt that instructs the model to call the\n * `output` tool with a schema-matched structured answer.\n */\nexport function buildToolPrompt(prompt: string): string {\n return `${prompt}\\n\\nRespond by calling the \\`output\\` tool with the structured answer that matches the schema.`;\n}\n\n/**\n * One-shot setup shared by both `generateObject` and `streamObject`. Loads\n * Zod, computes the JSON schema, primes the captured-raw / usage / retry\n * state. Returns the values needed by the caller's loop.\n */\nexport function setupStructuredOutput<T extends ZodType>(\n schema: T,\n maxRetries: number | undefined,\n) {\n const z = requireZod();\n // Universal Zod 3+4 conversion (feature-detects native v4, falls back to lib on v3).\n const jsonSchema = toJsonSchema(schema, { unrepresentable: \"any\" });\n return {\n z,\n jsonSchema,\n maxRetries: maxRetries ?? 1,\n initialUsage: { inputTokens: 0, outputTokens: 0 },\n };\n}\n\n/**\n * Cleanup the transient agent after generateObject/streamObject finish.\n * Disposes AND hard-deletes from the registry so the count stays stable.\n *\n * @internal\n */\nexport async function disposeAndDeleteTransient(\n agent: { dispose: () => Promise<void>; agentId: string },\n deletor: (agentId: string) => Promise<void>,\n): Promise<void> {\n await agent.dispose();\n try {\n await deletor(agent.agentId);\n } catch {\n // Best-effort cleanup.\n }\n}\n\nvoid (null as unknown as ZodType); // satisfies unused-import check\n"]}
@@ -1,4 +1,4 @@
1
- import { registerBuiltins, listProviders, getProviderProfile } from './chunk-Q4CMI2LP.js';
1
+ import { registerBuiltins, listProviders, getProviderProfile } from './chunk-WLQNMXQE.js';
2
2
 
3
3
  // src/providers.ts
4
4
  function listProviders2() {
@@ -11,5 +11,5 @@ function getProviderProfile2(name) {
11
11
  }
12
12
 
13
13
  export { getProviderProfile2 as getProviderProfile, listProviders2 as listProviders };
14
- //# sourceMappingURL=chunk-2BDH744Z.js.map
15
- //# sourceMappingURL=chunk-2BDH744Z.js.map
14
+ //# sourceMappingURL=chunk-UTSRIDKZ.js.map
15
+ //# sourceMappingURL=chunk-UTSRIDKZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/providers.ts"],"names":["listProviders","getProviderProfile"],"mappings":";;;AA4BO,SAASA,cAAAA,GAA4C;AAC1D,EAAA,gBAAA,EAAiB;AACjB,EAAA,OAAO,aAAA,EAAa;AACtB;AAQO,SAASC,oBAAmB,IAAA,EAA2C;AAC5E,EAAA,gBAAA,EAAiB;AACjB,EAAA,OAAO,mBAAW,IAAI,CAAA;AACxB","file":"chunk-2BDH744Z.js","sourcesContent":["/**\n * The provider registry, as public API.\n *\n * It was `@internal`, which meant the SDK was the only thing that could answer \"which providers\n * exist, and what does each one need?\". `theokit` consequently kept a hand-written list of three —\n * against the 46 registered here — so an agent declaring `ollama/qwen2.5:3b` routed to whatever\n * key happened to be set instead of to Ollama (usetheokit/theokit#326).\n *\n * A second table that nothing forces to agree with the first is not a cache, it is a future bug.\n * These two functions exist so there is one table.\n *\n * Both ensure the builtins are registered before answering: registration is lazy (it happens when\n * an agent is created, a run is routed, or a provider is defined), so a caller asking early would\n * otherwise get an empty registry and reasonably conclude the SDK knows nothing.\n */\n\nimport { registerBuiltins } from \"./internal/providers/builtin/index.js\";\nimport {\n getProviderProfile as getProfile,\n listProviders as listProfiles,\n} from \"./internal/providers/registry.js\";\nimport type { ProviderProfile } from \"./internal/providers/types.js\";\n\n/**\n * Every registered provider — builtins, the JSON catalog, and anything a plugin registered.\n *\n * @public\n */\nexport function listProviders(): readonly ProviderProfile[] {\n registerBuiltins();\n return listProfiles();\n}\n\n/**\n * One provider by name or alias (`lm-studio` resolves to `lmstudio`), or `undefined` when nothing\n * has registered it.\n *\n * @public\n */\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n registerBuiltins();\n return getProfile(name);\n}\n"]}
1
+ {"version":3,"sources":["../src/providers.ts"],"names":["listProviders","getProviderProfile"],"mappings":";;;AA4BO,SAASA,cAAAA,GAA4C;AAC1D,EAAA,gBAAA,EAAiB;AACjB,EAAA,OAAO,aAAA,EAAa;AACtB;AAQO,SAASC,oBAAmB,IAAA,EAA2C;AAC5E,EAAA,gBAAA,EAAiB;AACjB,EAAA,OAAO,mBAAW,IAAI,CAAA;AACxB","file":"chunk-UTSRIDKZ.js","sourcesContent":["/**\n * The provider registry, as public API.\n *\n * It was `@internal`, which meant the SDK was the only thing that could answer \"which providers\n * exist, and what does each one need?\". `theokit` consequently kept a hand-written list of three —\n * against the 46 registered here — so an agent declaring `ollama/qwen2.5:3b` routed to whatever\n * key happened to be set instead of to Ollama (usetheokit/theokit#326).\n *\n * A second table that nothing forces to agree with the first is not a cache, it is a future bug.\n * These two functions exist so there is one table.\n *\n * Both ensure the builtins are registered before answering: registration is lazy (it happens when\n * an agent is created, a run is routed, or a provider is defined), so a caller asking early would\n * otherwise get an empty registry and reasonably conclude the SDK knows nothing.\n */\n\nimport { registerBuiltins } from \"./internal/providers/builtin/index.js\";\nimport {\n getProviderProfile as getProfile,\n listProviders as listProfiles,\n} from \"./internal/providers/registry.js\";\nimport type { ProviderProfile } from \"./internal/providers/types.js\";\n\n/**\n * Every registered provider — builtins, the JSON catalog, and anything a plugin registered.\n *\n * @public\n */\nexport function listProviders(): readonly ProviderProfile[] {\n registerBuiltins();\n return listProfiles();\n}\n\n/**\n * One provider by name or alias (`lm-studio` resolves to `lmstudio`), or `undefined` when nothing\n * has registered it.\n *\n * @public\n */\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n registerBuiltins();\n return getProfile(name);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkZF2LDKQQ_cjs = require('./chunk-ZF2LDKQQ.cjs');
4
- var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
4
+ var chunkEG4QM7ZJ_cjs = require('./chunk-EG4QM7ZJ.cjs');
5
5
  var fs = require('fs');
6
6
  var path = require('path');
7
7
 
@@ -32,7 +32,7 @@ async function getProperLockfile() {
32
32
  if (!validateLockModule(mod)) {
33
33
  if (!warnedStructural) {
34
34
  warnedStructural = true;
35
- chunkNUKRL3I6_cjs.diag(
35
+ chunkEG4QM7ZJ_cjs.diag(
36
36
  "[theokit-sdk] proper-lockfile: imported module does NOT expose the expected `lock`/`unlock` API surface. This may indicate a supply-chain compromise or an incompatible major version. Falling back to in-process mutex (no cross-process safety). Reinstall with: pnpm add proper-lockfile@^11\n"
37
37
  );
38
38
  }
@@ -56,7 +56,7 @@ async function withFileLock(path, fn, options) {
56
56
  if (lib === null) {
57
57
  if (!warnedMissing && !warnedStructural) {
58
58
  warnedMissing = true;
59
- chunkNUKRL3I6_cjs.diag(describeLockLoadFailure(loadFailure));
59
+ chunkEG4QM7ZJ_cjs.diag(describeLockLoadFailure(loadFailure));
60
60
  }
61
61
  return chunkZF2LDKQQ_cjs.withCwdMutex(`file-lock:${path}`, fn);
62
62
  }
@@ -181,5 +181,5 @@ exports.appendJsonl = appendJsonl;
181
181
  exports.loadJsonl = loadJsonl;
182
182
  exports.readJsonlIds = readJsonlIds;
183
183
  exports.withFileLock = withFileLock;
184
- //# sourceMappingURL=chunk-2ADR2GSO.cjs.map
185
- //# sourceMappingURL=chunk-2ADR2GSO.cjs.map
184
+ //# sourceMappingURL=chunk-UU36SHFY.cjs.map
185
+ //# sourceMappingURL=chunk-UU36SHFY.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/file-lock.ts","../src/internal/persistence/jsonl.ts"],"names":["diag","withCwdMutex","readFileSync","path","mkdirSync","dirname","openSync","writeSync","closeSync","fstatSync","readSync"],"mappings":";;;;;;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,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,IAAA,IAAI,OAAO,QAAQ,QAAA,IAAY,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-2ADR2GSO.cjs","sourcesContent":["/**\n * Cross-process file lock helper (ADR D61).\n *\n * Uses `proper-lockfile` (optional peer dep) for cross-process locks. When\n * the peer dep is absent, falls back to `withCwdMutex` (in-process only)\n * with a one-shot stderr warning.\n *\n * EC-1 fix: uses a companion `<path>.lock` file with `realpath: false` so\n * `withFileLock` works even when the target `path` does not exist yet.\n * Without this, fresh installs that lock-then-create would crash with ENOENT.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { withCwdMutex } from \"./cwd-mutex.js\";\n\ninterface ProperLockfileModule {\n lock: (file: string, options: ProperLockfileOptions) => Promise<() => Promise<void>>;\n}\n\ninterface ProperLockfileOptions {\n lockfilePath?: string;\n realpath?: boolean;\n stale?: number;\n retries?: {\n retries: number;\n factor?: number;\n minTimeout?: number;\n maxTimeout?: number;\n };\n}\n\nlet cached: ProperLockfileModule | null | undefined;\nlet warnedMissing = false;\nlet warnedStructural = false;\n/** Why the import failed, kept so the warning can report the observation instead of a guess (#174). */\nlet loadFailure: unknown;\n\n/** Node reports a missing module as `ERR_MODULE_NOT_FOUND` (ESM loader) or `MODULE_NOT_FOUND` (CJS). */\nfunction isModuleAbsent(err: unknown): boolean {\n const code = (err as { code?: unknown } | null | undefined)?.code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\n/**\n * #174 — build the fallback warning from what actually happened.\n *\n * This used to always read \"proper-lockfile not installed\", because the import was wrapped in a\n * bare `catch` that discarded the error (Unbreakable Rule 8: a swallowed error is the dangerous\n * kind). A consumer whose package WAS installed, declared and resolvable spent a debugging session\n * re-verifying the install, because the message named a cause the code had never checked.\n *\n * Absence is now the only case that claims absence. Every other failure — a broken install, an\n * interop problem, a bundler that rewrote the specifier — reports its own code and message, which\n * is what points at the real cause.\n *\n * @internal\n */\nfunction describeLockLoadFailure(err: unknown): string {\n const consequence =\n \"cross-process file lock unavailable — concurrent processes over the same file are NOT serialized.\";\n if (isModuleAbsent(err)) {\n return `[theokit-sdk] proper-lockfile not installed; ${consequence} Install with: pnpm add proper-lockfile\\n`;\n }\n const code = (err as { code?: unknown } | null | undefined)?.code;\n const detail = err instanceof Error ? err.message : String(err);\n return (\n `[theokit-sdk] proper-lockfile could not be loaded${code !== undefined ? ` (${String(code)})` : \"\"}: ` +\n `${detail}. ${consequence} The package resolves for the SDK but failed to load — check bundling ` +\n \"and module-format interop before re-checking the install.\\n\"\n );\n}\n\n/** Test seam for the message builder — NOT in the public barrel. @internal */\nexport function __TESTING__describeLockLoadFailure(err: unknown): string {\n return describeLockLoadFailure(err);\n}\n\nasync function getProperLockfile(): Promise<ProperLockfileModule | null> {\n if (cached !== undefined) return cached;\n try {\n const mod = await import(\"proper-lockfile\");\n // T5.9 — supply-chain hardening: validate the imported module\n // exposes the API surface we depend on BEFORE caching it. A\n // tampered or incompatible version that lacks `lock`/`unlock`\n // functions gets treated as \"not installed\" with an advisory\n // warning — never silently used.\n if (!validateLockModule(mod)) {\n if (!warnedStructural) {\n warnedStructural = true;\n diag(\n \"[theokit-sdk] proper-lockfile: imported module does NOT expose \" +\n \"the expected `lock`/`unlock` API surface. This may indicate a \" +\n \"supply-chain compromise or an incompatible major version. \" +\n \"Falling back to in-process mutex (no cross-process safety). \" +\n \"Reinstall with: pnpm add proper-lockfile@^11\\n\",\n );\n }\n cached = null;\n return cached;\n }\n cached = mod as ProperLockfileModule;\n } catch (err) {\n // #174 — keep WHY. Discarding it here is what made the fallback warning assert a cause it had\n // never observed, and sent a consumer to re-check an install that was already correct.\n loadFailure = err;\n cached = null;\n }\n return cached;\n}\n\n/**\n * T5.9 — Structural validation of the dynamically-imported\n * `proper-lockfile` module. Verifies the API surface we depend on\n * (`lock` and `unlock` as functions) is present. Pure function —\n * never throws, never mutates, never performs I/O.\n *\n * Exported via `__TESTING__validateLockModule` seam so unit tests\n * can drive the check without spinning up the dynamic import.\n *\n * @internal\n */\nfunction validateLockModule(mod: unknown): boolean {\n if (mod === null || mod === undefined || typeof mod !== \"object\") return false;\n const m = mod as Record<string, unknown>;\n return typeof m.lock === \"function\" && typeof m.unlock === \"function\";\n}\n\n/**\n * T5.9 — Test seam: expose the structural validator for unit tests.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__validateLockModule(mod: unknown): boolean {\n return validateLockModule(mod);\n}\n\n/**\n * T5.9 — Test seam: reset the module cache + warning flags between\n * tests so each test starts fresh. NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__resetFileLockCache(): void {\n cached = undefined;\n warnedMissing = false;\n warnedStructural = false;\n loadFailure = undefined;\n}\n\n/**\n * Retry and staleness tuning for `withFileLock`.\n *\n * Every field is optional and the defaults are applied per call, so `undefined` means the default\n * rather than \"no limit\". They are handed to `proper-lockfile` and have NO effect on the fallback\n * path: when that package is absent, `withFileLock` degrades to the in-process mutex, which\n * queues indefinitely and never goes stale.\n *\n * `stale` (default 30000 ms) is how old a lock file must be before it is treated as abandoned by a\n * dead process and broken. Setting it below the longest a legitimate holder can run is what turns\n * a slow operation into two concurrent ones.\n *\n * `retries` (default 5) is the number of acquisition attempts AFTER the first, and `retryFactor`\n * (default 1.5) the backoff multiplier between them. The per-attempt wait is clamped to\n * 100–5000 ms, which the caller cannot change. Exhausting the retries rejects — it does not fall\n * through to running `fn` unlocked.\n *\n * @public — re-exported from the semver-protected `@theokit/sdk/persistence` barrel, and (for\n * back-compat) from the semver-exempt `@theokit/sdk/internal/persistence` alias.\n */\nexport interface FileLockOptions {\n /** Stale lock timeout in ms. Default 30_000 (30s). */\n stale?: number;\n /** Max retries on busy lock. Default 5. */\n retries?: number;\n /** Backoff factor between retries. Default 1.5. */\n retryFactor?: number;\n}\n\n/**\n * Run `fn` while holding an OS-level cross-process lock on `path`.\n *\n * If `proper-lockfile` is installed, uses it with a companion `<path>.lock`\n * file (`realpath: false`, so target file does NOT need to exist yet).\n * Otherwise falls back to in-process `withCwdMutex` and prints a one-shot\n * stderr warning telling the user to install `proper-lockfile` for\n * cross-process safety.\n *\n * The lock is released even when `fn` throws.\n *\n */\nexport async function withFileLock<T>(\n path: string,\n fn: () => Promise<T>,\n options?: FileLockOptions,\n): Promise<T> {\n const lib = await getProperLockfile();\n\n if (lib === null) {\n // #174 — stay silent when the structural check already explained itself. Emitting \"not\n // installed\" on top of \"does not expose lock/unlock\" would be two contradictory diagnoses of\n // one failure, and the reader has no way to tell which is true.\n if (!warnedMissing && !warnedStructural) {\n warnedMissing = true;\n diag(describeLockLoadFailure(loadFailure));\n }\n return withCwdMutex(`file-lock:${path}`, fn);\n }\n\n // proper-lockfile errors immediately on same-process concurrent acquire\n // (\"Lock file is already being held\"). Wrap with cwd-mutex first so\n // in-process callers queue and only ONE thread at a time enters the\n // cross-process acquire path. Combined: full in-process + cross-process\n // serialization.\n return withCwdMutex(`file-lock:${path}`, async () => {\n const release = await lib.lock(path, {\n // EC-1: companion lockfile, target path may not exist yet.\n lockfilePath: `${path}.lock`,\n realpath: false,\n stale: options?.stale ?? 30_000,\n retries: {\n retries: options?.retries ?? 5,\n factor: options?.retryFactor ?? 1.5,\n minTimeout: 100,\n maxTimeout: 5_000,\n },\n });\n\n try {\n return await fn();\n } finally {\n await release();\n }\n });\n}\n\n/**\n * Test helper — resets the cached proper-lockfile module + warning flag.\n * Allows tests to simulate \"module absent\" by clearing cache then\n * monkey-patching the dynamic import resolution.\n *\n * @internal\n */\nexport function _resetFileLockCacheForTesting(): void {\n cached = undefined;\n warnedMissing = false;\n}\n","/**\n * Durable JSONL primitives shared by the eval harness (M6).\n *\n * - `loadJsonl` — generic dataset reader (split/trim/skip-blank/parse) with a\n * line-numbered {@link JsonlParseError}. The dataset SCHEMA is the caller's\n * concern via `map` (M6 ADR D3) — this module owns only the parse.\n * - `appendJsonl` / `readJsonlIds` — crash-durable, resumable batch persistence\n * (M6 ADR D1): each record is appended as one whole `\\n`-terminated line the\n * instant it is produced, and a re-run resumes by skipping already-keyed rows.\n *\n * reference: knowledge-base/references/theocode-eval/lib/swebench-dataset.ts:82\n * (parseJsonl + line-N error) and swebench-batch.ts:113,205 (resume + per-line\n * flush).\n *\n * @internal\n */\nimport {\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/** Raised when a JSONL line is not valid JSON or is not a JSON object. Carries the 1-based line number. */\nexport class JsonlParseError extends Error {\n constructor(\n message: string,\n readonly line: number,\n ) {\n super(message);\n this.name = \"JsonlParseError\";\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Parse a single trimmed line to a plain object, or `undefined` if blank / invalid / non-object. */\nfunction tryParseObjectLine(line: string): Record<string, unknown> | undefined {\n if (line.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n return isPlainObject(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a JSONL file into rows. Blank lines are skipped. A malformed or\n * non-object line throws {@link JsonlParseError} naming the 1-based line. When\n * `map` is provided, each raw object is mapped to the typed row (the SWE-bench\n * schema lives in the caller's `map`, per M6 ADR D3).\n */\nexport function loadJsonl<T = Record<string, unknown>>(\n path: string,\n opts: {\n map?: (raw: Record<string, unknown>, lineNumber: number) => T;\n /**\n * M81 — tolerate a truncated LAST line (a crash artifact: the process died mid-write).\n *\n * Opt-in on purpose. As a default it would also swallow corruption in the MIDDLE of the file,\n * turning loud data loss into silent data loss — the wrong trade for a session store.\n */\n tolerateTrailingPartialLine?: boolean;\n } = {},\n): T[] {\n const lines = readFileSync(path, \"utf8\").split(\"\\n\");\n const out: T[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n const lineNumber = i + 1;\n const line = (lines[i] ?? \"\").trim();\n if (line.length === 0) continue;\n // M81 — `undefined` = a tolerated invalid line (the last one, truncated by a crash). Any other\n // invalid line has already thrown inside `parseLine`.\n const parsed = parseLine(\n line,\n lineNumber,\n opts.tolerateTrailingPartialLine === true && lineNumber === lines.length,\n );\n if (parsed === undefined) break;\n out.push(opts.map ? opts.map(parsed, lineNumber) : (parsed as unknown as T));\n }\n return out;\n}\n\n/**\n * Parses ONE line, returning `undefined` when it is a tolerated truncated last line.\n *\n * Extracted because `loadJsonl` went over the cognitive-complexity ceiling once it gained the\n * tolerance — and because parsing a line and iterating a file are two responsibilities that were\n * only together out of habit.\n */\nfunction parseLine(\n line: string,\n lineNumber: number,\n tolerate: boolean,\n): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n if (tolerate) return undefined;\n throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);\n }\n if (!isPlainObject(parsed)) {\n throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);\n }\n return parsed;\n}\n\n/**\n * Append one record as a whole `\\n`-terminated JSON line. Creates the parent dir\n * if missing. `appendFileSync` is synchronous, so within a single Node process\n * the event loop serializes writes and each call writes its line atomically —\n * interleave-safe for the bounded-concurrency batch runner.\n *\n * reference: swebench-batch.ts:192 (mkdir-before-append), :205 (per-line flush).\n */\nexport function appendJsonl(path: string, record: unknown): void {\n // T2.4 — `0o700` for the same reason the file below is `0o600`, and it is the half M93 missed. A\n // private file inside a group-writable directory can be replaced wholesale, and the replacement's\n // mode is whatever the writer chose. Under `umask 002` this directory was born `0775`.\n //\n // The directory sits under `~/.theokit`, shared with the credential and trust stores, and the\n // framework already wrote the diagnosis while fixing a sibling (`@theokit/agents\n // config/trust-store.ts:157-161`): the mode argument is a no-op on a directory that already\n // exists, \"and this one is shared with the SDK's transcript root — whoever creates it first sets\n // the permissions\". Whoever creates it first is usually THIS function, because a session writes a\n // transcript before it ever touches a credential. So `assertSecureModes` was not wrong to demand a\n // private directory; this path was wrong to produce one that fails it, depending on run order.\n //\n // Creation-time only, deliberately: repairing a pre-existing directory means `stat` + `chmod` on\n // every append, and this is the hot path of every session. The pre-existing case is what\n // `assertSecureModes` is for.\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const prefix = needsLineBreakBefore(path) ? \"\\n\" : \"\";\n // M93 (adversarial review, H1) — `0o600`. `appendFileSync` takes no `mode`, so the permission came\n // from the umask: under `umask 022` the transcript was born `0664`, world-readable. The previous\n // path (`replaceFileAtomic`) pinned `0o600` on purpose — \"holds the FULL in-flight content\n // (credential snapshots, OAuth tokens)\" (`atomic-write.ts:107`) — and switching to append lost\n // that silently. The same class had already been caught in the consumer (`atomic-sync.ts`, M88\n // HIGH-1).\n //\n // `mode` only applies on CREATION; a pre-existing file keeps whatever permission it already has.\n const fd = openSync(path, \"a\", 0o600);\n try {\n writeSync(fd, `${prefix}${JSON.stringify(record)}\\n`);\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Does the file end without a `\\n`? Then the last line is truncated — a crash mid-append.\n *\n * Without this check the next append **glues** itself onto the middle of the broken line, producing\n * an invalid line the reader discards: the NEW record disappears along with the partial one. The\n * previous path (read-modify-write) self-healed from this because it rewrote the whole file.\n * Measured in M93's adversarial review (H2): after an append over a truncated file, the\n * just-written record was no longer readable.\n *\n * Reads **one byte**, not the file.\n */\nfunction needsLineBreakBefore(path: string): boolean {\n let fd: number;\n try {\n fd = openSync(path, \"r\");\n } catch {\n return false; // the file does not exist yet: nothing to splice onto\n }\n try {\n const size = fstatSync(fd).size;\n if (size === 0) return false;\n const buf = Buffer.alloc(1);\n readSync(fd, buf, 0, 1, size - 1);\n return buf[0] !== 0x0a;\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Read the set of keys from an existing JSONL file for which `keyFn(parsed)`\n * returns a non-empty string. Used to resume a crashed batch by skipping rows\n * already persisted with a successful result. A trailing partial line from an\n * interrupted append is tolerated (skipped, not thrown), and a missing file\n * yields an empty set.\n *\n * reference: swebench-batch.ts:113 (readDoneIds), :129 (success-only),\n * :131 (tolerate partial line).\n */\nexport function readJsonlIds(\n path: string,\n keyFn: (parsed: Record<string, unknown>) => string | undefined,\n): Set<string> {\n const done = new Set<string>();\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return done; // no file yet → nothing done\n }\n for (const rawLine of text.split(\"\\n\")) {\n // A trailing partial line from an interrupted run parses to undefined → skipped.\n const parsed = tryParseObjectLine(rawLine.trim());\n if (parsed === undefined) continue;\n const key = keyFn(parsed);\n if (typeof key === \"string\" && key.length > 0) done.add(key);\n }\n return done;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/file-lock.ts","../src/internal/persistence/jsonl.ts"],"names":["diag","withCwdMutex","readFileSync","path","mkdirSync","dirname","openSync","writeSync","closeSync","fstatSync","readSync"],"mappings":";;;;;;;;AAiCA,IAAI,MAAA;AACJ,IAAI,aAAA,GAAgB,KAAA;AACpB,IAAI,gBAAA,GAAmB,KAAA;AAEvB,IAAI,WAAA;AAGJ,SAAS,eAAe,GAAA,EAAuB;AAC7C,EAAA,MAAM,OAAQ,GAAA,EAA+C,IAAA;AAC7D,EAAA,OAAO,IAAA,KAAS,0BAA0B,IAAA,KAAS,kBAAA;AACrD;AAgBA,SAAS,wBAAwB,GAAA,EAAsB;AACrD,EAAA,MAAM,WAAA,GACJ,wGAAA;AACF,EAAA,IAAI,cAAA,CAAe,GAAG,CAAA,EAAG;AACvB,IAAA,OAAO,gDAAgD,WAAW,CAAA;AAAA,CAAA;AAAA,EACpE;AACA,EAAA,MAAM,OAAQ,GAAA,EAA+C,IAAA;AAC7D,EAAA,MAAM,SAAS,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC9D,EAAA,OACE,CAAA,iDAA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C,CAAA;AAC1B,IAAAC,WAAA,CAAS,EAAA,EAAI,GAAA,EAAK,CAAA,EAAG,CAAA,EAAG,OAAO,CAAC,CAAA;AAChC,IAAA,OAAO,GAAA,CAAI,CAAC,CAAA,KAAM,EAAA;AAAA,EACpB,CAAA,SAAE;AACA,IAAAF,YAAA,CAAU,EAAE,CAAA;AAAA,EACd;AACF;AAYO,SAAS,YAAA,CACd,MACA,KAAA,EACa;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAON,eAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,KAAA,MAAW,OAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,EAAG;AAEtC,IAAA,MAAM,MAAA,GAAS,kBAAA,CAAmB,OAAA,CAAQ,IAAA,EAAM,CAAA;AAChD,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,IAAA,IAAI,OAAO,QAAQ,QAAA,IAAY,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-UU36SHFY.cjs","sourcesContent":["/**\n * Cross-process file lock helper (ADR D61).\n *\n * Uses `proper-lockfile` (optional peer dep) for cross-process locks. When\n * the peer dep is absent, falls back to `withCwdMutex` (in-process only)\n * with a one-shot stderr warning.\n *\n * EC-1 fix: uses a companion `<path>.lock` file with `realpath: false` so\n * `withFileLock` works even when the target `path` does not exist yet.\n * Without this, fresh installs that lock-then-create would crash with ENOENT.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { withCwdMutex } from \"./cwd-mutex.js\";\n\ninterface ProperLockfileModule {\n lock: (file: string, options: ProperLockfileOptions) => Promise<() => Promise<void>>;\n}\n\ninterface ProperLockfileOptions {\n lockfilePath?: string;\n realpath?: boolean;\n stale?: number;\n retries?: {\n retries: number;\n factor?: number;\n minTimeout?: number;\n maxTimeout?: number;\n };\n}\n\nlet cached: ProperLockfileModule | null | undefined;\nlet warnedMissing = false;\nlet warnedStructural = false;\n/** Why the import failed, kept so the warning can report the observation instead of a guess (#174). */\nlet loadFailure: unknown;\n\n/** Node reports a missing module as `ERR_MODULE_NOT_FOUND` (ESM loader) or `MODULE_NOT_FOUND` (CJS). */\nfunction isModuleAbsent(err: unknown): boolean {\n const code = (err as { code?: unknown } | null | undefined)?.code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\n/**\n * #174 — build the fallback warning from what actually happened.\n *\n * This used to always read \"proper-lockfile not installed\", because the import was wrapped in a\n * bare `catch` that discarded the error (Unbreakable Rule 8: a swallowed error is the dangerous\n * kind). A consumer whose package WAS installed, declared and resolvable spent a debugging session\n * re-verifying the install, because the message named a cause the code had never checked.\n *\n * Absence is now the only case that claims absence. Every other failure — a broken install, an\n * interop problem, a bundler that rewrote the specifier — reports its own code and message, which\n * is what points at the real cause.\n *\n * @internal\n */\nfunction describeLockLoadFailure(err: unknown): string {\n const consequence =\n \"cross-process file lock unavailable — concurrent processes over the same file are NOT serialized.\";\n if (isModuleAbsent(err)) {\n return `[theokit-sdk] proper-lockfile not installed; ${consequence} Install with: pnpm add proper-lockfile\\n`;\n }\n const code = (err as { code?: unknown } | null | undefined)?.code;\n const detail = err instanceof Error ? err.message : String(err);\n return (\n `[theokit-sdk] proper-lockfile could not be loaded${code !== undefined ? ` (${String(code)})` : \"\"}: ` +\n `${detail}. ${consequence} The package resolves for the SDK but failed to load — check bundling ` +\n \"and module-format interop before re-checking the install.\\n\"\n );\n}\n\n/** Test seam for the message builder — NOT in the public barrel. @internal */\nexport function __TESTING__describeLockLoadFailure(err: unknown): string {\n return describeLockLoadFailure(err);\n}\n\nasync function getProperLockfile(): Promise<ProperLockfileModule | null> {\n if (cached !== undefined) return cached;\n try {\n const mod = await import(\"proper-lockfile\");\n // T5.9 — supply-chain hardening: validate the imported module\n // exposes the API surface we depend on BEFORE caching it. A\n // tampered or incompatible version that lacks `lock`/`unlock`\n // functions gets treated as \"not installed\" with an advisory\n // warning — never silently used.\n if (!validateLockModule(mod)) {\n if (!warnedStructural) {\n warnedStructural = true;\n diag(\n \"[theokit-sdk] proper-lockfile: imported module does NOT expose \" +\n \"the expected `lock`/`unlock` API surface. This may indicate a \" +\n \"supply-chain compromise or an incompatible major version. \" +\n \"Falling back to in-process mutex (no cross-process safety). \" +\n \"Reinstall with: pnpm add proper-lockfile@^11\\n\",\n );\n }\n cached = null;\n return cached;\n }\n cached = mod as ProperLockfileModule;\n } catch (err) {\n // #174 — keep WHY. Discarding it here is what made the fallback warning assert a cause it had\n // never observed, and sent a consumer to re-check an install that was already correct.\n loadFailure = err;\n cached = null;\n }\n return cached;\n}\n\n/**\n * T5.9 — Structural validation of the dynamically-imported\n * `proper-lockfile` module. Verifies the API surface we depend on\n * (`lock` and `unlock` as functions) is present. Pure function —\n * never throws, never mutates, never performs I/O.\n *\n * Exported via `__TESTING__validateLockModule` seam so unit tests\n * can drive the check without spinning up the dynamic import.\n *\n * @internal\n */\nfunction validateLockModule(mod: unknown): boolean {\n if (mod === null || mod === undefined || typeof mod !== \"object\") return false;\n const m = mod as Record<string, unknown>;\n return typeof m.lock === \"function\" && typeof m.unlock === \"function\";\n}\n\n/**\n * T5.9 — Test seam: expose the structural validator for unit tests.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__validateLockModule(mod: unknown): boolean {\n return validateLockModule(mod);\n}\n\n/**\n * T5.9 — Test seam: reset the module cache + warning flags between\n * tests so each test starts fresh. NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__resetFileLockCache(): void {\n cached = undefined;\n warnedMissing = false;\n warnedStructural = false;\n loadFailure = undefined;\n}\n\n/**\n * Retry and staleness tuning for `withFileLock`.\n *\n * Every field is optional and the defaults are applied per call, so `undefined` means the default\n * rather than \"no limit\". They are handed to `proper-lockfile` and have NO effect on the fallback\n * path: when that package is absent, `withFileLock` degrades to the in-process mutex, which\n * queues indefinitely and never goes stale.\n *\n * `stale` (default 30000 ms) is how old a lock file must be before it is treated as abandoned by a\n * dead process and broken. Setting it below the longest a legitimate holder can run is what turns\n * a slow operation into two concurrent ones.\n *\n * `retries` (default 5) is the number of acquisition attempts AFTER the first, and `retryFactor`\n * (default 1.5) the backoff multiplier between them. The per-attempt wait is clamped to\n * 100–5000 ms, which the caller cannot change. Exhausting the retries rejects — it does not fall\n * through to running `fn` unlocked.\n *\n * @public — re-exported from the semver-protected `@theokit/sdk/persistence` barrel, and (for\n * back-compat) from the semver-exempt `@theokit/sdk/internal/persistence` alias.\n */\nexport interface FileLockOptions {\n /** Stale lock timeout in ms. Default 30_000 (30s). */\n stale?: number;\n /** Max retries on busy lock. Default 5. */\n retries?: number;\n /** Backoff factor between retries. Default 1.5. */\n retryFactor?: number;\n}\n\n/**\n * Run `fn` while holding an OS-level cross-process lock on `path`.\n *\n * If `proper-lockfile` is installed, uses it with a companion `<path>.lock`\n * file (`realpath: false`, so target file does NOT need to exist yet).\n * Otherwise falls back to in-process `withCwdMutex` and prints a one-shot\n * stderr warning telling the user to install `proper-lockfile` for\n * cross-process safety.\n *\n * The lock is released even when `fn` throws.\n *\n */\nexport async function withFileLock<T>(\n path: string,\n fn: () => Promise<T>,\n options?: FileLockOptions,\n): Promise<T> {\n const lib = await getProperLockfile();\n\n if (lib === null) {\n // #174 — stay silent when the structural check already explained itself. Emitting \"not\n // installed\" on top of \"does not expose lock/unlock\" would be two contradictory diagnoses of\n // one failure, and the reader has no way to tell which is true.\n if (!warnedMissing && !warnedStructural) {\n warnedMissing = true;\n diag(describeLockLoadFailure(loadFailure));\n }\n return withCwdMutex(`file-lock:${path}`, fn);\n }\n\n // proper-lockfile errors immediately on same-process concurrent acquire\n // (\"Lock file is already being held\"). Wrap with cwd-mutex first so\n // in-process callers queue and only ONE thread at a time enters the\n // cross-process acquire path. Combined: full in-process + cross-process\n // serialization.\n return withCwdMutex(`file-lock:${path}`, async () => {\n const release = await lib.lock(path, {\n // EC-1: companion lockfile, target path may not exist yet.\n lockfilePath: `${path}.lock`,\n realpath: false,\n stale: options?.stale ?? 30_000,\n retries: {\n retries: options?.retries ?? 5,\n factor: options?.retryFactor ?? 1.5,\n minTimeout: 100,\n maxTimeout: 5_000,\n },\n });\n\n try {\n return await fn();\n } finally {\n await release();\n }\n });\n}\n\n/**\n * Test helper — resets the cached proper-lockfile module + warning flag.\n * Allows tests to simulate \"module absent\" by clearing cache then\n * monkey-patching the dynamic import resolution.\n *\n * @internal\n */\nexport function _resetFileLockCacheForTesting(): void {\n cached = undefined;\n warnedMissing = false;\n}\n","/**\n * Durable JSONL primitives shared by the eval harness (M6).\n *\n * - `loadJsonl` — generic dataset reader (split/trim/skip-blank/parse) with a\n * line-numbered {@link JsonlParseError}. The dataset SCHEMA is the caller's\n * concern via `map` (M6 ADR D3) — this module owns only the parse.\n * - `appendJsonl` / `readJsonlIds` — crash-durable, resumable batch persistence\n * (M6 ADR D1): each record is appended as one whole `\\n`-terminated line the\n * instant it is produced, and a re-run resumes by skipping already-keyed rows.\n *\n * reference: knowledge-base/references/theocode-eval/lib/swebench-dataset.ts:82\n * (parseJsonl + line-N error) and swebench-batch.ts:113,205 (resume + per-line\n * flush).\n *\n * @internal\n */\nimport {\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/** Raised when a JSONL line is not valid JSON or is not a JSON object. Carries the 1-based line number. */\nexport class JsonlParseError extends Error {\n constructor(\n message: string,\n readonly line: number,\n ) {\n super(message);\n this.name = \"JsonlParseError\";\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Parse a single trimmed line to a plain object, or `undefined` if blank / invalid / non-object. */\nfunction tryParseObjectLine(line: string): Record<string, unknown> | undefined {\n if (line.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n return isPlainObject(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a JSONL file into rows. Blank lines are skipped. A malformed or\n * non-object line throws {@link JsonlParseError} naming the 1-based line. When\n * `map` is provided, each raw object is mapped to the typed row (the SWE-bench\n * schema lives in the caller's `map`, per M6 ADR D3).\n */\nexport function loadJsonl<T = Record<string, unknown>>(\n path: string,\n opts: {\n map?: (raw: Record<string, unknown>, lineNumber: number) => T;\n /**\n * M81 — tolerate a truncated LAST line (a crash artifact: the process died mid-write).\n *\n * Opt-in on purpose. As a default it would also swallow corruption in the MIDDLE of the file,\n * turning loud data loss into silent data loss — the wrong trade for a session store.\n */\n tolerateTrailingPartialLine?: boolean;\n } = {},\n): T[] {\n const lines = readFileSync(path, \"utf8\").split(\"\\n\");\n const out: T[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n const lineNumber = i + 1;\n const line = (lines[i] ?? \"\").trim();\n if (line.length === 0) continue;\n // M81 — `undefined` = a tolerated invalid line (the last one, truncated by a crash). Any other\n // invalid line has already thrown inside `parseLine`.\n const parsed = parseLine(\n line,\n lineNumber,\n opts.tolerateTrailingPartialLine === true && lineNumber === lines.length,\n );\n if (parsed === undefined) break;\n out.push(opts.map ? opts.map(parsed, lineNumber) : (parsed as unknown as T));\n }\n return out;\n}\n\n/**\n * Parses ONE line, returning `undefined` when it is a tolerated truncated last line.\n *\n * Extracted because `loadJsonl` went over the cognitive-complexity ceiling once it gained the\n * tolerance — and because parsing a line and iterating a file are two responsibilities that were\n * only together out of habit.\n */\nfunction parseLine(\n line: string,\n lineNumber: number,\n tolerate: boolean,\n): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n if (tolerate) return undefined;\n throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);\n }\n if (!isPlainObject(parsed)) {\n throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);\n }\n return parsed;\n}\n\n/**\n * Append one record as a whole `\\n`-terminated JSON line. Creates the parent dir\n * if missing. `appendFileSync` is synchronous, so within a single Node process\n * the event loop serializes writes and each call writes its line atomically —\n * interleave-safe for the bounded-concurrency batch runner.\n *\n * reference: swebench-batch.ts:192 (mkdir-before-append), :205 (per-line flush).\n */\nexport function appendJsonl(path: string, record: unknown): void {\n // T2.4 — `0o700` for the same reason the file below is `0o600`, and it is the half M93 missed. A\n // private file inside a group-writable directory can be replaced wholesale, and the replacement's\n // mode is whatever the writer chose. Under `umask 002` this directory was born `0775`.\n //\n // The directory sits under `~/.theokit`, shared with the credential and trust stores, and the\n // framework already wrote the diagnosis while fixing a sibling (`@theokit/agents\n // config/trust-store.ts:157-161`): the mode argument is a no-op on a directory that already\n // exists, \"and this one is shared with the SDK's transcript root — whoever creates it first sets\n // the permissions\". Whoever creates it first is usually THIS function, because a session writes a\n // transcript before it ever touches a credential. So `assertSecureModes` was not wrong to demand a\n // private directory; this path was wrong to produce one that fails it, depending on run order.\n //\n // Creation-time only, deliberately: repairing a pre-existing directory means `stat` + `chmod` on\n // every append, and this is the hot path of every session. The pre-existing case is what\n // `assertSecureModes` is for.\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const prefix = needsLineBreakBefore(path) ? \"\\n\" : \"\";\n // M93 (adversarial review, H1) — `0o600`. `appendFileSync` takes no `mode`, so the permission came\n // from the umask: under `umask 022` the transcript was born `0664`, world-readable. The previous\n // path (`replaceFileAtomic`) pinned `0o600` on purpose — \"holds the FULL in-flight content\n // (credential snapshots, OAuth tokens)\" (`atomic-write.ts:107`) — and switching to append lost\n // that silently. The same class had already been caught in the consumer (`atomic-sync.ts`, M88\n // HIGH-1).\n //\n // `mode` only applies on CREATION; a pre-existing file keeps whatever permission it already has.\n const fd = openSync(path, \"a\", 0o600);\n try {\n writeSync(fd, `${prefix}${JSON.stringify(record)}\\n`);\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Does the file end without a `\\n`? Then the last line is truncated — a crash mid-append.\n *\n * Without this check the next append **glues** itself onto the middle of the broken line, producing\n * an invalid line the reader discards: the NEW record disappears along with the partial one. The\n * previous path (read-modify-write) self-healed from this because it rewrote the whole file.\n * Measured in M93's adversarial review (H2): after an append over a truncated file, the\n * just-written record was no longer readable.\n *\n * Reads **one byte**, not the file.\n */\nfunction needsLineBreakBefore(path: string): boolean {\n let fd: number;\n try {\n fd = openSync(path, \"r\");\n } catch {\n return false; // the file does not exist yet: nothing to splice onto\n }\n try {\n const size = fstatSync(fd).size;\n if (size === 0) return false;\n const buf = Buffer.alloc(1);\n readSync(fd, buf, 0, 1, size - 1);\n return buf[0] !== 0x0a;\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Read the set of keys from an existing JSONL file for which `keyFn(parsed)`\n * returns a non-empty string. Used to resume a crashed batch by skipping rows\n * already persisted with a successful result. A trailing partial line from an\n * interrupted append is tolerated (skipped, not thrown), and a missing file\n * yields an empty set.\n *\n * reference: swebench-batch.ts:113 (readDoneIds), :129 (success-only),\n * :131 (tolerate partial line).\n */\nexport function readJsonlIds(\n path: string,\n keyFn: (parsed: Record<string, unknown>) => string | undefined,\n): Set<string> {\n const done = new Set<string>();\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return done; // no file yet → nothing done\n }\n for (const rawLine of text.split(\"\\n\")) {\n // A trailing partial line from an interrupted run parses to undefined → skipped.\n const parsed = tryParseObjectLine(rawLine.trim());\n if (parsed === undefined) continue;\n const key = keyFn(parsed);\n if (typeof key === \"string\" && key.length > 0) done.add(key);\n }\n return done;\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkVKJ7V7EB_cjs = require('./chunk-VKJ7V7EB.cjs');
4
- var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
4
+ var chunk4ZHTIJNE_cjs = require('./chunk-4ZHTIJNE.cjs');
5
5
  var crypto = require('crypto');
6
6
  var fs = require('fs');
7
7
  var path = require('path');
8
8
 
9
- var PathTraversalError = class extends chunkK3FW2XZD_cjs.ConfigurationError {
9
+ var PathTraversalError = class extends chunk4ZHTIJNE_cjs.ConfigurationError {
10
10
  name = "PathTraversalError";
11
11
  constructor(input, resolvedPath) {
12
12
  super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
@@ -14,7 +14,7 @@ var PathTraversalError = class extends chunkK3FW2XZD_cjs.ConfigurationError {
14
14
  });
15
15
  }
16
16
  };
17
- var ForbiddenPathError = class extends chunkK3FW2XZD_cjs.ConfigurationError {
17
+ var ForbiddenPathError = class extends chunk4ZHTIJNE_cjs.ConfigurationError {
18
18
  name = "ForbiddenPathError";
19
19
  constructor(path) {
20
20
  super(
@@ -188,18 +188,18 @@ function rejectParentTraversal(input, normalized) {
188
188
  function sanitizeIdentifier(input, options) {
189
189
  const maxLen = options?.maxLen ?? 64;
190
190
  if (input.length === 0 || input.length > maxLen) {
191
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
191
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
192
192
  code: "invalid_identifier"
193
193
  });
194
194
  }
195
195
  const controlChar = firstControlCharLabel(input);
196
196
  if (controlChar !== void 0) {
197
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier contains ${controlChar}: "${input}"`, {
197
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Identifier contains ${controlChar}: "${input}"`, {
198
198
  code: "invalid_identifier"
199
199
  });
200
200
  }
201
201
  if (!IDENTIFIER_PATTERN.test(input)) {
202
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
202
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
203
203
  code: "invalid_identifier"
204
204
  });
205
205
  }
@@ -207,7 +207,7 @@ function sanitizeIdentifier(input, options) {
207
207
  }
208
208
  function safeFilenameForId(id, options) {
209
209
  if (id.length === 0) {
210
- throw new chunkK3FW2XZD_cjs.ConfigurationError("Filename id must be a non-empty string", {
210
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError("Filename id must be a non-empty string", {
211
211
  code: "invalid_filename_id"
212
212
  });
213
213
  }
@@ -227,5 +227,5 @@ exports.safeFilenameForId = safeFilenameForId;
227
227
  exports.safePathJoin = safePathJoin;
228
228
  exports.sanitizeIdentifier = sanitizeIdentifier;
229
229
  exports.validateArtifactPath = validateArtifactPath;
230
- //# sourceMappingURL=chunk-R3UPQFKK.cjs.map
231
- //# sourceMappingURL=chunk-R3UPQFKK.cjs.map
230
+ //# sourceMappingURL=chunk-V2BOS4WF.cjs.map
231
+ //# sourceMappingURL=chunk-V2BOS4WF.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/security/path-guard.ts"],"names":["ConfigurationError","atOrInsideRoot","resolve","path","realpathSync","lstatSync","readlinkSync","dirname","createHash"],"mappings":";;;;;;;;AAgCO,IAAM,kBAAA,GAAN,cAAiCA,oCAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,WAAA,CAAY,OAAe,YAAA,EAAsB;AAC/C,IAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,KAAK,CAAA,QAAA,EAAM,YAAY,CAAA,CAAA,EAAI;AAAA,MAC1D,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACF;AAYO,IAAM,kBAAA,GAAN,cAAiCA,oCAAA,CAAmB;AAAA,EACvC,IAAA,GAAe,oBAAA;AAAA,EAEjC,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA;AAAA,MACE,SAAS,IAAI,CAAA,qFAAA,CAAA;AAAA,MACb;AAAA,Q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M;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,MAAM,WAAA,EAAY;AAC3B;AAwBO,SAAS,iBAAA,CAAkB,IAAY,OAAA,EAAuC;AACnF,EAAA,IAAI,EAAA,CAAG,WAAW,CAAA,EAAG;AACnB,IAAA,MAAM,IAAIA,qCAAmB,wCAAA,EAA0C;AAAA,MACrE,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,GAAA;AAClC,EAAA,MAAM,KAAA,GAAQ,GAAG,WAAA,EAAY;AAC7B,EAAA,IAAI,MAAM,MAAA,IAAU,MAAA,IAAU,kBAAA,CAAmB,IAAA,CAAK,KAAK,CAAA,EAAG;AAC5D,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,CAAA,EAAA,EAAKQ,iBAAA,CAAW,QAAQ,CAAA,CAAE,MAAA,CAAO,EAAE,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACxE","file":"chunk-R3UPQFKK.cjs","sourcesContent":["/**\n * Canonical path-guard module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { atOrInsideRoot } from \"../runtime/context/path-containment.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Is `target` the same as `base`, or strictly under it?\n *\n * The prefix must not double the separator. `resolve` strips a trailing `sep` from every base\n * EXCEPT the filesystem root, where `resolve(sep) === sep`; there `base + sep` would be `//`, which\n * no absolute path starts with, so a root base rejected EVERY path (#149). Only the root takes that\n * branch — for any other base the prefix is unchanged, so containment is not weakened.\n *\n * Both containment checks in this module go through here: they had the same defect and were fixed\n * one at a time, which is exactly how the two drifted apart in the first place.\n *\n * Both arguments MUST already be resolved absolute paths.\n */\nfunction isInside(target: string, base: string): boolean {\n // B-117 — compared after symlink resolution, via the shared rule. A prefix test judges a link by\n // its NAME: `<base>/link/x` where `link` points outside is lexically inside and physically not.\n // Measured reachable from the plugin manager and the MCP client before this was changed.\n //\n // The root itself stays allowed, which `insideRoot` alone does not answer: it returns false for\n // `target === base` (correct for its own caller, wrong here, where `safePathJoin(base)` with no\n // parts must return `base`). Kept as an explicit second clause rather than by weakening the\n // shared rule for everyone.\n return atOrInsideRoot(target, base);\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n // T5.5 — NUL byte + C0/DEL control char rejection at the boundary.\n // Apply before path resolution so a malicious input never reaches\n // `resolve` (which on some platforms behaved unexpectedly with NUL\n // and in N-API callers historically silently truncated).\n rejectNulAndControlChars(base, \"base\");\n for (const part of parts) {\n rejectNulAndControlChars(part, \"path segment\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (!isInside(target, baseResolved)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * T5.5 — the operator-legible label for the first NUL (`\\x00`), C0 control char (`\\x01-\\x1F`) or\n * DEL (`\\x7F`) in `input`, or `undefined` when it carries none. Centralizes the scan so every\n * public path-guard / sanitize entrypoint shares one definition of \"control character\".\n *\n * Detection is separated from the throw so the two callers can share the scan and the precise\n * diagnostic while each raising the error ITS OWN contract documents (#368) — a path guard reports\n * a traversal, an identifier validator reports an invalid identifier. Before that split both threw\n * `PathTraversalError`, which made an identifier validator's error class depend on the bytes of the\n * input it was handed.\n *\n * @internal\n */\nfunction firstControlCharLabel(input: string): string | undefined {\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n return code === 0x00 ? \"<nul-byte>\" : `<control-char-0x${code.toString(16)}>`;\n }\n }\n return undefined;\n}\n\n/**\n * Reject any path-shaped input carrying a NUL or control character, as `PathTraversalError` — the\n * same shape as every other path-shape rejection, so callers do not learn a second error class.\n *\n * @internal\n */\nfunction rejectNulAndControlChars(input: string, role: string): void {\n const label = firstControlCharLabel(input);\n if (label !== undefined) throw new PathTraversalError(`${role}: ${input}`, label);\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // T5.5 — reject NUL / control chars before any FS call (a NUL byte\n // in the path used to silently truncate at the C boundary on legacy\n // libc — defense in depth even on modern Node).\n rejectNulAndControlChars(path, \"path\");\n rejectNulAndControlChars(base, \"base\");\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (!isInside(resolved, baseResolved)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n// T5.6 — top-level credential dot-dirs / dot-files. Matching against\n// the FIRST path segment (lowercase). Adding any entry here costs a\n// CHANGELOG note + an explicit case-fold test (entries are lowercased\n// at module load).\nconst SENSITIVE_FIRST_SEGMENTS = new Set([\n \".ssh\",\n \".aws\",\n \".docker\",\n \".kube\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — credential basenames blocked at ANY depth (lowercase). Catches\n// the developer-laptop case where an agent recurses into a subdir.\nconst SENSITIVE_BASENAMES = new Set([\n \"id_rsa\",\n \"id_ed25519\",\n \"id_ecdsa\",\n \"id_dsa\",\n \"authorized_keys\",\n \"known_hosts\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — extension suffixes blocked at ANY depth (lowercase). Covers\n// the entire `*.pem` / `*.key` private-material family.\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // T5.6 — lowercase normalization defeats case-only bypass on\n // case-insensitive filesystems (Windows/macOS-default) where `.ENV`\n // and `.env` map to the same inode but a case-sensitive string\n // check passes the former.\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").toLowerCase();\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n if (isForbiddenFirstSegment(segments[0]!)) return true;\n if (isForbiddenBasename(segments[segments.length - 1]!)) return true;\n return false;\n}\n\nfunction isForbiddenFirstSegment(first: string): boolean {\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n if (first === \".git\" || first === \"node_modules\" || first === \".theo\") return true;\n return SENSITIVE_FIRST_SEGMENTS.has(first);\n}\n\nfunction isForbiddenBasename(basename: string): boolean {\n if (LOCK_FILES.has(basename)) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n for (const suffix of SENSITIVE_SUFFIXES) {\n if (basename.endsWith(suffix)) return true;\n }\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * T1.4 — validate a relative artifact path string BEFORE it is used to look\n * up a fixture or to fetch from PaaS. Rejects every well-known traversal\n * vector at the boundary, throwing `PathTraversalError`.\n *\n * Vectors rejected:\n * - classic `..` parent-directory traversal (any segment).\n * - backslash separators (Windows-style `..\\\\windows`).\n * - URL-encoded `%2e%2e` / `%2E%2E` (double-decoded traversal).\n * - NUL byte injection (`\\x00`).\n * - Windows drive letter prefix (`C:`, `D:\\\\...`).\n * - Home-tilde expansion (`~/`, `~root/...`).\n * - Absolute paths starting with `/`.\n *\n * Does NOT touch the filesystem — the call is shape-only. Live symlink\n * traversal protection happens via `assertNoSymlinkEscape` at the FS-resolve\n * boundary.\n *\n * @param input - Caller-supplied artifact path.\n * @throws `PathTraversalError` on any rejection.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/security` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function validateArtifactPath(input: string): void {\n rejectKnownPrefixVectors(input);\n const normalized = decodeAndNormalize(input);\n rejectParentTraversal(input, normalized);\n}\n\nfunction rejectKnownPrefixVectors(input: string): void {\n if (input.includes(\"\\x00\")) {\n throw new PathTraversalError(input, \"<nul-byte>\");\n }\n if (input.startsWith(\"/\") || input.startsWith(\"~\")) {\n throw new PathTraversalError(input, input);\n }\n if (/^[A-Za-z]:[\\\\/]?/.test(input)) {\n throw new PathTraversalError(input, input);\n }\n}\n\nfunction decodeAndNormalize(input: string): string {\n // URL-encoded traversal — 2 passes catches `%252e%252e`.\n // Malformed sequences (decodeURIComponent throws) are themselves a rejection.\n let decoded = input;\n for (let i = 0; i < 2; i += 1) {\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n throw new PathTraversalError(input, \"<malformed-url-encoding>\");\n }\n }\n // Normalize backslash to forward slash before segment-walking.\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction rejectParentTraversal(input: string, normalized: string): void {\n for (const segment of normalized.split(\"/\")) {\n if (segment === \"..\" || segment === \"..%00\") {\n throw new PathTraversalError(input, normalized);\n }\n }\n // Defense in depth: literal `..` anywhere in the normalized string.\n if (normalized.includes(\"..\")) {\n throw new PathTraversalError(input, normalized);\n }\n}\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * ONE error class leaves this function: `ConfigurationError` with code\n * `invalid_identifier`, for every rejection — length out of range, a path\n * separator, `..`, a space, a leading `-`, and a NUL / C0 control char / DEL\n * alike. A caller can branch on that code and know it has covered the whole\n * rejection surface.\n *\n * Before #368 the control-char branch threw `PathTraversalError` instead, which\n * made the error CLASS a function of the attacker's bytes; the message still names\n * the offending byte, which is the part that was worth keeping.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on every rejection.\n */\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n // T5.5 — explicit NUL / control char rejection ahead of the generic pattern check. The\n // IDENTIFIER_PATTERN regex already excludes these (they are not in `[a-z0-9\\-_]`); naming the\n // offending byte gives operators a precise diagnostic instead of the generic \"invalid characters\"\n // message, which is what makes a prompt-injection trace legible (Rule 3).\n //\n // #368 — the diagnostic used to arrive as a `PathTraversalError`, because the branch reused\n // `safePathJoin`'s thrower. That made the error CLASS a function of the attacker's bytes: a\n // caller branching on the documented `invalid_identifier` rethrew for any input carrying a\n // control char, so a rejection surfaced as a 500 and the 400/500 split became an oracle. The\n // detection is shared; the error each contract documents is not.\n const controlChar = firstControlCharLabel(input);\n if (controlChar !== undefined) {\n throw new ConfigurationError(`Identifier contains ${controlChar}: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n\n/**\n * Convert ANY opaque id (agent id, run id, conversation id, namespace, email,\n * arbitrary string) into a deterministic, filesystem-safe filename component.\n *\n * Unlike {@link sanitizeIdentifier} (which THROWS on non-conforming input),\n * this is a total function: it NEVER throws on a non-empty string. It returns\n * the lowercased id verbatim when it already matches the safe grammar\n * `^[a-z0-9][a-z0-9-_]*$` and fits `maxLen` (so UUIDs, hashes, and slugs stay\n * human-readable), otherwise a deterministic `h-<16 hex>` sha256 token\n * (collision-resistant and always a valid filename). The output charset is\n * always `[a-z0-9_-]`, safe as a literal path segment on every filesystem.\n *\n * @param id - any opaque identifier (must be a non-empty string)\n * @param options.maxLen - max length for the passthrough branch (default 128).\n * Ids longer than this are hashed; the hash token itself is always short.\n * @throws ConfigurationError (code `invalid_filename_id`) only on empty input.\n *\n * @example\n * safeFilenameForId(\"550e8400-e29b-41d4-a716-446655440000\") // passthrough\n * safeFilenameForId(\"user@example.com\") // \"h-<16hex>\"\n *\n */\nexport function safeFilenameForId(id: string, options?: { maxLen?: number }): string {\n if (id.length === 0) {\n throw new ConfigurationError(\"Filename id must be a non-empty string\", {\n code: \"invalid_filename_id\",\n });\n }\n const maxLen = options?.maxLen ?? 128;\n const lower = id.toLowerCase();\n if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {\n return lower;\n }\n return `h-${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 16)}`;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/security/path-guard.ts"],"names":["ConfigurationError","atOrInsideRoot","resolve","path","realpathSync","lstatSync","read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module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { atOrInsideRoot } from \"../runtime/context/path-containment.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Is `target` the same as `base`, or strictly under it?\n *\n * The prefix must not double the separator. `resolve` strips a trailing `sep` from every base\n * EXCEPT the filesystem root, where `resolve(sep) === sep`; there `base + sep` would be `//`, which\n * no absolute path starts with, so a root base rejected EVERY path (#149). Only the root takes that\n * branch — for any other base the prefix is unchanged, so containment is not weakened.\n *\n * Both containment checks in this module go through here: they had the same defect and were fixed\n * one at a time, which is exactly how the two drifted apart in the first place.\n *\n * Both arguments MUST already be resolved absolute paths.\n */\nfunction isInside(target: string, base: string): boolean {\n // B-117 — compared after symlink resolution, via the shared rule. A prefix test judges a link by\n // its NAME: `<base>/link/x` where `link` points outside is lexically inside and physically not.\n // Measured reachable from the plugin manager and the MCP client before this was changed.\n //\n // The root itself stays allowed, which `insideRoot` alone does not answer: it returns false for\n // `target === base` (correct for its own caller, wrong here, where `safePathJoin(base)` with no\n // parts must return `base`). Kept as an explicit second clause rather than by weakening the\n // shared rule for everyone.\n return atOrInsideRoot(target, base);\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n // T5.5 — NUL byte + C0/DEL control char rejection at the boundary.\n // Apply before path resolution so a malicious input never reaches\n // `resolve` (which on some platforms behaved unexpectedly with NUL\n // and in N-API callers historically silently truncated).\n rejectNulAndControlChars(base, \"base\");\n for (const part of parts) {\n rejectNulAndControlChars(part, \"path segment\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (!isInside(target, baseResolved)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * T5.5 — the operator-legible label for the first NUL (`\\x00`), C0 control char (`\\x01-\\x1F`) or\n * DEL (`\\x7F`) in `input`, or `undefined` when it carries none. Centralizes the scan so every\n * public path-guard / sanitize entrypoint shares one definition of \"control character\".\n *\n * Detection is separated from the throw so the two callers can share the scan and the precise\n * diagnostic while each raising the error ITS OWN contract documents (#368) — a path guard reports\n * a traversal, an identifier validator reports an invalid identifier. Before that split both threw\n * `PathTraversalError`, which made an identifier validator's error class depend on the bytes of the\n * input it was handed.\n *\n * @internal\n */\nfunction firstControlCharLabel(input: string): string | undefined {\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n return code === 0x00 ? \"<nul-byte>\" : `<control-char-0x${code.toString(16)}>`;\n }\n }\n return undefined;\n}\n\n/**\n * Reject any path-shaped input carrying a NUL or control character, as `PathTraversalError` — the\n * same shape as every other path-shape rejection, so callers do not learn a second error class.\n *\n * @internal\n */\nfunction rejectNulAndControlChars(input: string, role: string): void {\n const label = firstControlCharLabel(input);\n if (label !== undefined) throw new PathTraversalError(`${role}: ${input}`, label);\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // T5.5 — reject NUL / control chars before any FS call (a NUL byte\n // in the path used to silently truncate at the C boundary on legacy\n // libc — defense in depth even on modern Node).\n rejectNulAndControlChars(path, \"path\");\n rejectNulAndControlChars(base, \"base\");\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (!isInside(resolved, baseResolved)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n// T5.6 — top-level credential dot-dirs / dot-files. Matching against\n// the FIRST path segment (lowercase). Adding any entry here costs a\n// CHANGELOG note + an explicit case-fold test (entries are lowercased\n// at module load).\nconst SENSITIVE_FIRST_SEGMENTS = new Set([\n \".ssh\",\n \".aws\",\n \".docker\",\n \".kube\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — credential basenames blocked at ANY depth (lowercase). Catches\n// the developer-laptop case where an agent recurses into a subdir.\nconst SENSITIVE_BASENAMES = new Set([\n \"id_rsa\",\n \"id_ed25519\",\n \"id_ecdsa\",\n \"id_dsa\",\n \"authorized_keys\",\n \"known_hosts\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\n// T5.6 — extension suffixes blocked at ANY depth (lowercase). Covers\n// the entire `*.pem` / `*.key` private-material family.\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // T5.6 — lowercase normalization defeats case-only bypass on\n // case-insensitive filesystems (Windows/macOS-default) where `.ENV`\n // and `.env` map to the same inode but a case-sensitive string\n // check passes the former.\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").toLowerCase();\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n if (isForbiddenFirstSegment(segments[0]!)) return true;\n if (isForbiddenBasename(segments[segments.length - 1]!)) return true;\n return false;\n}\n\nfunction isForbiddenFirstSegment(first: string): boolean {\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n if (first === \".git\" || first === \"node_modules\" || first === \".theo\") return true;\n return SENSITIVE_FIRST_SEGMENTS.has(first);\n}\n\nfunction isForbiddenBasename(basename: string): boolean {\n if (LOCK_FILES.has(basename)) return true;\n if (SENSITIVE_BASENAMES.has(basename)) return true;\n for (const suffix of SENSITIVE_SUFFIXES) {\n if (basename.endsWith(suffix)) return true;\n }\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * T1.4 — validate a relative artifact path string BEFORE it is used to look\n * up a fixture or to fetch from PaaS. Rejects every well-known traversal\n * vector at the boundary, throwing `PathTraversalError`.\n *\n * Vectors rejected:\n * - classic `..` parent-directory traversal (any segment).\n * - backslash separators (Windows-style `..\\\\windows`).\n * - URL-encoded `%2e%2e` / `%2E%2E` (double-decoded traversal).\n * - NUL byte injection (`\\x00`).\n * - Windows drive letter prefix (`C:`, `D:\\\\...`).\n * - Home-tilde expansion (`~/`, `~root/...`).\n * - Absolute paths starting with `/`.\n *\n * Does NOT touch the filesystem — the call is shape-only. Live symlink\n * traversal protection happens via `assertNoSymlinkEscape` at the FS-resolve\n * boundary.\n *\n * @param input - Caller-supplied artifact path.\n * @throws `PathTraversalError` on any rejection.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/security` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function validateArtifactPath(input: string): void {\n rejectKnownPrefixVectors(input);\n const normalized = decodeAndNormalize(input);\n rejectParentTraversal(input, normalized);\n}\n\nfunction rejectKnownPrefixVectors(input: string): void {\n if (input.includes(\"\\x00\")) {\n throw new PathTraversalError(input, \"<nul-byte>\");\n }\n if (input.startsWith(\"/\") || input.startsWith(\"~\")) {\n throw new PathTraversalError(input, input);\n }\n if (/^[A-Za-z]:[\\\\/]?/.test(input)) {\n throw new PathTraversalError(input, input);\n }\n}\n\nfunction decodeAndNormalize(input: string): string {\n // URL-encoded traversal — 2 passes catches `%252e%252e`.\n // Malformed sequences (decodeURIComponent throws) are themselves a rejection.\n let decoded = input;\n for (let i = 0; i < 2; i += 1) {\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n throw new PathTraversalError(input, \"<malformed-url-encoding>\");\n }\n }\n // Normalize backslash to forward slash before segment-walking.\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction rejectParentTraversal(input: string, normalized: string): void {\n for (const segment of normalized.split(\"/\")) {\n if (segment === \"..\" || segment === \"..%00\") {\n throw new PathTraversalError(input, normalized);\n }\n }\n // Defense in depth: literal `..` anywhere in the normalized string.\n if (normalized.includes(\"..\")) {\n throw new PathTraversalError(input, normalized);\n }\n}\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * ONE error class leaves this function: `ConfigurationError` with code\n * `invalid_identifier`, for every rejection — length out of range, a path\n * separator, `..`, a space, a leading `-`, and a NUL / C0 control char / DEL\n * alike. A caller can branch on that code and know it has covered the whole\n * rejection surface.\n *\n * Before #368 the control-char branch threw `PathTraversalError` instead, which\n * made the error CLASS a function of the attacker's bytes; the message still names\n * the offending byte, which is the part that was worth keeping.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on every rejection.\n */\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n // T5.5 — explicit NUL / control char rejection ahead of the generic pattern check. The\n // IDENTIFIER_PATTERN regex already excludes these (they are not in `[a-z0-9\\-_]`); naming the\n // offending byte gives operators a precise diagnostic instead of the generic \"invalid characters\"\n // message, which is what makes a prompt-injection trace legible (Rule 3).\n //\n // #368 — the diagnostic used to arrive as a `PathTraversalError`, because the branch reused\n // `safePathJoin`'s thrower. That made the error CLASS a function of the attacker's bytes: a\n // caller branching on the documented `invalid_identifier` rethrew for any input carrying a\n // control char, so a rejection surfaced as a 500 and the 400/500 split became an oracle. The\n // detection is shared; the error each contract documents is not.\n const controlChar = firstControlCharLabel(input);\n if (controlChar !== undefined) {\n throw new ConfigurationError(`Identifier contains ${controlChar}: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n\n/**\n * Convert ANY opaque id (agent id, run id, conversation id, namespace, email,\n * arbitrary string) into a deterministic, filesystem-safe filename component.\n *\n * Unlike {@link sanitizeIdentifier} (which THROWS on non-conforming input),\n * this is a total function: it NEVER throws on a non-empty string. It returns\n * the lowercased id verbatim when it already matches the safe grammar\n * `^[a-z0-9][a-z0-9-_]*$` and fits `maxLen` (so UUIDs, hashes, and slugs stay\n * human-readable), otherwise a deterministic `h-<16 hex>` sha256 token\n * (collision-resistant and always a valid filename). The output charset is\n * always `[a-z0-9_-]`, safe as a literal path segment on every filesystem.\n *\n * @param id - any opaque identifier (must be a non-empty string)\n * @param options.maxLen - max length for the passthrough branch (default 128).\n * Ids longer than this are hashed; the hash token itself is always short.\n * @throws ConfigurationError (code `invalid_filename_id`) only on empty input.\n *\n * @example\n * safeFilenameForId(\"550e8400-e29b-41d4-a716-446655440000\") // passthrough\n * safeFilenameForId(\"user@example.com\") // \"h-<16hex>\"\n *\n */\nexport function safeFilenameForId(id: string, options?: { maxLen?: number }): string {\n if (id.length === 0) {\n throw new ConfigurationError(\"Filename id must be a non-empty string\", {\n code: \"invalid_filename_id\",\n });\n }\n const maxLen = options?.maxLen ?? 128;\n const lower = id.toLowerCase();\n if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {\n return lower;\n }\n return `h-${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 16)}`;\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkNLXOGBRJ_cjs = require('./chunk-NLXOGBRJ.cjs');
4
- var chunkNGESVVJN_cjs = require('./chunk-NGESVVJN.cjs');
3
+ var chunkDKK5QY4C_cjs = require('./chunk-DKK5QY4C.cjs');
4
+ var chunk3FFAEAUJ_cjs = require('./chunk-3FFAEAUJ.cjs');
5
5
  var chunkNINIJCHU_cjs = require('./chunk-NINIJCHU.cjs');
6
- var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
7
- var chunkJTB5Q42C_cjs = require('./chunk-JTB5Q42C.cjs');
6
+ var chunk4ZHTIJNE_cjs = require('./chunk-4ZHTIJNE.cjs');
7
+ var chunkXL7Q7HB2_cjs = require('./chunk-XL7Q7HB2.cjs');
8
8
  var croner = require('croner');
9
9
 
10
10
  // src/internal/cron/run-job.ts
@@ -12,7 +12,7 @@ async function runCronJob(job) {
12
12
  if (job.workflow !== void 0) return job.workflow.run(job.inputData);
13
13
  if (job.agent !== void 0) return runWithEphemeralAgent(job.agent, requireMessage(job));
14
14
  if (job.agentId !== void 0) return runWithExistingAgent(job.agentId, requireMessage(job));
15
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
15
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
16
16
  `Cron job ${job.id} has no target (agent, agentId, or workflow) \u2014 cannot run.`,
17
17
  { code: "cron_no_target" }
18
18
  );
@@ -22,7 +22,7 @@ function isAgentRun(outcome) {
22
22
  }
23
23
  function requireMessage(job) {
24
24
  if (job.message === void 0) {
25
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Cron job ${job.id} is an agent target but has no message.`, {
25
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Cron job ${job.id} is an agent target but has no message.`, {
26
26
  code: "cron_missing_message"
27
27
  });
28
28
  }
@@ -31,7 +31,7 @@ function requireMessage(job) {
31
31
  async function runWithExistingAgent(agentId, message) {
32
32
  const info = await chunkNINIJCHU_cjs.getAgentFacade().get(agentId).catch(() => void 0);
33
33
  if (info === void 0) {
34
- throw new chunkK3FW2XZD_cjs.UnknownAgentError(
34
+ throw new chunk4ZHTIJNE_cjs.UnknownAgentError(
35
35
  `Cron job references agentId "${agentId}" but no such agent is registered. The agent may have been disposed or the process restarted without persisting the agent registry.`,
36
36
  { code: "agent_not_registered" }
37
37
  );
@@ -49,7 +49,7 @@ async function fireCronJobAsTask(job) {
49
49
  const fireTs = Date.now();
50
50
  const taskId = `cron-${job.id}-${fireTs}`;
51
51
  try {
52
- await chunkNGESVVJN_cjs.submit({
52
+ await chunk3FFAEAUJ_cjs.submit({
53
53
  kind: "cron",
54
54
  id: taskId,
55
55
  allowReservedPrefix: true,
@@ -187,13 +187,13 @@ var FIELD_RANGES = [
187
187
  ];
188
188
  function validateCronExpression(cron) {
189
189
  if (typeof cron !== "string" || cron.length === 0) {
190
- throw new chunkK3FW2XZD_cjs.ConfigurationError("Invalid cron expression: empty", {
190
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError("Invalid cron expression: empty", {
191
191
  code: "invalid_cron"
192
192
  });
193
193
  }
194
194
  if (cron.startsWith("@")) {
195
195
  if (!SHORTHANDS.has(cron)) {
196
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Invalid cron expression: unknown shorthand ${cron}`, {
196
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Invalid cron expression: unknown shorthand ${cron}`, {
197
197
  code: "invalid_cron"
198
198
  });
199
199
  }
@@ -201,7 +201,7 @@ function validateCronExpression(cron) {
201
201
  }
202
202
  const fields = cron.trim().split(/\s+/);
203
203
  if (fields.length !== FIELD_RANGES.length) {
204
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
204
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
205
205
  `Invalid cron expression: ${cron} (expected ${FIELD_RANGES.length} fields, got ${fields.length})`,
206
206
  { code: "invalid_cron" }
207
207
  );
@@ -209,7 +209,7 @@ function validateCronExpression(cron) {
209
209
  for (const [index, range] of FIELD_RANGES.entries()) {
210
210
  const field = fields[index];
211
211
  if (!isValidCronField(field, range)) {
212
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {
212
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {
213
213
  code: "invalid_cron"
214
214
  });
215
215
  }
@@ -251,7 +251,7 @@ function validateTimezone(timezone) {
251
251
  try {
252
252
  new Intl.DateTimeFormat("en-US", { timeZone: timezone });
253
253
  } catch {
254
- throw new chunkK3FW2XZD_cjs.ConfigurationError(`Invalid IANA timezone: ${timezone}`, {
254
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(`Invalid IANA timezone: ${timezone}`, {
255
255
  code: "invalid_timezone"
256
256
  });
257
257
  }
@@ -295,7 +295,7 @@ var Cron = class {
295
295
  const job = getJob(jobId);
296
296
  if (job === void 0) {
297
297
  return Promise.reject(
298
- new chunkK3FW2XZD_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" })
298
+ new chunk4ZHTIJNE_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" })
299
299
  );
300
300
  }
301
301
  return Promise.resolve(job);
@@ -335,7 +335,7 @@ var Cron = class {
335
335
  static async run(jobId, _options = {}) {
336
336
  const job = getJob(jobId);
337
337
  if (job === void 0) {
338
- throw new chunkK3FW2XZD_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" });
338
+ throw new chunk4ZHTIJNE_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" });
339
339
  }
340
340
  return runCronJob(job);
341
341
  }
@@ -373,11 +373,11 @@ async function createCronJob(options) {
373
373
  validateCronExpression(options.cron);
374
374
  const timezone = options.timezone ?? "UTC";
375
375
  validateTimezone(timezone);
376
- chunkJTB5Q42C_cjs.resolveApiKey(options.apiKey);
376
+ chunkXL7Q7HB2_cjs.resolveApiKey(options.apiKey);
377
377
  const runtime = detectRuntime(options);
378
378
  const now = Date.now();
379
379
  const job = {
380
- id: chunkNLXOGBRJ_cjs.generateCronId(),
380
+ id: chunkDKK5QY4C_cjs.generateCronId(),
381
381
  cron: options.cron,
382
382
  timezone,
383
383
  enabled: options.enabled ?? true,
@@ -400,25 +400,25 @@ function validateCronTarget(options) {
400
400
  (t) => t !== void 0
401
401
  ).length;
402
402
  if (targets > 1) {
403
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
403
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
404
404
  "agent, agentId, and workflow are mutually exclusive \u2014 pass exactly one target.",
405
405
  { code: "cron_ambiguous_target" }
406
406
  );
407
407
  }
408
408
  if (targets === 0) {
409
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
409
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
410
410
  "Cron job requires exactly one target: agent, agentId, or workflow.",
411
411
  { code: "cron_no_target" }
412
412
  );
413
413
  }
414
414
  if (options.workflow !== void 0 && options.message !== void 0) {
415
- throw new chunkK3FW2XZD_cjs.ConfigurationError(
415
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError(
416
416
  "A workflow cron target takes inputData, not a message \u2014 remove `message`.",
417
417
  { code: "cron_workflow_message" }
418
418
  );
419
419
  }
420
420
  if (options.workflow === void 0 && options.message === void 0) {
421
- throw new chunkK3FW2XZD_cjs.ConfigurationError("An agent cron target requires a message.", {
421
+ throw new chunk4ZHTIJNE_cjs.ConfigurationError("An agent cron target requires a message.", {
422
422
  code: "cron_missing_message"
423
423
  });
424
424
  }
@@ -435,7 +435,7 @@ function detectRuntime(options) {
435
435
  async function updateJobStatus(jobId, enabled) {
436
436
  const existing = getJob(jobId);
437
437
  if (existing === void 0) {
438
- throw new chunkK3FW2XZD_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" });
438
+ throw new chunk4ZHTIJNE_cjs.UnknownAgentError(`Cron job ${jobId} not found`, { code: "unknown_cron_job" });
439
439
  }
440
440
  const updated = {
441
441
  ...existing,
@@ -454,5 +454,5 @@ async function updateJobStatus(jobId, enabled) {
454
454
  }
455
455
 
456
456
  exports.Cron = Cron;
457
- //# sourceMappingURL=chunk-CASUEY42.cjs.map
458
- //# sourceMappingURL=chunk-CASUEY42.cjs.map
457
+ //# sourceMappingURL=chunk-VX4SQ2LY.cjs.map
458
+ //# sourceMappingURL=chunk-VX4SQ2LY.cjs.map