@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/workflow/event-stream.ts","../src/workflow.ts"],"names":[],"mappings":";;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX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AC,CAAA;AAClE,EAAA,OAAO,EAAC;AACV;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-FUL2I7G5.js","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\n/**\n * Fluent step accumulator returned by {@link Workflow.create}. Each method\n * appends a step and returns the SAME builder (mutated in place, never a copy);\n * `.commit()` freezes the list into a {@link Workflow} and mints the id its\n * single-flight lock uses.\n *\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n *\n * You never construct one directly — `Workflow.create(options)` validates the\n * options with Zod and hands it back. Import it from `@theokit/sdk/workflow`; the\n * root `@theokit/sdk` barrel does not export it.\n *\n * How it fails:\n * - Every appending method throws a plain `Error` after `.commit()` —\n * \"Workflow already committed; create a fresh Workflow.create(...) call.\" A\n * builder is single-use.\n * - A step id is validated on the spot by `sanitizeIdentifier`\n * (`^[a-z0-9][a-z0-9-_]*$`, max 64 chars). Every rejection — length, a space,\n * `/`, `..`, a leading `-`, a NUL or control char — throws `ConfigurationError`\n * with code `invalid_identifier`, not a plain `Error` (#368 collapsed a second\n * class that the control-char branch used to raise).\n * - `sleep(durationMs)` throws a plain `Error` on a negative or non-finite value.\n * - A duplicate id anywhere in the tree, including inside `parallel`, `branch`,\n * `foreach` and `dowhile`, throws `WorkflowDuplicateStepIdError` at\n * `.commit()` — not at the `.then()` that introduced it.\n *\n * Traps:\n * - `.then(step)` is a STEP APPENDER, not a promise continuation. That makes the\n * builder a JavaScript thenable, so `await Workflow.create({ ... })` — the\n * shape `await Agent.create({ ... })` trains you into — is a mistake:\n * TypeScript rejects it (TS1320) and plain JavaScript throws an unrelated\n * `TypeError: Cannot read properties of undefined (reading 'length')` out of\n * the id validator. `Workflow.create` is synchronous.\n * - `parallel`, `branch`, `foreach`, `dowhile` and `suspend` widen the output\n * type to `unknown` (or `unknown[]`); only `.then<T>()` and `sleep` carry a\n * type through. The generics are a convenience, not a checked pipeline —\n * nothing verifies that one step's output matches the next step's input.\n * - Auto-generated ids are POSITIONAL (`parallel_2`, `foreach_5`), so inserting a\n * step earlier renames the later ones. Pass `opts.id` for any step whose id you\n * rely on in event streams or resume snapshots.\n */\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\n/**\n * A committed, immutable workflow: a fixed list of steps you can `run`, `stream`\n * or `resume`. Built with `Workflow.create(options)` plus `.commit()`; the\n * constructor is not part of the published surface.\n *\n * import { Workflow, fn } from \"@theokit/sdk/workflow\";\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n * const run = await wf.run({ id: \"x\" }); // run.status, run.output\n *\n * THE IMPORT SPECIFIER MATTERS. `Workflow` is emitted TWICE — once as the\n * `@theokit/sdk/workflow` sub-path entry, and once inside the shared chunk behind\n * the root `@theokit/sdk` barrel. Both declarations carry private fields, so the\n * two are DISTINCT nominal types and TypeScript refuses to pass one where the\n * other is expected:\n *\n * Types have separate declarations of a private property '_options'.\n *\n * Import `Workflow` — and everything that consumes one, such as `workflowStep`\n * and `cloneWorkflow` — from `@theokit/sdk/workflow`, and do not mix the two\n * specifiers in one program. The root barrel re-exports only `Workflow`,\n * `agentStep` and `fn`; the builder, the step helpers, the error classes and every\n * workflow type live on the sub-path. (`workflowAsTool` is exempt: it accepts any\n * `{ run }`-shaped value structurally, so either `Workflow` satisfies it.)\n *\n * How it fails: a step that throws does NOT reject `run()`. The promise resolves\n * with `status: \"failed\"` and the cause on `run.error`; `\"suspended\"` and\n * `\"cancelled\"` are the other non-`\"completed\"` terminals, and an `outputSchema`\n * mismatch also lands as `\"failed\"` (`WorkflowOutputError`) rather than a throw.\n * What DOES throw out of `run()` is pre-flight: `WorkflowAlreadyRunningError` when\n * you pin `WorkflowRunOptions.runId` to one still in flight. `Workflow.resume`\n * throws `WorkflowSnapshotNotFoundError` for an unknown `runId`.\n *\n * Traps:\n * - Without an explicit `runId` each call mints its own, so concurrent runs of\n * the same committed workflow do NOT collide — the single-flight lock only\n * bites when you pin the id yourself.\n * - `stream()` reports progress; its `result` promise is the AUTHORITATIVE\n * outcome. Not every terminal emits a closing event, so a consumer that only\n * drains events can miss a failure. Always `await result`.\n * - `run()` and `stream()` load the executor by dynamic `import()`, so the first\n * call pays a module load and cannot be made synchronous.\n *\n * @public\n */\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":[],"mappings":";;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,MAAA,GAAS,QAAQ,KAAA,EAAM;AAC7B,MAAA,IAAI,MAAA,KAAW,QAAW,MAAA,CAAO,EAAE,OAAO,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAAA,WACzD,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,IACxB,CAAA;AAAA,IACA,GAAA,GAAY;AACV,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,KAAA,GAAQ,IAAA;AACR,MAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAA,CAAO,EAAE,KAAA,EAAO,MAAA,EAAW,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,IACjF,CAAA;AAAA,IACA,IAAA,GAA+C;AAC7C,MAAA,MAAM,QAAA,GAAW,OAAO,KAAA,EAAM;AAC9B,MAAA,IAAI,QAAA,KAA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AAEA,SAAS,WAAA,GAAsB;AAC7B,EAAA,OAAO,UAAA,CAAW,MAAA,CAAO,UAAA,EAAW,CAAE,OAAA,CAAQ,MAAM,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA;AACpE;AAEA,SAAS,cAAc,CAAA,EAA6C;AAClE,EAAA,IAAI,CAAA,CAAE,IAAA,KAAS,UAAA,EAAY,OAAO,CAAA,CAAE,QAAA;AACpC,EAAA,IAAI,CAAA,CAAE,SAAS,QAAA,EAAU;AACvB,IAAA,MAAM,MAAA,GAAS,EAAE,UAAA,CAAW,GAAA,CAAI,CAAC,GAAG,MAAM,CAAA,KAAM,MAAM,CAAA;AACtD,IAAA,OAAO,CAAA,CAAE,aAAa,MAAA,GAAY,CAAC,GAAG,MAAA,EAAQ,CAAA,CAAE,QAAQ,CAAA,GAAI,MAAA;AAAA,EAC9D;AACA,EAAA,IAAI,CAAA,CAAE,IAAA,KAAS,SAAA,IAAa,CAAA,CAAE,IAAA,KAAS,SAAA,EAAW,OAAO,CAAC,CAAC,CAAA,CAAE,IAAI,CAAC,CAAA;AAClE,EAAA,OAAO,EAAC;AACV;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-OSEG74VJ.js","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\n/**\n * Fluent step accumulator returned by {@link Workflow.create}. Each method\n * appends a step and returns the SAME builder (mutated in place, never a copy);\n * `.commit()` freezes the list into a {@link Workflow} and mints the id its\n * single-flight lock uses.\n *\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n *\n * You never construct one directly — `Workflow.create(options)` validates the\n * options with Zod and hands it back. Import it from `@theokit/sdk/workflow`; the\n * root `@theokit/sdk` barrel does not export it.\n *\n * How it fails:\n * - Every appending method throws a plain `Error` after `.commit()` —\n * \"Workflow already committed; create a fresh Workflow.create(...) call.\" A\n * builder is single-use.\n * - A step id is validated on the spot by `sanitizeIdentifier`\n * (`^[a-z0-9][a-z0-9-_]*$`, max 64 chars). Every rejection — length, a space,\n * `/`, `..`, a leading `-`, a NUL or control char — throws `ConfigurationError`\n * with code `invalid_identifier`, not a plain `Error` (#368 collapsed a second\n * class that the control-char branch used to raise).\n * - `sleep(durationMs)` throws a plain `Error` on a negative or non-finite value.\n * - A duplicate id anywhere in the tree, including inside `parallel`, `branch`,\n * `foreach` and `dowhile`, throws `WorkflowDuplicateStepIdError` at\n * `.commit()` — not at the `.then()` that introduced it.\n *\n * Traps:\n * - `.then(step)` is a STEP APPENDER, not a promise continuation. That makes the\n * builder a JavaScript thenable, so `await Workflow.create({ ... })` — the\n * shape `await Agent.create({ ... })` trains you into — is a mistake:\n * TypeScript rejects it (TS1320) and plain JavaScript throws an unrelated\n * `TypeError: Cannot read properties of undefined (reading 'length')` out of\n * the id validator. `Workflow.create` is synchronous.\n * - `parallel`, `branch`, `foreach`, `dowhile` and `suspend` widen the output\n * type to `unknown` (or `unknown[]`); only `.then<T>()` and `sleep` carry a\n * type through. The generics are a convenience, not a checked pipeline —\n * nothing verifies that one step's output matches the next step's input.\n * - Auto-generated ids are POSITIONAL (`parallel_2`, `foreach_5`), so inserting a\n * step earlier renames the later ones. Pass `opts.id` for any step whose id you\n * rely on in event streams or resume snapshots.\n */\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\n/**\n * A committed, immutable workflow: a fixed list of steps you can `run`, `stream`\n * or `resume`. Built with `Workflow.create(options)` plus `.commit()`; the\n * constructor is not part of the published surface.\n *\n * import { Workflow, fn } from \"@theokit/sdk/workflow\";\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n * const run = await wf.run({ id: \"x\" }); // run.status, run.output\n *\n * THE IMPORT SPECIFIER MATTERS. `Workflow` is emitted TWICE — once as the\n * `@theokit/sdk/workflow` sub-path entry, and once inside the shared chunk behind\n * the root `@theokit/sdk` barrel. Both declarations carry private fields, so the\n * two are DISTINCT nominal types and TypeScript refuses to pass one where the\n * other is expected:\n *\n * Types have separate declarations of a private property '_options'.\n *\n * Import `Workflow` — and everything that consumes one, such as `workflowStep`\n * and `cloneWorkflow` — from `@theokit/sdk/workflow`, and do not mix the two\n * specifiers in one program. The root barrel re-exports only `Workflow`,\n * `agentStep` and `fn`; the builder, the step helpers, the error classes and every\n * workflow type live on the sub-path. (`workflowAsTool` is exempt: it accepts any\n * `{ run }`-shaped value structurally, so either `Workflow` satisfies it.)\n *\n * How it fails: a step that throws does NOT reject `run()`. The promise resolves\n * with `status: \"failed\"` and the cause on `run.error`; `\"suspended\"` and\n * `\"cancelled\"` are the other non-`\"completed\"` terminals, and an `outputSchema`\n * mismatch also lands as `\"failed\"` (`WorkflowOutputError`) rather than a throw.\n * What DOES throw out of `run()` is pre-flight: `WorkflowAlreadyRunningError` when\n * you pin `WorkflowRunOptions.runId` to one still in flight. `Workflow.resume`\n * throws `WorkflowSnapshotNotFoundError` for an unknown `runId`.\n *\n * Traps:\n * - Without an explicit `runId` each call mints its own, so concurrent runs of\n * the same committed workflow do NOT collide — the single-flight lock only\n * bites when you pin the id yourself.\n * - `stream()` reports progress; its `result` promise is the AUTHORITATIVE\n * outcome. Not every terminal emits a closing event, so a consumer that only\n * drains events can miss a failure. Always `await result`.\n * - `run()` and `stream()` load the executor by dynamic `import()`, so the first\n * call pays a module load and cannot be made synchronous.\n *\n * @public\n */\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { atomicWriteJson } from './chunk-VF7EWVDG.js';
2
- import { diag } from './chunk-T7O6K6PX.js';
1
+ import { atomicWriteJson } from './chunk-2GUYQR5P.js';
2
+ import { diag } from './chunk-XEQ3TM66.js';
3
3
  import { readFile, rename } from 'fs/promises';
4
4
 
5
5
  function migrateSchema(opts) {
@@ -77,5 +77,5 @@ async function writeVersionedJson(path, data, currentVersion) {
77
77
  }
78
78
 
79
79
  export { migrateSchema, readVersionedJson, writeVersionedJson };
80
- //# sourceMappingURL=chunk-UCBJBJ27.js.map
81
- //# sourceMappingURL=chunk-UCBJBJ27.js.map
80
+ //# sourceMappingURL=chunk-PUAEFLYK.js.map
81
+ //# sourceMappingURL=chunk-PUAEFLYK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/schema-version.ts"],"names":[],"mappings":";;;;AA4HO,SAAS,cAAc,IAAA,EAAiD;AAC7E,EAAA,MAAM,EAAE,EAAA,EAAI,cAAA,EAAgB,UAAA,EAAY,KAAA,GAAQ,MAAK,GAAI,IAAA;AACzD,EAAA,MAAM,YAAY,EAAA,CAAG,MAAA,CAAO,gBAAgB,EAAE,MAAA,EAAQ,MAAM,CAAA;AAC5D,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,CAAA,EAAI,KAAK,CAAA,iBAAA,EAAoB,MAAM,cAAc,cAAc,CAAA,0DAAA;AAAA,KAEjE;AAAA,EACF;AAEA,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,EAAA,EAAI,MAAA,EAAQ,KAAK,CAAA,EAAE;AAAA,EAC5C;AAEA,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,UAAU,EAC3B,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,SAAA,GAAY,EAAE,SAAS,CAAA,CACxC,OAAO,CAAC,CAAA,KAAM,EAAE,SAAA,GAAY,MAAA,IAAU,CAAA,CAAE,SAAA,IAAa,cAAc,CAAA;AAEtE,EAAA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AqC,CAAA;AAAA,IACjE;AACA,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAEA,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,KAAW,IAAA,EAAM;AACjD,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAEA,EAAA,MAAM,IAAA,GAAO,MAAA;AACb,EAAA,MAAM,YAAY,IAAA,CAAK,cAAA;AACvB,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAEA,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,IAAA;AAAA,MACE,CAAA,cAAA,EAAiB,IAAI,CAAA,gBAAA,EAAmB,MAAM,cAAc,cAAc,CAAA;AAAA;AAAA,KAE5E;AACA,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAKA,EAAA,OAAO,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC/B;AAyBA,eAAsB,kBAAA,CACpB,IAAA,EACA,IAAA,EACA,cAAA,EACe;AACf,EAAA,MAAM,IAAA,GAA6B;AAAA,IACjC,cAAA,EAAgB,cAAA;AAAA,IAChB;AAAA,GACF;AACA,EAAA,MAAM,eAAA,CAAgB,MAAM,IAAI,CAAA;AAClC","file":"chunk-UCBJBJ27.js","sourcesContent":["/**\n * Schema versioning helpers (ADR D62).\n *\n * Two parallel APIs:\n * - `migrateSchema` — SQLite via `PRAGMA user_version` + ordered forward-only migrations.\n * - `readVersionedJson` / `writeVersionedJson` — JSON files with `_schemaVersion` field.\n *\n * Forward-only: never deletes data, never downgrades. Migration callbacks\n * own the transformation; this module owns the bookkeeping.\n *\n * @internal\n */\n\nimport { readFile, rename } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"./atomic-write.js\";\n\n// ────────────────────── SQLite migrations ──────────────────────\n\n/**\n * The three `better-sqlite3` methods this module actually uses, declared structurally so nothing\n * here imports the driver.\n *\n * A real `better-sqlite3` `Database` satisfies it. `pragma` is called both to read\n * (`pragma(\"user_version\", { simple: true })`, which must return the number itself rather than a\n * row array) and to write (`pragma(\"user_version = N\")`). `transaction` must return a function\n * that, when called, runs the wrapped body inside a real SQLite transaction and rolls it back if\n * the body throws — a stub that merely calls through gives `migrateSchema` no atomicity, and a\n * half-applied migration is exactly what it exists to prevent.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface SqliteLike {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n exec: (sql: string) => void;\n transaction: <Args extends unknown[], R>(fn: (...args: Args) => R) => (...args: Args) => R;\n}\n\n/**\n * One forward migration step.\n *\n * `up` runs inside the shared transaction and must be self-contained: it may not commit, and any\n * error it throws aborts the whole run and rolls back every step in it, including the ones that\n * already succeeded. `user_version` is set to `toVersion` immediately after `up` returns, inside\n * the same transaction, so version and schema move together or not at all.\n *\n * `toVersion` is the version the database reaches, not the one it starts from. Steps are ordered\n * by it, gaps are allowed, and two steps sharing a `toVersion` both run — nothing deduplicates\n * them.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface Migration {\n toVersion: number;\n up: (db: SqliteLike) => void;\n}\n\n/**\n * Arguments to `migrateSchema`.\n *\n * `currentVersion` is the version the code expects, and it is the ceiling: a migration whose\n * `toVersion` exceeds it is left unapplied for a later release. `migrations` may be given in any\n * order and may contain steps already applied — both are filtered and sorted here. `label` only\n * ever appears in the downgrade error message.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaOptions {\n db: SqliteLike;\n currentVersion: number;\n migrations: ReadonlyArray<Migration>;\n /** For log/error context (e.g., \"memory-index\", \"registry\"). */\n label?: string;\n}\n\n/**\n * What `migrateSchema` did.\n *\n * `from` is the `user_version` found on the database, `to` is the version it holds afterwards,\n * and `ran` is how many steps executed. When nothing was pending, `to === from` and `ran === 0`.\n *\n * `to` is the `toVersion` of the last step applied, NOT `currentVersion`. A database at version 3\n * against `currentVersion: 5` with no migration in that range comes back as\n * `{ from: 3, to: 3, ran: 0 }` — the gap is reported, not closed. Comparing `to` with\n * `currentVersion` is how a caller notices that the migration list is missing a step.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaResult {\n from: number;\n to: number;\n ran: number;\n}\n\n/**\n * Bring a SQLite database's `user_version` up to `currentVersion` by running the steps that sit\n * between the two.\n *\n * Steps are sorted ascending by `toVersion` and filtered to `> stored && <= currentVersion`, then\n * run in that order inside ONE transaction: each `up` is followed immediately by the matching\n * `user_version` write. Either every step in the run commits or none does — a step that throws\n * aborts the transaction, propagates the error, and leaves the database at the version it started\n * from. There is no partially-migrated state and no resume point.\n *\n * Forward-only. When the stored version is greater than `currentVersion` — an older build opening\n * a database a newer one already migrated — this throws immediately, before touching anything,\n * with a message naming both versions and `label`. Nothing downgrades, and no data is deleted on\n * any path here; what a step does is the step's own business.\n *\n * A stored version equal to `currentVersion` returns without opening a transaction. A `user_version`\n * that is absent or not a number is read as 0, so a fresh database runs every step.\n *\n * Concurrency: the SQLite transaction is the only serialization. This takes no file lock, so two\n * processes migrating the same file at once are arbitrated by SQLite's own write lock — the loser\n * gets a busy or locked error from the driver, not a queued turn. Wrap the call in `withFileLock`\n * if that matters.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function migrateSchema(opts: MigrateSchemaOptions): MigrateSchemaResult {\n const { db, currentVersion, migrations, label = \"db\" } = opts;\n const storedRaw = db.pragma(\"user_version\", { simple: true });\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored > currentVersion) {\n throw new Error(\n `[${label}] schema version ${stored} > current ${currentVersion}; ` +\n \"did you downgrade the SDK? Forward-only migrations only.\",\n );\n }\n\n if (stored === currentVersion) {\n return { from: stored, to: stored, ran: 0 };\n }\n\n const pending = [...migrations]\n .sort((a, b) => a.toVersion - b.toVersion)\n .filter((m) => m.toVersion > stored && m.toVersion <= currentVersion);\n\n let ran = 0;\n let lastApplied = stored;\n\n db.transaction(() => {\n for (const m of pending) {\n m.up(db);\n db.pragma(`user_version = ${m.toVersion}`);\n lastApplied = m.toVersion;\n ran += 1;\n }\n })();\n\n return { from: stored, to: lastApplied, ran };\n}\n\n// ────────────────────── JSON versioned files ──────────────────────\n\n/**\n * The on-disk envelope: the payload under `data`, its schema version alongside it.\n *\n * `writeVersionedJson` always produces this shape. `readVersionedJson` reads it, but tolerates a\n * file that is not in it — a legacy object with no `_schemaVersion` is treated as version 0 and\n * handed to the migrate callback whole, so this type describes what is written, not everything\n * that can be read.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface VersionedJsonFile<T> {\n _schemaVersion: number;\n data: T;\n}\n\n/**\n * Upgrade callback for `readVersionedJson`, invoked only when the stored version is BELOW the\n * current one.\n *\n * `parsed` is the whole parsed JSON value, not `parsed.data`. That is deliberate: a legacy file\n * predating the envelope has its fields at the top level, and a callback handed only `.data`\n * would receive `undefined` for exactly the files that need migrating. It is typed `unknown`\n * because nothing has validated it — narrow before reading.\n *\n * `fromVersion` is the `_schemaVersion` found on disk, or 0 when the field is missing or not a\n * number.\n *\n * The return value is used as-is and is NOT written back; the file on disk still holds the old\n * shape until someone calls `writeVersionedJson`. Throwing here propagates out of\n * `readVersionedJson`, which otherwise never throws — return the default value instead if an\n * unmigratable file should be survivable.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport type VersionedJsonMigrate<T> = (parsed: unknown, fromVersion: number) => T;\n\n/**\n * Arguments to `readVersionedJson`.\n *\n * `defaultValue` is a factory rather than a value because it is called on several paths and each\n * caller must get its own object — returning a shared mutable default would let one caller's\n * edits appear in another's. It is called for a missing file, an unreadable one, a corrupt one,\n * a non-object payload, and a file written by a newer version.\n *\n * `migrate` is called only for a stored version strictly below `currentVersion`.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface ReadVersionedJsonOptions<T> {\n path: string;\n currentVersion: number;\n migrate: VersionedJsonMigrate<T>;\n defaultValue: () => T;\n}\n\n/**\n * Read a versioned JSON file, migrating or falling back rather than failing.\n *\n * What comes back, by case:\n *\n * - version matches `currentVersion` — the file's `data` field, returned as `T` WITHOUT\n * validation. A file whose envelope is right but whose payload is not gets through.\n * - version below `currentVersion` — whatever `migrate(parsed, stored)` returns. The migrated\n * value is not persisted; the file is untouched.\n * - version above `currentVersion` — `defaultValue()`, plus a warning. Forward-only: a file\n * written by a newer build is left alone rather than downgraded.\n * - file missing, or unreadable for any other reason (permissions, a directory in its place) —\n * `defaultValue()`, silently. Absence and denial are not distinguished.\n * - file present but not valid JSON — `defaultValue()`, and the file is RENAMED to\n * `<path>.corrupt.<epoch-ms>` so the next run starts clean and the bad bytes stay available.\n * A rename that itself fails is warned about and the read still returns the default, which\n * means the same corrupt file will be met again next time.\n * - JSON that parses to a non-object (a number, a string, `null`) — `defaultValue()`, silently\n * and without moving the file aside.\n *\n * The only ways this throws are through the callbacks you supply: `migrate` or `defaultValue`\n * raising. Nothing else here rejects.\n *\n * There is no locking. A concurrent `writeVersionedJson` on the same path is atomic at the rename,\n * so a reader sees either the old file or the new one, never a half-written one — but a\n * read-modify-write built from this pair is NOT atomic across the two calls, and needs\n * `withFileLock` around both.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function readVersionedJson<T>(opts: ReadVersionedJsonOptions<T>): Promise<T> {\n const { path, currentVersion, migrate, defaultValue } = opts;\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf-8\");\n } catch {\n return defaultValue();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // T5.10 — move corrupt file aside so (a) user can investigate and\n // (b) next run starts fresh instead of hitting the same warning loop.\n const asidePath = `${path}.corrupt.${Date.now()}`;\n try {\n await rename(path, asidePath);\n diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.\\n`);\n } catch {\n diag(`[theokit-sdk] ${path} is corrupt; using default value.\\n`);\n }\n return defaultValue();\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return defaultValue();\n }\n\n const file = parsed as { _schemaVersion?: unknown; data?: unknown };\n const storedRaw = file._schemaVersion;\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored === currentVersion) {\n return file.data as T;\n }\n\n if (stored > currentVersion) {\n diag(\n `[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; ` +\n \"using default value (forward-only).\\n\",\n );\n return defaultValue();\n }\n\n // EC-2 fix: pass the FULL parsed object to migrate, not just `file.data`.\n // Legacy shapes (e.g., `{ schemaVersion: \"1.0\", agents: {...} }` without\n // a `data` field) need to inspect the whole thing.\n return migrate(parsed, stored);\n}\n\n/**\n * Write `data` wrapped in the version envelope, replacing the file atomically.\n *\n * The bytes go to a temp file in the same directory and are moved into place with `rename`, so a\n * crash or a concurrent reader never observes a partial file: the path holds either the previous\n * content or the complete new content. Parent directories are created as needed, and the file is\n * created with mode 0600 (subject to the process umask), formatted with two-space indentation and\n * a trailing newline.\n *\n * `currentVersion` is stamped verbatim as `_schemaVersion`; nothing checks it against what was\n * already on disk, so this will happily overwrite a newer file with an older version. Read first\n * if that matters.\n *\n * Rejects when `data` cannot be serialized — a circular reference, or a `toJSON` that throws.\n * Serialization happens before any filesystem call, so on that path no directory is created, no\n * temp file exists, and the file already on disk is untouched.\n *\n * Atomicity is the rename's, so it is as strong as the filesystem's: on NFS, SMB or FUSE the\n * underlying writer emits a one-shot warning that the guarantee is weaker there.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function writeVersionedJson<T>(\n path: string,\n data: T,\n currentVersion: number,\n): Promise<void> {\n const file: VersionedJsonFile<T> = {\n _schemaVersion: currentVersion,\n data,\n };\n await atomicWriteJson(path, file);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/schema-version.ts"],"names":[],"mappings":";;;;AA4HO,SAAS,cAAc,IAAA,EAAiD;AAC7E,EAAA,MAAM,EAAE,EAAA,EAAI,cAAA,EAAgB,UAAA,EAAY,KAAA,GAAQ,MAAK,GAAI,IAAA;AACzD,EAAA,MAAM,YAAY,EAAA,CAAG,MAAA,CAAO,gBAAgB,EAAE,MAAA,EAAQ,MAAM,CAAA;AAC5D,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,CAAA,EAAI,KAAK,CAAA,iBAAA,EAAoB,MAAM,cAAc,cAAc,CAAA,0DAAA;AAAA,KAEjE;AAAA,EACF;AAEA,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,EAAA,EAAI,MAAA,EAAQ,KAAK,CAAA,EAAE;AAAA,EAC5C;AAEA,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,UAAU,EAC3B,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,SAAA,GAAY,EAAE,SAAS,CAAA,CACxC,OAAO,CAAC,CA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AAA;AAAA,IACxF,CAAA,CAAA,MAAQ;AACN,MAAA,IAAA,CAAK,iBAAiB,IAAI,CAAA;AAAA,CAAqC,CAAA;AAAA,IACjE;AACA,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAEA,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,KAAW,IAAA,EAAM;AACjD,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAEA,EAAA,MAAM,IAAA,GAAO,MAAA;AACb,EAAA,MAAM,YAAY,IAAA,CAAK,cAAA;AACvB,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAEA,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,IAAA;AAAA,MACE,CAAA,cAAA,EAAiB,IAAI,CAAA,gBAAA,EAAmB,MAAM,cAAc,cAAc,CAAA;AAAA;AAAA,KAE5E;AACA,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAKA,EAAA,OAAO,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC/B;AAyBA,eAAsB,kBAAA,CACpB,IAAA,EACA,IAAA,EACA,cAAA,EACe;AACf,EAAA,MAAM,IAAA,GAA6B;AAAA,IACjC,cAAA,EAAgB,cAAA;AAAA,IAChB;AAAA,GACF;AACA,EAAA,MAAM,eAAA,CAAgB,MAAM,IAAI,CAAA;AAClC","file":"chunk-PUAEFLYK.js","sourcesContent":["/**\n * Schema versioning helpers (ADR D62).\n *\n * Two parallel APIs:\n * - `migrateSchema` — SQLite via `PRAGMA user_version` + ordered forward-only migrations.\n * - `readVersionedJson` / `writeVersionedJson` — JSON files with `_schemaVersion` field.\n *\n * Forward-only: never deletes data, never downgrades. Migration callbacks\n * own the transformation; this module owns the bookkeeping.\n *\n * @internal\n */\n\nimport { readFile, rename } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"./atomic-write.js\";\n\n// ────────────────────── SQLite migrations ──────────────────────\n\n/**\n * The three `better-sqlite3` methods this module actually uses, declared structurally so nothing\n * here imports the driver.\n *\n * A real `better-sqlite3` `Database` satisfies it. `pragma` is called both to read\n * (`pragma(\"user_version\", { simple: true })`, which must return the number itself rather than a\n * row array) and to write (`pragma(\"user_version = N\")`). `transaction` must return a function\n * that, when called, runs the wrapped body inside a real SQLite transaction and rolls it back if\n * the body throws — a stub that merely calls through gives `migrateSchema` no atomicity, and a\n * half-applied migration is exactly what it exists to prevent.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface SqliteLike {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n exec: (sql: string) => void;\n transaction: <Args extends unknown[], R>(fn: (...args: Args) => R) => (...args: Args) => R;\n}\n\n/**\n * One forward migration step.\n *\n * `up` runs inside the shared transaction and must be self-contained: it may not commit, and any\n * error it throws aborts the whole run and rolls back every step in it, including the ones that\n * already succeeded. `user_version` is set to `toVersion` immediately after `up` returns, inside\n * the same transaction, so version and schema move together or not at all.\n *\n * `toVersion` is the version the database reaches, not the one it starts from. Steps are ordered\n * by it, gaps are allowed, and two steps sharing a `toVersion` both run — nothing deduplicates\n * them.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface Migration {\n toVersion: number;\n up: (db: SqliteLike) => void;\n}\n\n/**\n * Arguments to `migrateSchema`.\n *\n * `currentVersion` is the version the code expects, and it is the ceiling: a migration whose\n * `toVersion` exceeds it is left unapplied for a later release. `migrations` may be given in any\n * order and may contain steps already applied — both are filtered and sorted here. `label` only\n * ever appears in the downgrade error message.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaOptions {\n db: SqliteLike;\n currentVersion: number;\n migrations: ReadonlyArray<Migration>;\n /** For log/error context (e.g., \"memory-index\", \"registry\"). */\n label?: string;\n}\n\n/**\n * What `migrateSchema` did.\n *\n * `from` is the `user_version` found on the database, `to` is the version it holds afterwards,\n * and `ran` is how many steps executed. When nothing was pending, `to === from` and `ran === 0`.\n *\n * `to` is the `toVersion` of the last step applied, NOT `currentVersion`. A database at version 3\n * against `currentVersion: 5` with no migration in that range comes back as\n * `{ from: 3, to: 3, ran: 0 }` — the gap is reported, not closed. Comparing `to` with\n * `currentVersion` is how a caller notices that the migration list is missing a step.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface MigrateSchemaResult {\n from: number;\n to: number;\n ran: number;\n}\n\n/**\n * Bring a SQLite database's `user_version` up to `currentVersion` by running the steps that sit\n * between the two.\n *\n * Steps are sorted ascending by `toVersion` and filtered to `> stored && <= currentVersion`, then\n * run in that order inside ONE transaction: each `up` is followed immediately by the matching\n * `user_version` write. Either every step in the run commits or none does — a step that throws\n * aborts the transaction, propagates the error, and leaves the database at the version it started\n * from. There is no partially-migrated state and no resume point.\n *\n * Forward-only. When the stored version is greater than `currentVersion` — an older build opening\n * a database a newer one already migrated — this throws immediately, before touching anything,\n * with a message naming both versions and `label`. Nothing downgrades, and no data is deleted on\n * any path here; what a step does is the step's own business.\n *\n * A stored version equal to `currentVersion` returns without opening a transaction. A `user_version`\n * that is absent or not a number is read as 0, so a fresh database runs every step.\n *\n * Concurrency: the SQLite transaction is the only serialization. This takes no file lock, so two\n * processes migrating the same file at once are arbitrated by SQLite's own write lock — the loser\n * gets a busy or locked error from the driver, not a queued turn. Wrap the call in `withFileLock`\n * if that matters.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function migrateSchema(opts: MigrateSchemaOptions): MigrateSchemaResult {\n const { db, currentVersion, migrations, label = \"db\" } = opts;\n const storedRaw = db.pragma(\"user_version\", { simple: true });\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored > currentVersion) {\n throw new Error(\n `[${label}] schema version ${stored} > current ${currentVersion}; ` +\n \"did you downgrade the SDK? Forward-only migrations only.\",\n );\n }\n\n if (stored === currentVersion) {\n return { from: stored, to: stored, ran: 0 };\n }\n\n const pending = [...migrations]\n .sort((a, b) => a.toVersion - b.toVersion)\n .filter((m) => m.toVersion > stored && m.toVersion <= currentVersion);\n\n let ran = 0;\n let lastApplied = stored;\n\n db.transaction(() => {\n for (const m of pending) {\n m.up(db);\n db.pragma(`user_version = ${m.toVersion}`);\n lastApplied = m.toVersion;\n ran += 1;\n }\n })();\n\n return { from: stored, to: lastApplied, ran };\n}\n\n// ────────────────────── JSON versioned files ──────────────────────\n\n/**\n * The on-disk envelope: the payload under `data`, its schema version alongside it.\n *\n * `writeVersionedJson` always produces this shape. `readVersionedJson` reads it, but tolerates a\n * file that is not in it — a legacy object with no `_schemaVersion` is treated as version 0 and\n * handed to the migrate callback whole, so this type describes what is written, not everything\n * that can be read.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface VersionedJsonFile<T> {\n _schemaVersion: number;\n data: T;\n}\n\n/**\n * Upgrade callback for `readVersionedJson`, invoked only when the stored version is BELOW the\n * current one.\n *\n * `parsed` is the whole parsed JSON value, not `parsed.data`. That is deliberate: a legacy file\n * predating the envelope has its fields at the top level, and a callback handed only `.data`\n * would receive `undefined` for exactly the files that need migrating. It is typed `unknown`\n * because nothing has validated it — narrow before reading.\n *\n * `fromVersion` is the `_schemaVersion` found on disk, or 0 when the field is missing or not a\n * number.\n *\n * The return value is used as-is and is NOT written back; the file on disk still holds the old\n * shape until someone calls `writeVersionedJson`. Throwing here propagates out of\n * `readVersionedJson`, which otherwise never throws — return the default value instead if an\n * unmigratable file should be survivable.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport type VersionedJsonMigrate<T> = (parsed: unknown, fromVersion: number) => T;\n\n/**\n * Arguments to `readVersionedJson`.\n *\n * `defaultValue` is a factory rather than a value because it is called on several paths and each\n * caller must get its own object — returning a shared mutable default would let one caller's\n * edits appear in another's. It is called for a missing file, an unreadable one, a corrupt one,\n * a non-object payload, and a file written by a newer version.\n *\n * `migrate` is called only for a stored version strictly below `currentVersion`.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport interface ReadVersionedJsonOptions<T> {\n path: string;\n currentVersion: number;\n migrate: VersionedJsonMigrate<T>;\n defaultValue: () => T;\n}\n\n/**\n * Read a versioned JSON file, migrating or falling back rather than failing.\n *\n * What comes back, by case:\n *\n * - version matches `currentVersion` — the file's `data` field, returned as `T` WITHOUT\n * validation. A file whose envelope is right but whose payload is not gets through.\n * - version below `currentVersion` — whatever `migrate(parsed, stored)` returns. The migrated\n * value is not persisted; the file is untouched.\n * - version above `currentVersion` — `defaultValue()`, plus a warning. Forward-only: a file\n * written by a newer build is left alone rather than downgraded.\n * - file missing, or unreadable for any other reason (permissions, a directory in its place) —\n * `defaultValue()`, silently. Absence and denial are not distinguished.\n * - file present but not valid JSON — `defaultValue()`, and the file is RENAMED to\n * `<path>.corrupt.<epoch-ms>` so the next run starts clean and the bad bytes stay available.\n * A rename that itself fails is warned about and the read still returns the default, which\n * means the same corrupt file will be met again next time.\n * - JSON that parses to a non-object (a number, a string, `null`) — `defaultValue()`, silently\n * and without moving the file aside.\n *\n * The only ways this throws are through the callbacks you supply: `migrate` or `defaultValue`\n * raising. Nothing else here rejects.\n *\n * There is no locking. A concurrent `writeVersionedJson` on the same path is atomic at the rename,\n * so a reader sees either the old file or the new one, never a half-written one — but a\n * read-modify-write built from this pair is NOT atomic across the two calls, and needs\n * `withFileLock` around both.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function readVersionedJson<T>(opts: ReadVersionedJsonOptions<T>): Promise<T> {\n const { path, currentVersion, migrate, defaultValue } = opts;\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf-8\");\n } catch {\n return defaultValue();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // T5.10 — move corrupt file aside so (a) user can investigate and\n // (b) next run starts fresh instead of hitting the same warning loop.\n const asidePath = `${path}.corrupt.${Date.now()}`;\n try {\n await rename(path, asidePath);\n diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.\\n`);\n } catch {\n diag(`[theokit-sdk] ${path} is corrupt; using default value.\\n`);\n }\n return defaultValue();\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return defaultValue();\n }\n\n const file = parsed as { _schemaVersion?: unknown; data?: unknown };\n const storedRaw = file._schemaVersion;\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored === currentVersion) {\n return file.data as T;\n }\n\n if (stored > currentVersion) {\n diag(\n `[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; ` +\n \"using default value (forward-only).\\n\",\n );\n return defaultValue();\n }\n\n // EC-2 fix: pass the FULL parsed object to migrate, not just `file.data`.\n // Legacy shapes (e.g., `{ schemaVersion: \"1.0\", agents: {...} }` without\n // a `data` field) need to inspect the whole thing.\n return migrate(parsed, stored);\n}\n\n/**\n * Write `data` wrapped in the version envelope, replacing the file atomically.\n *\n * The bytes go to a temp file in the same directory and are moved into place with `rename`, so a\n * crash or a concurrent reader never observes a partial file: the path holds either the previous\n * content or the complete new content. Parent directories are created as needed, and the file is\n * created with mode 0600 (subject to the process umask), formatted with two-space indentation and\n * a trailing newline.\n *\n * `currentVersion` is stamped verbatim as `_schemaVersion`; nothing checks it against what was\n * already on disk, so this will happily overwrite a newer file with an older version. Read first\n * if that matters.\n *\n * Rejects when `data` cannot be serialized — a circular reference, or a `toJSON` that throws.\n * Serialization happens before any filesystem call, so on that path no directory is created, no\n * temp file exists, and the file already on disk is untouched.\n *\n * Atomicity is the rename's, so it is as strong as the filesystem's: on NFS, SMB or FUSE the\n * underlying writer emits a one-shot warning that the guarantee is weaker there.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport async function writeVersionedJson<T>(\n path: string,\n data: T,\n currentVersion: number,\n): Promise<void> {\n const file: VersionedJsonFile<T> = {\n _schemaVersion: currentVersion,\n data,\n };\n await atomicWriteJson(path, file);\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkI6TGFUCO_cjs = require('./chunk-I6TGFUCO.cjs');
4
- var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
5
- var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
3
+ var chunkUALX2J2Q_cjs = require('./chunk-UALX2J2Q.cjs');
4
+ var chunk4ZHTIJNE_cjs = require('./chunk-4ZHTIJNE.cjs');
5
+ var chunkEG4QM7ZJ_cjs = require('./chunk-EG4QM7ZJ.cjs');
6
6
  var fs = require('fs');
7
7
  var promises = require('fs/promises');
8
8
  var path = require('path');
@@ -27,7 +27,7 @@ function assertValidIdForStore(id) {
27
27
  /* allowReserved */
28
28
  true
29
29
  )) {
30
- throw new chunkK3FW2XZD_cjs.InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);
30
+ throw new chunk4ZHTIJNE_cjs.InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);
31
31
  }
32
32
  }
33
33
  function terminalTimestamp(h) {
@@ -129,14 +129,14 @@ var JsonFileTaskStore = class {
129
129
  }
130
130
  async insert(handle) {
131
131
  assertValidIdForStore(handle.id);
132
- await chunkI6TGFUCO_cjs.atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));
132
+ await chunkUALX2J2Q_cjs.atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));
133
133
  }
134
134
  async update(id, mutate) {
135
135
  assertValidIdForStore(id);
136
136
  const existing = await this.get(id);
137
137
  if (existing === void 0) return void 0;
138
138
  const next = mutate(existing);
139
- await chunkI6TGFUCO_cjs.atomicWriteText(this.filePath(id), JSON.stringify(next));
139
+ await chunkUALX2J2Q_cjs.atomicWriteText(this.filePath(id), JSON.stringify(next));
140
140
  return next;
141
141
  }
142
142
  async get(id) {
@@ -147,7 +147,7 @@ var JsonFileTaskStore = class {
147
147
  } catch (err) {
148
148
  const code = err.code;
149
149
  if (code === "ENOENT") return void 0;
150
- chunkNUKRL3I6_cjs.diag(`[task-store] failed to read ${id}: ${err.message}
150
+ chunkEG4QM7ZJ_cjs.diag(`[task-store] failed to read ${id}: ${err.message}
151
151
  `);
152
152
  return void 0;
153
153
  }
@@ -231,5 +231,5 @@ exports.JsonFileTaskStore = JsonFileTaskStore;
231
231
  exports.TASK_RESERVED_PREFIXES = TASK_RESERVED_PREFIXES;
232
232
  exports.getTaskStoreFor = getTaskStoreFor;
233
233
  exports.isValidTaskId = isValidTaskId;
234
- //# sourceMappingURL=chunk-2C72DXQF.cjs.map
235
- //# sourceMappingURL=chunk-2C72DXQF.cjs.map
234
+ //# sourceMappingURL=chunk-RFMBZPOW.cjs.map
235
+ //# sourceMappingURL=chunk-RFMBZPOW.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types/task.ts","../src/internal/task/store.ts"],"names":["InvalidTaskIdError","mkdirSync","join","atomicWriteText","readFile","diag","readdirSync","unlink"],"mappings":";;;;;;;;;;AAwJA,IAAM,eAAA,GAAkB,uBAAA;AAGxB,IAAM,iBAAA,GAAoB,CAAC,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAUxC,SAAS,aAAA,CAAc,IAAY,aAAA,EAAiC;AACzE,EAAA,IA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AAO,EAAE,CAAA,EAAG,KAAA,EAAA;AAAA,IACpC,CAAC,CAAA;AACD,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,gBAAgB,OAAA,EAAsC;AACpE,EAAA,IAAI,OAAA,CAAQ,OAAA,KAAY,QAAA,EAAU,OAAO,IAAI,iBAAA,EAAkB;AAC/D,EAAA,OAAO,IAAI,iBAAA,CAAkB,OAAA,CAAQ,GAAG,CAAA;AAC1C","file":"chunk-2C72DXQF.cjs","sourcesContent":["/**\n * Public type contract for the Task observability registry (ADRs D361-D374).\n *\n * Tasks are an opt-in observability layer over async work in the SDK\n * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have\n * a closed 5-state lifecycle (D362), discriminated events (D366), and a\n * pluggable store (D364). The `Task` facade in `task.ts` is the public\n * surface; consumers import these types from `@theokit/sdk`.\n *\n * @public\n */\n\n/**\n * Closed enum of the 5 lifecycle states (D362).\n *\n * Transitions are acyclic:\n * queued → running → (finished | error | cancelled)\n * queued → cancelled (direct, no run started)\n */\nexport type TaskState = \"queued\" | \"running\" | \"finished\" | \"error\" | \"cancelled\";\n\n/** Discriminator of the runtime that produced a task (D374). */\nexport type TaskKind = \"run\" | \"batch\" | \"workflow\" | \"cron\" | \"custom\";\n\n/** Discriminated union of task lifecycle events (D366). */\nexport type TaskEvent =\n | {\n readonly type: \"submitted\";\n readonly taskId: string;\n readonly kind: TaskKind;\n readonly submittedAt: number;\n readonly meta?: Record<string, unknown>;\n /** D372 — flag set on the first yielded event when the ring buffer was at cap. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"started\"; readonly taskId: string; readonly startedAt: number }\n | {\n readonly type: \"progress\";\n readonly taskId: string;\n readonly at: number;\n readonly payload: unknown;\n }\n | {\n readonly type: \"finished\";\n readonly taskId: string;\n readonly finishedAt: number;\n readonly result: unknown;\n }\n | {\n readonly type: \"errored\";\n readonly taskId: string;\n readonly erroredAt: number;\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly type: \"cancelled\";\n readonly taskId: string;\n readonly cancelledAt: number;\n readonly reason?: string;\n };\n\n/** Public read-only view of a task entry in the registry. */\nexport interface TaskHandle {\n readonly id: string;\n readonly kind: TaskKind;\n readonly state: TaskState;\n readonly submittedAt: number;\n readonly startedAt?: number;\n readonly finishedAt?: number;\n readonly cancelledAt?: number;\n readonly erroredAt?: number;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly meta?: Record<string, unknown>;\n /**\n * EC-7 — cross-process best-effort cancel flag. Set by CLI\n * `theokit tasks cancel` via JsonFileTaskStore. The owning process\n * polls at checkpoints and honors via AbortController. Always\n * `undefined` for in-process cancel paths (which go directly through\n * AbortController).\n */\n readonly cancelRequested?: boolean;\n /**\n * Why the task was cancelled, when whoever cancelled it said. Free text, written alongside\n * `cancelledAt` for a `queued` task and alongside `cancelRequested` for a `running` one.\n *\n * Absent when no reason was given — an empty string is not a reason, and a default like\n * \"cancelled\" would put words in the operator's mouth. `theokit tasks cancel --reason` is what\n * writes it (#351); nothing in the runtime reads it, because it exists for the human reading the\n * registry later.\n */\n readonly cancelReason?: string;\n}\n\n/** Query filter for `Task.list`. */\nexport interface TaskFilter {\n readonly state?: TaskState | readonly TaskState[];\n readonly kind?: TaskKind | readonly TaskKind[];\n readonly submittedAfter?: number;\n readonly submittedBefore?: number;\n /**\n * Defaults to 100. `JsonFileTaskStore` returns the newest matching tasks first and reads its\n * whole directory to find them (256 files at a time); page past this limit with\n * `submittedBefore` (#362).\n */\n readonly limit?: number;\n}\n\n/** Options for `Task.submit`. */\nexport interface TaskSubmitOptions {\n /**\n * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`\n * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`\n * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.\n */\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Optional caller-provided AbortSignal. If already aborted at submit\n * time, the registry short-circuits to `cancelled` without acquiring\n * a semaphore slot (EC-4).\n */\n readonly signal?: AbortSignal;\n /**\n * SE2 — an opt-in {@link import(\"./run-events.js\").RunEventSink}. The task's\n * lifecycle is forwarded to it as typed `task_started` / `task_updated` /\n * `task_completed` RunEvents, so a caller that spawned the task can observe it\n * through the same `onRunEvent` channel as the rest of the run. Best-effort (a\n * throwing sink never breaks the task). The dedicated `Task.subscribe(id)`\n * channel is unaffected.\n */\n readonly onRunEvent?: import(\"./run-events.js\").RunEventSink;\n}\n\n/** Options shape for `TaskStore` factory (D364). */\nexport type TaskStoreOptions =\n | { readonly backend: \"memory\" }\n | { readonly backend: \"json\"; readonly dir: string };\n\n/** Result of `Task.cancel` (D365 — idempotent). */\nexport interface TaskCancelResult {\n readonly cancelled: boolean;\n readonly alreadyTerminal: boolean;\n}\n\n/**\n * Grammar for user-supplied task IDs (D368).\n * `crypto.randomUUID()` outputs do NOT match this (UUIDs have dashes\n * AND uppercase letters in their canonical form on some Node versions),\n * but the registry normalizes auto-generated IDs to lowercase before\n * insertion, so they pass the same regex.\n */\nconst TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\n/** Reserved prefixes for adapter-generated IDs (D368, EC-5). */\nconst RESERVED_PREFIXES = [\"wf-\", \"b-\", \"cron-\"] as const;\n\n/**\n * Validates a task ID against the public grammar + reserved prefixes.\n * Throws `InvalidTaskIdError` from `../errors.js` on rejection.\n *\n * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`\n * to register their own IDs; user-facing surfaces (`Task.submit`,\n * `agent.send({ task: { id } })`) leave it false.\n */\nexport function isValidTaskId(id: string, allowReserved: boolean): boolean {\n if (!TASK_ID_GRAMMAR.test(id)) return false;\n if (allowReserved) return true;\n for (const prefix of RESERVED_PREFIXES) {\n if (id.startsWith(prefix)) return false;\n }\n return true;\n}\n\n/** Re-exported for adapter implementations + tests. */\nexport const TASK_RESERVED_PREFIXES: readonly string[] = RESERVED_PREFIXES;\n","/**\n * `TaskStore` interface + 2 implementations (ADR D364).\n *\n * - `InMemoryTaskStore` — default, transient, single-process.\n * - `JsonFileTaskStore` — opt-in, one JSON file per task under a\n * dedicated dir; single-process invariant (EC-15 documented).\n *\n * Edge cases absorbed:\n * - EC-1: constructor auto-creates dir (mkdirSync recursive idempotent).\n * - EC-2: every method validates the task id against the public\n * grammar (D368) BEFORE doing any path I/O — path-traversal defense.\n * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).\n * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted\n * atomic writes.\n * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap.\n * It no longer advertises `submittedBefore` as a way to page past it:\n * the cap is applied to the raw directory listing before any filter, so\n * paging beyond 256 files is not reachable through this interface.\n * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the\n * single-process invariant; v0.2 SQLite covers cross-process.\n *\n * @internal\n */\n\nimport { mkdirSync, readdirSync } from \"node:fs\";\nimport { readFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskFilter,\n type TaskHandle,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nconst JSON_LOAD_CAP = 256;\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Storage interface used by `TaskRegistry`. */\nexport interface TaskStore {\n insert(handle: TaskHandle): Promise<void>;\n update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;\n get(id: string): Promise<TaskHandle | undefined>;\n /**\n * Returns at most `filter.limit ?? 100` matching handles.\n *\n * `JsonFileTaskStore` returns them newest-first and considers every task in its\n * directory, reading at most 256 files concurrently (#362 — that number bounds\n * I/O, not which tasks are visible). Walk past `limit` by passing the oldest\n * `submittedAt` of a page as the next call's `submittedBefore`; the ordering is\n * what makes that a cursor rather than a re-roll of an arbitrary subset.\n * `InMemoryTaskStore` applies the same filters but does not order its result.\n */\n list(filter: TaskFilter): Promise<TaskHandle[]>;\n delete(id: string): Promise<boolean>;\n /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */\n evictTerminalOlderThan(epochMs: number): Promise<number>;\n}\n\nfunction assertValidIdForStore(id: string): void {\n if (!isValidTaskId(id, /* allowReserved */ true)) {\n throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);\n }\n}\n\nfunction terminalTimestamp(h: TaskHandle): number | undefined {\n if (h.state === \"finished\") return h.finishedAt;\n if (h.state === \"error\") return h.erroredAt;\n if (h.state === \"cancelled\") return h.cancelledAt;\n return undefined;\n}\n\nfunction isTerminal(state: TaskState): boolean {\n return state === \"finished\" || state === \"error\" || state === \"cancelled\";\n}\n\nfunction matchesState(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.state === undefined) return true;\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n return states.includes(h.state);\n}\nfunction matchesKind(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.kind === undefined) return true;\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n return kinds.includes(h.kind);\n}\nfunction matchesTime(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.submittedAfter !== undefined && h.submittedAt <= filter.submittedAfter) return false;\n if (filter.submittedBefore !== undefined && h.submittedAt >= filter.submittedBefore) return false;\n return true;\n}\nfunction matchesFilter(h: TaskHandle, filter: TaskFilter): boolean {\n return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);\n}\n\n/** The states `evictTerminalOlderThan` considers terminal. */\nconst TERMINAL_STATES: readonly TaskState[] = [\"finished\", \"error\", \"cancelled\"];\n\n/**\n * Where `submittedAt` belongs in a newest-first list — the first index whose entry is older.\n *\n * Linear rather than binary: the list is bounded by the caller's `limit` (100 by default) and the\n * scan runs once per MATCHING handle, so the comparison count is dwarfed by the file read that\n * produced the handle. A binary search here would trade a real cost for an imagined one.\n */\nfunction insertionIndex(newestFirst: readonly TaskHandle[], submittedAt: number): number {\n for (let i = 0; i < newestFirst.length; i++) {\n const entry = newestFirst[i];\n if (entry !== undefined && entry.submittedAt < submittedAt) return i;\n }\n return newestFirst.length;\n}\n\nfunction applyFilter(values: Iterable<TaskHandle>, filter: TaskFilter): TaskHandle[] {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n const out: TaskHandle[] = [];\n for (const h of values) {\n if (matchesFilter(h, filter)) {\n out.push(h);\n if (out.length >= limit) break;\n }\n }\n return out;\n}\n\n/* ─── InMemory ─── */\n\n/**\n * Default `TaskStore` — a plain `Map` living in the current process.\n *\n * Nothing reaches disk and nothing survives the process, so a task recorded here\n * is invisible to a reader in another process (`theokit tasks`). Select it with\n * `getTaskStoreFor({ backend: \"memory\" })`.\n *\n * How it fails: every id-taking method validates against the task-id grammar\n * (`^[a-z0-9][a-z0-9_-]*$`; reserved `wf-`/`b-`/`cron-` prefixes are permitted\n * here) and throws `InvalidTaskIdError` before touching the map. A missing id is\n * reported by returning `undefined` (`get`, `update`) or `false` (`delete`), never\n * by throwing.\n *\n * Traps:\n * - `insert()` is a `Map.set`: an existing id is overwritten silently, not\n * rejected.\n * - `list()` walks in INSERTION order and stops as soon as `filter.limit ?? 100`\n * matches are collected. It never sorts, so the limit truncates an\n * oldest-first scan rather than returning the most recent tasks.\n * - Nothing evicts on its own; terminal handles accumulate until a caller invokes\n * `evictTerminalOlderThan`.\n */\nexport class InMemoryTaskStore implements TaskStore {\n private readonly map = new Map<string, TaskHandle>();\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n this.map.set(handle.id, handle);\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = this.map.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n this.map.set(id, next);\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n return this.map.get(id);\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n return applyFilter(this.map.values(), filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n return this.map.delete(id);\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n let count = 0;\n for (const [id, h] of this.map.entries()) {\n if (!isTerminal(h.state)) continue;\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n this.map.delete(id);\n count++;\n }\n }\n return count;\n }\n}\n\n/* ─── JsonFile (opt-in) ───\n *\n * IMPORTANT (EC-15): `JsonFileTaskStore` is **single-process**.\n * Concurrent writers from multiple Node processes against the same\n * directory may corrupt entries (atomic-write protects per-file, but\n * the `list()` scan + `update()` read-modify-write cycle is not\n * serialised across processes). Use only when the `TaskRegistry`\n * runs in exactly one process. v0.2 will add a SQLite backend with\n * the same interface for cross-process scenarios (D364 + D61).\n */\n/**\n * Opt-in `TaskStore` that keeps one JSON file per task under `dir`, so another\n * process can read the registry off disk.\n *\n * const store = new JsonFileTaskStore(\"/var/lib/theokit/tasks\");\n *\n * Two calls are synchronous, and both are deliberate: the constructor creates `dir`\n * recursively (`mkdirSync`), and `list()` scans it with `readdirSync` before awaiting\n * anything. Every other operation is async — `get` uses `readFile`, `delete` uses\n * `unlink`, and every write goes through an atomic temp-file-plus-rename.\n *\n * SINGLE-PROCESS ONLY — see the note above. Per-file atomicity does not make\n * `update()` safe: it is a read-modify-write, so two writers that both `get`\n * before either writes lose one of the two mutations. That is true within one\n * process as well as across processes.\n *\n * How it fails:\n * - An invalid id throws `InvalidTaskIdError` BEFORE any path is constructed.\n * That ordering is the path-traversal defence, and it is why ids are validated\n * rather than escaped.\n * - A missing task is `undefined` from `get` and `false` from `delete`.\n * - A file that exists but does not parse is NOT surfaced as an error: `get`\n * writes to the diagnostics channel and returns `undefined`, so a corrupted\n * task also silently vanishes from `list()`.\n * - `list()` returns `[]` when `dir` does not exist; any other `readdir` failure\n * (for example a permission error) throws.\n *\n * Traps:\n * - `list()` reads every task file in the directory (256 at a time) to apply the\n * filter, because `state`, `kind` and `submittedAt` live inside the files. On a\n * large directory that is a lot of I/O for one call; the memory it holds is\n * bounded by `limit`, the time is not.\n * - `list()` is `async`, but its directory scan is not: `readdirSync` blocks the event\n * loop for the whole listing before the first `await`. Only the per-file reads that\n * follow it are concurrent.\n * - Files whose name contains `.tmp` are skipped as orphans of an interrupted\n * write, and nothing ever removes them.\n */\nexport class JsonFileTaskStore implements TaskStore {\n constructor(private readonly dir: string) {\n // EC-1: idempotent mkdir; ignore EEXIST.\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n }\n\n private filePath(id: string): string {\n return join(this.dir, `${id}.json`);\n }\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = await this.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n await atomicWriteText(this.filePath(id), JSON.stringify(next));\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n try {\n const raw = await readFile(this.filePath(id), \"utf8\");\n return JSON.parse(raw) as TaskHandle;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n // Corrupt JSON or other I/O error — log + degrade gracefully (D50/EC-7 cache pattern).\n diag(`[task-store] failed to read ${id}: ${(err as Error).message}\\n`);\n return undefined;\n }\n }\n\n /**\n * Task ids backed by a file in `dir`, in readdir order.\n *\n * EC-8: orphan `.tmp` files left by an interrupted atomic write are skipped, as is any name\n * outside the id grammar. EC-6: a missing directory lists as empty; any other `readdir` failure\n * (a permission error, say) throws rather than being reported as \"no tasks\".\n */\n private candidateIds(): string[] {\n let entries: string[];\n try {\n entries = readdirSync(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return []; // EC-6\n throw err;\n }\n return entries\n .filter((name) => name.endsWith(\".json\") && !name.includes(\".tmp\"))\n .map((name) => name.slice(0, -\".json\".length))\n .filter((id) => isValidTaskId(id, true));\n }\n\n /**\n * Read every task in `ids`, handing each loaded handle to `visit`, at most `JSON_LOAD_CAP` file\n * reads in flight.\n *\n * #362 — the cap used to be applied to the directory listing, which made it a bound on WHICH\n * tasks were visible rather than on how much I/O ran at once. Every filter then ran on that\n * arbitrary readdir-ordered prefix. As a concurrency bound it does the job it was named for\n * without deciding what the caller gets to see; the caller's own bound on memory is whatever\n * `visit` chooses to retain.\n */\n private async forEachHandle(\n ids: readonly string[],\n visit: (handle: TaskHandle) => void | Promise<void>,\n ): Promise<void> {\n for (let start = 0; start < ids.length; start += JSON_LOAD_CAP) {\n const batch = ids.slice(start, start + JSON_LOAD_CAP);\n const loaded = await Promise.all(batch.map(async (id) => this.get(id)));\n for (const handle of loaded) {\n if (handle !== undefined) await visit(handle);\n }\n }\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n // Newest-first, keeping at most `limit` handles in memory regardless of how many match. The\n // order is what makes `submittedBefore` a real cursor: with the previous readdir order, a page\n // was an arbitrary subset, so a caller walking the timeline skipped every task that happened\n // to fall outside its window and could never come back for them.\n const newest: TaskHandle[] = [];\n await this.forEachHandle(this.candidateIds(), (handle) => {\n if (!matchesFilter(handle, filter)) return;\n const at = insertionIndex(newest, handle.submittedAt);\n if (at >= limit) return; // older than everything already held, and the page is full\n newest.splice(at, 0, handle);\n if (newest.length > limit) newest.pop();\n });\n return newest;\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n try {\n await unlink(this.filePath(id));\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw err;\n }\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n // #362 — eviction scans the directory itself rather than borrowing `list()`. Sharing that path\n // made one call incomplete twice over: it saw only a 256-file window, and it wanted the OLDEST\n // handles while `list()` is ordered newest-first — so on a large directory it could delete\n // nothing while thousands of eligible handles sat just outside the page. Sweeping every\n // candidate is what lets one call mean \"everything eligible is gone\".\n let count = 0;\n await this.forEachHandle(this.candidateIds(), async (handle) => {\n if (!TERMINAL_STATES.includes(handle.state)) return;\n const ts = terminalTimestamp(handle);\n if (ts === undefined || ts >= epochMs) return;\n if (await this.delete(handle.id)) count++;\n });\n return count;\n }\n}\n\n/** Factory used by `TaskRegistry.configure` (D364). */\nexport function getTaskStoreFor(options: TaskStoreOptions): TaskStore {\n if (options.backend === \"memory\") return new InMemoryTaskStore();\n return new JsonFileTaskStore(options.dir);\n}\n"]}
1
+ {"version":3,"sources":["../src/types/task.ts","../src/internal/task/store.ts"],"names":["InvalidTaskIdError","mkdirSync","join","atomicWriteText","readFile","diag","readdirSync","unlink"],"mappings":";;;;;;;;;;AAwJA,IAAM,eAAA,GAAkB,uBAAA;AAGxB,IAAM,iBAAA,GAAoB,CAAC,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAUxC,SAAS,aAAA,CAAc,IAAY,aAAA,EAAiC;AACzE,EAAA,IAAI,CAAC,eAAA,CAAgB,IAAA,CAAK,EAAE,GAAG,OAAO,KAAA;AACtC,EAAA,IAAI,eAAe,OAAO,IAAA;AAC1B,EAAA,KAAA,MAAW,UAAU,iBAAA,EAAmB;AACtC,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,MAAM,CAAA,EAAG,OAAO,KAAA;AAAA,EACpC;AACA,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,sBAAA,GAA4C;ACxIzD,IAAM,aAAA,GAAgB,GAAA;AACtB,IAAM,kBAAA,GAAqB,GAAA;AAuB3B,SAAS,sBAAsB,EAAA,EAAkB;AAC/C,EAAA,IAAI,CAAC,aAAA;AAAA,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AAI;AAAA,IACxC,CAAC,CAAA;AACD,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEA,MAAM,OAAO,EAAA,EAA8B;AACzC,IAAA,qBAAA,CAAsB,EAAE,CAAA;AACxB,IAAA,IAAI;AACF,MAAA,MAAMC,eAAA,CAAO,IAAA,CAAK,QAAA,CAAS,EAAE,CAAC,CAAA;AAC9B,MAAA,OAAO,IAAA;AAAA,IACT,SAAS,GAAA,EAAK;AACZ,MAAA,IAAK,GAAA,CAA8B,IAAA,KAAS,QAAA,EAAU,OAAO,KAAA;AAC7D,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,uBAAuB,OAAA,EAAkC;AAM7D,IAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,IAAA,MAAM,KAAK,aAAA,CAAc,IAAA,CAAK,YAAA,EAAa,EAAG,OAAO,MAAA,KAAW;AAC9D,MAAA,IAAI,CAAC,eAAA,CAAgB,QAAA,CAAS,MAAA,CAAO,KAAK,CAAA,EAAG;AAC7C,MAAA,MAAM,EAAA,GAAK,kBAAkB,MAAM,CAAA;AACnC,MAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,IAAM,OAAA,EAAS;AACvC,MAAA,IAAI,MAAM,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,EAAE,CAAA,EAAG,KAAA,EAAA;AAAA,IACpC,CAAC,CAAA;AACD,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,gBAAgB,OAAA,EAAsC;AACpE,EAAA,IAAI,OAAA,CAAQ,OAAA,KAAY,QAAA,EAAU,OAAO,IAAI,iBAAA,EAAkB;AAC/D,EAAA,OAAO,IAAI,iBAAA,CAAkB,OAAA,CAAQ,GAAG,CAAA;AAC1C","file":"chunk-RFMBZPOW.cjs","sourcesContent":["/**\n * Public type contract for the Task observability registry (ADRs D361-D374).\n *\n * Tasks are an opt-in observability layer over async work in the SDK\n * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have\n * a closed 5-state lifecycle (D362), discriminated events (D366), and a\n * pluggable store (D364). The `Task` facade in `task.ts` is the public\n * surface; consumers import these types from `@theokit/sdk`.\n *\n * @public\n */\n\n/**\n * Closed enum of the 5 lifecycle states (D362).\n *\n * Transitions are acyclic:\n * queued → running → (finished | error | cancelled)\n * queued → cancelled (direct, no run started)\n */\nexport type TaskState = \"queued\" | \"running\" | \"finished\" | \"error\" | \"cancelled\";\n\n/** Discriminator of the runtime that produced a task (D374). */\nexport type TaskKind = \"run\" | \"batch\" | \"workflow\" | \"cron\" | \"custom\";\n\n/** Discriminated union of task lifecycle events (D366). */\nexport type TaskEvent =\n | {\n readonly type: \"submitted\";\n readonly taskId: string;\n readonly kind: TaskKind;\n readonly submittedAt: number;\n readonly meta?: Record<string, unknown>;\n /** D372 — flag set on the first yielded event when the ring buffer was at cap. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"started\"; readonly taskId: string; readonly startedAt: number }\n | {\n readonly type: \"progress\";\n readonly taskId: string;\n readonly at: number;\n readonly payload: unknown;\n }\n | {\n readonly type: \"finished\";\n readonly taskId: string;\n readonly finishedAt: number;\n readonly result: unknown;\n }\n | {\n readonly type: \"errored\";\n readonly taskId: string;\n readonly erroredAt: number;\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly type: \"cancelled\";\n readonly taskId: string;\n readonly cancelledAt: number;\n readonly reason?: string;\n };\n\n/** Public read-only view of a task entry in the registry. */\nexport interface TaskHandle {\n readonly id: string;\n readonly kind: TaskKind;\n readonly state: TaskState;\n readonly submittedAt: number;\n readonly startedAt?: number;\n readonly finishedAt?: number;\n readonly cancelledAt?: number;\n readonly erroredAt?: number;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly meta?: Record<string, unknown>;\n /**\n * EC-7 — cross-process best-effort cancel flag. Set by CLI\n * `theokit tasks cancel` via JsonFileTaskStore. The owning process\n * polls at checkpoints and honors via AbortController. Always\n * `undefined` for in-process cancel paths (which go directly through\n * AbortController).\n */\n readonly cancelRequested?: boolean;\n /**\n * Why the task was cancelled, when whoever cancelled it said. Free text, written alongside\n * `cancelledAt` for a `queued` task and alongside `cancelRequested` for a `running` one.\n *\n * Absent when no reason was given — an empty string is not a reason, and a default like\n * \"cancelled\" would put words in the operator's mouth. `theokit tasks cancel --reason` is what\n * writes it (#351); nothing in the runtime reads it, because it exists for the human reading the\n * registry later.\n */\n readonly cancelReason?: string;\n}\n\n/** Query filter for `Task.list`. */\nexport interface TaskFilter {\n readonly state?: TaskState | readonly TaskState[];\n readonly kind?: TaskKind | readonly TaskKind[];\n readonly submittedAfter?: number;\n readonly submittedBefore?: number;\n /**\n * Defaults to 100. `JsonFileTaskStore` returns the newest matching tasks first and reads its\n * whole directory to find them (256 files at a time); page past this limit with\n * `submittedBefore` (#362).\n */\n readonly limit?: number;\n}\n\n/** Options for `Task.submit`. */\nexport interface TaskSubmitOptions {\n /**\n * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`\n * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`\n * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.\n */\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Optional caller-provided AbortSignal. If already aborted at submit\n * time, the registry short-circuits to `cancelled` without acquiring\n * a semaphore slot (EC-4).\n */\n readonly signal?: AbortSignal;\n /**\n * SE2 — an opt-in {@link import(\"./run-events.js\").RunEventSink}. The task's\n * lifecycle is forwarded to it as typed `task_started` / `task_updated` /\n * `task_completed` RunEvents, so a caller that spawned the task can observe it\n * through the same `onRunEvent` channel as the rest of the run. Best-effort (a\n * throwing sink never breaks the task). The dedicated `Task.subscribe(id)`\n * channel is unaffected.\n */\n readonly onRunEvent?: import(\"./run-events.js\").RunEventSink;\n}\n\n/** Options shape for `TaskStore` factory (D364). */\nexport type TaskStoreOptions =\n | { readonly backend: \"memory\" }\n | { readonly backend: \"json\"; readonly dir: string };\n\n/** Result of `Task.cancel` (D365 — idempotent). */\nexport interface TaskCancelResult {\n readonly cancelled: boolean;\n readonly alreadyTerminal: boolean;\n}\n\n/**\n * Grammar for user-supplied task IDs (D368).\n * `crypto.randomUUID()` outputs do NOT match this (UUIDs have dashes\n * AND uppercase letters in their canonical form on some Node versions),\n * but the registry normalizes auto-generated IDs to lowercase before\n * insertion, so they pass the same regex.\n */\nconst TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\n/** Reserved prefixes for adapter-generated IDs (D368, EC-5). */\nconst RESERVED_PREFIXES = [\"wf-\", \"b-\", \"cron-\"] as const;\n\n/**\n * Validates a task ID against the public grammar + reserved prefixes.\n * Throws `InvalidTaskIdError` from `../errors.js` on rejection.\n *\n * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`\n * to register their own IDs; user-facing surfaces (`Task.submit`,\n * `agent.send({ task: { id } })`) leave it false.\n */\nexport function isValidTaskId(id: string, allowReserved: boolean): boolean {\n if (!TASK_ID_GRAMMAR.test(id)) return false;\n if (allowReserved) return true;\n for (const prefix of RESERVED_PREFIXES) {\n if (id.startsWith(prefix)) return false;\n }\n return true;\n}\n\n/** Re-exported for adapter implementations + tests. */\nexport const TASK_RESERVED_PREFIXES: readonly string[] = RESERVED_PREFIXES;\n","/**\n * `TaskStore` interface + 2 implementations (ADR D364).\n *\n * - `InMemoryTaskStore` — default, transient, single-process.\n * - `JsonFileTaskStore` — opt-in, one JSON file per task under a\n * dedicated dir; single-process invariant (EC-15 documented).\n *\n * Edge cases absorbed:\n * - EC-1: constructor auto-creates dir (mkdirSync recursive idempotent).\n * - EC-2: every method validates the task id against the public\n * grammar (D368) BEFORE doing any path I/O — path-traversal defense.\n * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).\n * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted\n * atomic writes.\n * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap.\n * It no longer advertises `submittedBefore` as a way to page past it:\n * the cap is applied to the raw directory listing before any filter, so\n * paging beyond 256 files is not reachable through this interface.\n * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the\n * single-process invariant; v0.2 SQLite covers cross-process.\n *\n * @internal\n */\n\nimport { mkdirSync, readdirSync } from \"node:fs\";\nimport { readFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskFilter,\n type TaskHandle,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nconst JSON_LOAD_CAP = 256;\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Storage interface used by `TaskRegistry`. */\nexport interface TaskStore {\n insert(handle: TaskHandle): Promise<void>;\n update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;\n get(id: string): Promise<TaskHandle | undefined>;\n /**\n * Returns at most `filter.limit ?? 100` matching handles.\n *\n * `JsonFileTaskStore` returns them newest-first and considers every task in its\n * directory, reading at most 256 files concurrently (#362 — that number bounds\n * I/O, not which tasks are visible). Walk past `limit` by passing the oldest\n * `submittedAt` of a page as the next call's `submittedBefore`; the ordering is\n * what makes that a cursor rather than a re-roll of an arbitrary subset.\n * `InMemoryTaskStore` applies the same filters but does not order its result.\n */\n list(filter: TaskFilter): Promise<TaskHandle[]>;\n delete(id: string): Promise<boolean>;\n /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */\n evictTerminalOlderThan(epochMs: number): Promise<number>;\n}\n\nfunction assertValidIdForStore(id: string): void {\n if (!isValidTaskId(id, /* allowReserved */ true)) {\n throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);\n }\n}\n\nfunction terminalTimestamp(h: TaskHandle): number | undefined {\n if (h.state === \"finished\") return h.finishedAt;\n if (h.state === \"error\") return h.erroredAt;\n if (h.state === \"cancelled\") return h.cancelledAt;\n return undefined;\n}\n\nfunction isTerminal(state: TaskState): boolean {\n return state === \"finished\" || state === \"error\" || state === \"cancelled\";\n}\n\nfunction matchesState(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.state === undefined) return true;\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n return states.includes(h.state);\n}\nfunction matchesKind(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.kind === undefined) return true;\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n return kinds.includes(h.kind);\n}\nfunction matchesTime(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.submittedAfter !== undefined && h.submittedAt <= filter.submittedAfter) return false;\n if (filter.submittedBefore !== undefined && h.submittedAt >= filter.submittedBefore) return false;\n return true;\n}\nfunction matchesFilter(h: TaskHandle, filter: TaskFilter): boolean {\n return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);\n}\n\n/** The states `evictTerminalOlderThan` considers terminal. */\nconst TERMINAL_STATES: readonly TaskState[] = [\"finished\", \"error\", \"cancelled\"];\n\n/**\n * Where `submittedAt` belongs in a newest-first list — the first index whose entry is older.\n *\n * Linear rather than binary: the list is bounded by the caller's `limit` (100 by default) and the\n * scan runs once per MATCHING handle, so the comparison count is dwarfed by the file read that\n * produced the handle. A binary search here would trade a real cost for an imagined one.\n */\nfunction insertionIndex(newestFirst: readonly TaskHandle[], submittedAt: number): number {\n for (let i = 0; i < newestFirst.length; i++) {\n const entry = newestFirst[i];\n if (entry !== undefined && entry.submittedAt < submittedAt) return i;\n }\n return newestFirst.length;\n}\n\nfunction applyFilter(values: Iterable<TaskHandle>, filter: TaskFilter): TaskHandle[] {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n const out: TaskHandle[] = [];\n for (const h of values) {\n if (matchesFilter(h, filter)) {\n out.push(h);\n if (out.length >= limit) break;\n }\n }\n return out;\n}\n\n/* ─── InMemory ─── */\n\n/**\n * Default `TaskStore` — a plain `Map` living in the current process.\n *\n * Nothing reaches disk and nothing survives the process, so a task recorded here\n * is invisible to a reader in another process (`theokit tasks`). Select it with\n * `getTaskStoreFor({ backend: \"memory\" })`.\n *\n * How it fails: every id-taking method validates against the task-id grammar\n * (`^[a-z0-9][a-z0-9_-]*$`; reserved `wf-`/`b-`/`cron-` prefixes are permitted\n * here) and throws `InvalidTaskIdError` before touching the map. A missing id is\n * reported by returning `undefined` (`get`, `update`) or `false` (`delete`), never\n * by throwing.\n *\n * Traps:\n * - `insert()` is a `Map.set`: an existing id is overwritten silently, not\n * rejected.\n * - `list()` walks in INSERTION order and stops as soon as `filter.limit ?? 100`\n * matches are collected. It never sorts, so the limit truncates an\n * oldest-first scan rather than returning the most recent tasks.\n * - Nothing evicts on its own; terminal handles accumulate until a caller invokes\n * `evictTerminalOlderThan`.\n */\nexport class InMemoryTaskStore implements TaskStore {\n private readonly map = new Map<string, TaskHandle>();\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n this.map.set(handle.id, handle);\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = this.map.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n this.map.set(id, next);\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n return this.map.get(id);\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n return applyFilter(this.map.values(), filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n return this.map.delete(id);\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n let count = 0;\n for (const [id, h] of this.map.entries()) {\n if (!isTerminal(h.state)) continue;\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n this.map.delete(id);\n count++;\n }\n }\n return count;\n }\n}\n\n/* ─── JsonFile (opt-in) ───\n *\n * IMPORTANT (EC-15): `JsonFileTaskStore` is **single-process**.\n * Concurrent writers from multiple Node processes against the same\n * directory may corrupt entries (atomic-write protects per-file, but\n * the `list()` scan + `update()` read-modify-write cycle is not\n * serialised across processes). Use only when the `TaskRegistry`\n * runs in exactly one process. v0.2 will add a SQLite backend with\n * the same interface for cross-process scenarios (D364 + D61).\n */\n/**\n * Opt-in `TaskStore` that keeps one JSON file per task under `dir`, so another\n * process can read the registry off disk.\n *\n * const store = new JsonFileTaskStore(\"/var/lib/theokit/tasks\");\n *\n * Two calls are synchronous, and both are deliberate: the constructor creates `dir`\n * recursively (`mkdirSync`), and `list()` scans it with `readdirSync` before awaiting\n * anything. Every other operation is async — `get` uses `readFile`, `delete` uses\n * `unlink`, and every write goes through an atomic temp-file-plus-rename.\n *\n * SINGLE-PROCESS ONLY — see the note above. Per-file atomicity does not make\n * `update()` safe: it is a read-modify-write, so two writers that both `get`\n * before either writes lose one of the two mutations. That is true within one\n * process as well as across processes.\n *\n * How it fails:\n * - An invalid id throws `InvalidTaskIdError` BEFORE any path is constructed.\n * That ordering is the path-traversal defence, and it is why ids are validated\n * rather than escaped.\n * - A missing task is `undefined` from `get` and `false` from `delete`.\n * - A file that exists but does not parse is NOT surfaced as an error: `get`\n * writes to the diagnostics channel and returns `undefined`, so a corrupted\n * task also silently vanishes from `list()`.\n * - `list()` returns `[]` when `dir` does not exist; any other `readdir` failure\n * (for example a permission error) throws.\n *\n * Traps:\n * - `list()` reads every task file in the directory (256 at a time) to apply the\n * filter, because `state`, `kind` and `submittedAt` live inside the files. On a\n * large directory that is a lot of I/O for one call; the memory it holds is\n * bounded by `limit`, the time is not.\n * - `list()` is `async`, but its directory scan is not: `readdirSync` blocks the event\n * loop for the whole listing before the first `await`. Only the per-file reads that\n * follow it are concurrent.\n * - Files whose name contains `.tmp` are skipped as orphans of an interrupted\n * write, and nothing ever removes them.\n */\nexport class JsonFileTaskStore implements TaskStore {\n constructor(private readonly dir: string) {\n // EC-1: idempotent mkdir; ignore EEXIST.\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n }\n\n private filePath(id: string): string {\n return join(this.dir, `${id}.json`);\n }\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = await this.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n await atomicWriteText(this.filePath(id), JSON.stringify(next));\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n try {\n const raw = await readFile(this.filePath(id), \"utf8\");\n return JSON.parse(raw) as TaskHandle;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n // Corrupt JSON or other I/O error — log + degrade gracefully (D50/EC-7 cache pattern).\n diag(`[task-store] failed to read ${id}: ${(err as Error).message}\\n`);\n return undefined;\n }\n }\n\n /**\n * Task ids backed by a file in `dir`, in readdir order.\n *\n * EC-8: orphan `.tmp` files left by an interrupted atomic write are skipped, as is any name\n * outside the id grammar. EC-6: a missing directory lists as empty; any other `readdir` failure\n * (a permission error, say) throws rather than being reported as \"no tasks\".\n */\n private candidateIds(): string[] {\n let entries: string[];\n try {\n entries = readdirSync(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return []; // EC-6\n throw err;\n }\n return entries\n .filter((name) => name.endsWith(\".json\") && !name.includes(\".tmp\"))\n .map((name) => name.slice(0, -\".json\".length))\n .filter((id) => isValidTaskId(id, true));\n }\n\n /**\n * Read every task in `ids`, handing each loaded handle to `visit`, at most `JSON_LOAD_CAP` file\n * reads in flight.\n *\n * #362 — the cap used to be applied to the directory listing, which made it a bound on WHICH\n * tasks were visible rather than on how much I/O ran at once. Every filter then ran on that\n * arbitrary readdir-ordered prefix. As a concurrency bound it does the job it was named for\n * without deciding what the caller gets to see; the caller's own bound on memory is whatever\n * `visit` chooses to retain.\n */\n private async forEachHandle(\n ids: readonly string[],\n visit: (handle: TaskHandle) => void | Promise<void>,\n ): Promise<void> {\n for (let start = 0; start < ids.length; start += JSON_LOAD_CAP) {\n const batch = ids.slice(start, start + JSON_LOAD_CAP);\n const loaded = await Promise.all(batch.map(async (id) => this.get(id)));\n for (const handle of loaded) {\n if (handle !== undefined) await visit(handle);\n }\n }\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n // Newest-first, keeping at most `limit` handles in memory regardless of how many match. The\n // order is what makes `submittedBefore` a real cursor: with the previous readdir order, a page\n // was an arbitrary subset, so a caller walking the timeline skipped every task that happened\n // to fall outside its window and could never come back for them.\n const newest: TaskHandle[] = [];\n await this.forEachHandle(this.candidateIds(), (handle) => {\n if (!matchesFilter(handle, filter)) return;\n const at = insertionIndex(newest, handle.submittedAt);\n if (at >= limit) return; // older than everything already held, and the page is full\n newest.splice(at, 0, handle);\n if (newest.length > limit) newest.pop();\n });\n return newest;\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n try {\n await unlink(this.filePath(id));\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw err;\n }\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n // #362 — eviction scans the directory itself rather than borrowing `list()`. Sharing that path\n // made one call incomplete twice over: it saw only a 256-file window, and it wanted the OLDEST\n // handles while `list()` is ordered newest-first — so on a large directory it could delete\n // nothing while thousands of eligible handles sat just outside the page. Sweeping every\n // candidate is what lets one call mean \"everything eligible is gone\".\n let count = 0;\n await this.forEachHandle(this.candidateIds(), async (handle) => {\n if (!TERMINAL_STATES.includes(handle.state)) return;\n const ts = terminalTimestamp(handle);\n if (ts === undefined || ts >= epochMs) return;\n if (await this.delete(handle.id)) count++;\n });\n return count;\n }\n}\n\n/** Factory used by `TaskRegistry.configure` (D364). */\nexport function getTaskStoreFor(options: TaskStoreOptions): TaskStore {\n if (options.backend === \"memory\") return new InMemoryTaskStore();\n return new JsonFileTaskStore(options.dir);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ConfigurationError, isTransientError } from './chunk-IDCKSLYH.js';
1
+ import { ConfigurationError, isTransientError } from './chunk-ZZMZWBR6.js';
2
2
 
3
3
  // src/internal/runtime/retry/with-retry.ts
4
4
  function defaultSleep(ms, signal) {
@@ -65,5 +65,5 @@ var Retry = class {
65
65
  };
66
66
 
67
67
  export { Retry };
68
- //# sourceMappingURL=chunk-NLTVXLGT.js.map
69
- //# sourceMappingURL=chunk-NLTVXLGT.js.map
68
+ //# sourceMappingURL=chunk-RFXWMRFC.js.map
69
+ //# sourceMappingURL=chunk-RFXWMRFC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/retry/with-retry.ts","../src/retry.ts"],"names":[],"mappings":";;;AAkCA,SAAS,YAAA,CAAa,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC5C,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,MAAA,CAAO,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AACvF,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,CAAO,MAAA,EAAQ,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AAAA,IAC1F;AACA,IAAA,MAAA,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AA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,OAAA,IAAW,IAAI,OAAA,IAAW,CAAC,IAAI,WAAA,CAAY,GAAG,GAAG,MAAM,GAAA;AAC3D,MAAA,MAAM,IAAI,KAAA,CAAM,SAAA,CAAU,KAAK,OAAO,CAAA,EAAG,IAAI,MAAM,CAAA;AACnD,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF;AACF;;;AC3FO,IAAM,QAAN,MAAY;AAAA,EACT,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,MAAA,CAAU,EAAA,EAAsB,OAAA,EAAoC;AACzE,IAAA,OAAO,SAAA,CAAU,IAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-NLTVXLGT.js","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/runtime/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — `Retry.create` replaces `withRetry` (ADR 0015 / ADR-P2). NOTE: `withRetry` is an\n * EXECUTOR, not a constructor — `Retry.create(fn, opts)` RUNS `fn` with retry and resolves to\n * its result (`Promise<T>`), not a `Retry` instance. The `.create` name is the uniformity\n * mandate; the executor semantics are the documented, accepted awkwardness. @public\n */\nexport class Retry {\n private constructor() {}\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/retry/with-retry.ts","../src/retry.ts"],"names":[],"mappings":";;;AAkCA,SAAS,YAAA,CAAa,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC5C,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,MAAA,CAAO,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AACvF,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAA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AAI,GAAA,CAAI,YAAY,GAAA,CAAI,cAAA,GAAiB,GAAA,CAAI,iBAAA,IAAqB,OAAO,CAAA;AAC9F,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,KAAQ,OAAO,CAAA;AACvC;AAWA,eAAsB,SAAA,CAAa,IAAsB,OAAA,EAAoC;AAC3F,EAAA,MAAM,GAAA,GAAM,oBAAoB,OAAO,CAAA;AACvC,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,WAAS;AACP,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,OAAA,IAAW,IAAI,OAAA,IAAW,CAAC,IAAI,WAAA,CAAY,GAAG,GAAG,MAAM,GAAA;AAC3D,MAAA,MAAM,IAAI,KAAA,CAAM,SAAA,CAAU,KAAK,OAAO,CAAA,EAAG,IAAI,MAAM,CAAA;AACnD,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF;AACF;;;AC3FO,IAAM,QAAN,MAAY;AAAA,EACT,WAAA,GAAc;AAAA,EAAC;AAAA,EACvB,OAAO,MAAA,CAAU,EAAA,EAAsB,OAAA,EAAoC;AACzE,IAAA,OAAO,SAAA,CAAU,IAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-RFXWMRFC.js","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/runtime/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — `Retry.create` replaces `withRetry` (ADR 0015 / ADR-P2). NOTE: `withRetry` is an\n * EXECUTOR, not a constructor — `Retry.create(fn, opts)` RUNS `fn` with retry and resolves to\n * its result (`Promise<T>`), not a `Retry` instance. The `.create` name is the uniformity\n * mandate; the executor semantics are the documented, accepted awkwardness. @public\n */\nexport class Retry {\n private constructor() {}\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { generateCronId } from './chunk-CHKH5452.js';
2
- import { submit } from './chunk-SUKXXLWD.js';
1
+ import { generateCronId } from './chunk-WHFUZMIC.js';
2
+ import { submit } from './chunk-A46SWMIF.js';
3
3
  import { getAgentFacade } from './chunk-6X6ID4MO.js';
4
- import { UnknownAgentError, ConfigurationError } from './chunk-IDCKSLYH.js';
5
- import { resolveApiKey } from './chunk-T7XEKOVW.js';
4
+ import { UnknownAgentError, ConfigurationError } from './chunk-ZZMZWBR6.js';
5
+ import { resolveApiKey } from './chunk-D4CUGAKZ.js';
6
6
  import { Cron as Cron$1 } from 'croner';
7
7
 
8
8
  // src/internal/cron/run-job.ts
@@ -452,5 +452,5 @@ async function updateJobStatus(jobId, enabled) {
452
452
  }
453
453
 
454
454
  export { Cron };
455
- //# sourceMappingURL=chunk-MG3SOM3M.js.map
456
- //# sourceMappingURL=chunk-MG3SOM3M.js.map
455
+ //# sourceMappingURL=chunk-RMIWHYC7.js.map
456
+ //# sourceMappingURL=chunk-RMIWHYC7.js.map