@theokit/sdk 4.53.1 → 4.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (692) hide show
  1. package/CHANGELOG.md +1088 -0
  2. package/README.md +9 -4
  3. package/dist/a2a/agent-mailbox.d.cts +27 -0
  4. package/dist/a2a/agent-mailbox.d.ts +27 -0
  5. package/dist/a2a/index.cjs +9 -4
  6. package/dist/a2a/index.cjs.map +1 -1
  7. package/dist/a2a/index.js +7 -2
  8. package/dist/a2a/index.js.map +1 -1
  9. package/dist/a2a/message-bus.d.cts +39 -0
  10. package/dist/a2a/message-bus.d.ts +39 -0
  11. package/dist/a2a/subagent.d.cts +68 -7
  12. package/dist/a2a/subagent.d.ts +68 -7
  13. package/dist/a2a/types.d.cts +26 -0
  14. package/dist/a2a/types.d.ts +26 -0
  15. package/dist/{agent-B9HXlwID.d.ts → agent-CIUgz7cN.d.cts} +190 -850
  16. package/dist/{agent-nLqeXKIX.d.cts → agent-DSec-E0c.d.ts} +190 -850
  17. package/dist/agent-NOEGF4GI.cjs +61 -0
  18. package/dist/{agent-YLAHVHEH.cjs.map → agent-NOEGF4GI.cjs.map} +1 -1
  19. package/dist/agent-VGD5WL4N.js +52 -0
  20. package/dist/{agent-FFVV4U5N.js.map → agent-VGD5WL4N.js.map} +1 -1
  21. package/dist/agent-builder.d.ts +19 -0
  22. package/dist/agent-session-store-P6V3FINW.js +7 -0
  23. package/dist/{agent-session-store-TNCGL5RN.js.map → agent-session-store-P6V3FINW.js.map} +1 -1
  24. package/dist/agent-session-store-ZJ3JSRS4.cjs +24 -0
  25. package/dist/{agent-session-store-DUGBAX5V.cjs.map → agent-session-store-ZJ3JSRS4.cjs.map} +1 -1
  26. package/dist/agent.d.ts +9 -6
  27. package/dist/auth/index.cjs +52 -35
  28. package/dist/auth/index.cjs.map +1 -1
  29. package/dist/auth/index.js +26 -9
  30. package/dist/auth/index.js.map +1 -1
  31. package/dist/{batch-UPKN4SG6.js → batch-2TGJMNCJ.js} +14 -13
  32. package/dist/batch-2TGJMNCJ.js.map +1 -0
  33. package/dist/{batch-ZEFN5SO7.cjs → batch-ND32UKZS.cjs} +31 -30
  34. package/dist/batch-ND32UKZS.cjs.map +1 -0
  35. package/dist/{chunk-TTJ54H3E.cjs → chunk-2ADR2GSO.cjs} +8 -8
  36. package/dist/chunk-2ADR2GSO.cjs.map +1 -0
  37. package/dist/{chunk-VGPXHHF3.cjs → chunk-2C72DXQF.cjs} +63 -27
  38. package/dist/chunk-2C72DXQF.cjs.map +1 -0
  39. package/dist/{chunk-4Q4K4WB5.js → chunk-2D34UTDC.js} +20 -4
  40. package/dist/chunk-2D34UTDC.js.map +1 -0
  41. package/dist/{chunk-UFIXH26P.js → chunk-2QKTVKH3.js} +4 -4
  42. package/dist/{chunk-UFIXH26P.js.map → chunk-2QKTVKH3.js.map} +1 -1
  43. package/dist/{chunk-GBBDINFK.js → chunk-3E77SX4H.js} +4 -4
  44. package/dist/{chunk-GBBDINFK.js.map → chunk-3E77SX4H.js.map} +1 -1
  45. package/dist/{chunk-VYHJZVL5.cjs → chunk-3EE6LVWT.cjs} +2 -2
  46. package/dist/chunk-3EE6LVWT.cjs.map +1 -0
  47. package/dist/chunk-3KGLRRFC.cjs +18 -0
  48. package/dist/chunk-3KGLRRFC.cjs.map +1 -0
  49. package/dist/{chunk-5NBUH3NO.js → chunk-3OR54XG4.js} +2 -2
  50. package/dist/{chunk-C6Y6CWYD.cjs.map → chunk-3OR54XG4.js.map} +1 -1
  51. package/dist/{chunk-ZN2DGEY3.cjs → chunk-3YJNUKYN.cjs} +15 -15
  52. package/dist/{chunk-ZN2DGEY3.cjs.map → chunk-3YJNUKYN.cjs.map} +1 -1
  53. package/dist/{chunk-POWRZSK4.js → chunk-44JAAH4X.js} +3 -3
  54. package/dist/{chunk-POWRZSK4.js.map → chunk-44JAAH4X.js.map} +1 -1
  55. package/dist/{chunk-SSDD676S.js → chunk-44MBDIHG.js} +4 -4
  56. package/dist/{chunk-SSDD676S.js.map → chunk-44MBDIHG.js.map} +1 -1
  57. package/dist/{chunk-OY7O3Q6R.js → chunk-4ERPXIVB.js} +5 -5
  58. package/dist/{chunk-OY7O3Q6R.js.map → chunk-4ERPXIVB.js.map} +1 -1
  59. package/dist/{chunk-3BK6YR5P.cjs → chunk-4I55V454.cjs} +4 -4
  60. package/dist/{chunk-3BK6YR5P.cjs.map → chunk-4I55V454.cjs.map} +1 -1
  61. package/dist/{chunk-B4YA6BRS.cjs → chunk-4O5TGQBW.cjs} +30 -7
  62. package/dist/chunk-4O5TGQBW.cjs.map +1 -0
  63. package/dist/{chunk-4JBHSLQO.cjs → chunk-4OTIXDMU.cjs} +2 -2
  64. package/dist/{chunk-4JBHSLQO.cjs.map → chunk-4OTIXDMU.cjs.map} +1 -1
  65. package/dist/{chunk-C6Y6CWYD.cjs → chunk-52NKC5HT.cjs} +2 -2
  66. package/dist/chunk-52NKC5HT.cjs.map +1 -0
  67. package/dist/{chunk-665SFFFR.cjs → chunk-53CBTBWO.cjs} +11 -11
  68. package/dist/{chunk-665SFFFR.cjs.map → chunk-53CBTBWO.cjs.map} +1 -1
  69. package/dist/{chunk-2D43RD5D.cjs → chunk-5BJV5UPY.cjs} +27 -27
  70. package/dist/chunk-5BJV5UPY.cjs.map +1 -0
  71. package/dist/{chunk-FFM3SJTQ.js → chunk-5JLFFPCH.js} +4 -4
  72. package/dist/{chunk-FFM3SJTQ.js.map → chunk-5JLFFPCH.js.map} +1 -1
  73. package/dist/{chunk-34XOCZJO.js → chunk-5PHVENFV.js} +3 -3
  74. package/dist/chunk-5PHVENFV.js.map +1 -0
  75. package/dist/{chunk-BDTVFIPB.cjs → chunk-5UOVYM3P.cjs} +36 -31
  76. package/dist/chunk-5UOVYM3P.cjs.map +1 -0
  77. package/dist/{chunk-VF7X6HDR.cjs → chunk-5USCYPPI.cjs} +15 -15
  78. package/dist/{chunk-VF7X6HDR.cjs.map → chunk-5USCYPPI.cjs.map} +1 -1
  79. package/dist/{chunk-D24WJWN2.js → chunk-AEOZTXVW.js} +3 -3
  80. package/dist/{chunk-D24WJWN2.js.map → chunk-AEOZTXVW.js.map} +1 -1
  81. package/dist/{chunk-DGOG5NXR.js → chunk-AG5JPQIY.js} +3 -3
  82. package/dist/{chunk-DGOG5NXR.js.map → chunk-AG5JPQIY.js.map} +1 -1
  83. package/dist/{chunk-V6HWJQQV.js → chunk-AGSBJD2L.js} +27 -30
  84. package/dist/chunk-AGSBJD2L.js.map +1 -0
  85. package/dist/{chunk-BFYGJGC5.js → chunk-AQLGBKNT.js} +3 -3
  86. package/dist/chunk-AQLGBKNT.js.map +1 -0
  87. package/dist/{chunk-7W7ZWMLQ.js → chunk-AWO27VRZ.js} +3 -3
  88. package/dist/chunk-AWO27VRZ.js.map +1 -0
  89. package/dist/{chunk-VYCKUKPA.cjs → chunk-B2J4ZMZL.cjs} +3 -2
  90. package/dist/chunk-B2J4ZMZL.cjs.map +1 -0
  91. package/dist/{chunk-BERBYXFH.js → chunk-BMAZLQQ4.js} +3 -3
  92. package/dist/{chunk-BERBYXFH.js.map → chunk-BMAZLQQ4.js.map} +1 -1
  93. package/dist/{chunk-5YKNEMXR.cjs → chunk-BVZW2B5V.cjs} +4 -4
  94. package/dist/chunk-BVZW2B5V.cjs.map +1 -0
  95. package/dist/{chunk-MSFLYJDY.js → chunk-CQ2TQ32Y.js} +4 -4
  96. package/dist/chunk-CQ2TQ32Y.js.map +1 -0
  97. package/dist/{chunk-C5DEO6OI.cjs → chunk-CQGYNZ3K.cjs} +4 -4
  98. package/dist/{chunk-C5DEO6OI.cjs.map → chunk-CQGYNZ3K.cjs.map} +1 -1
  99. package/dist/{chunk-D75S2X6I.cjs → chunk-CTCGWIUD.cjs} +5 -5
  100. package/dist/{chunk-D75S2X6I.cjs.map → chunk-CTCGWIUD.cjs.map} +1 -1
  101. package/dist/{chunk-NZL4BNFQ.js → chunk-CV7XMBHP.js} +4 -4
  102. package/dist/chunk-CV7XMBHP.js.map +1 -0
  103. package/dist/{chunk-SEL2ZQMT.js → chunk-DAPSQZT4.js} +15 -10
  104. package/dist/chunk-DAPSQZT4.js.map +1 -0
  105. package/dist/{chunk-SVO5WPZX.cjs → chunk-DQKERTND.cjs} +11 -11
  106. package/dist/{chunk-SVO5WPZX.cjs.map → chunk-DQKERTND.cjs.map} +1 -1
  107. package/dist/{chunk-GOVJO4YE.js → chunk-DUIF54UP.js} +6 -6
  108. package/dist/chunk-DUIF54UP.js.map +1 -0
  109. package/dist/{chunk-N5CR3TJZ.js → chunk-DZBSJX6J.js} +4 -4
  110. package/dist/{chunk-N5CR3TJZ.js.map → chunk-DZBSJX6J.js.map} +1 -1
  111. package/dist/{chunk-RAHSWE5C.cjs → chunk-EI2Q7SJ5.cjs} +12 -12
  112. package/dist/chunk-EI2Q7SJ5.cjs.map +1 -0
  113. package/dist/{chunk-UCFONJBG.js → chunk-EPSICJLZ.js} +2 -2
  114. package/dist/{chunk-UCFONJBG.js.map → chunk-EPSICJLZ.js.map} +1 -1
  115. package/dist/{chunk-3X6PM7DU.cjs → chunk-F3YZMOAU.cjs} +8 -8
  116. package/dist/{chunk-3X6PM7DU.cjs.map → chunk-F3YZMOAU.cjs.map} +1 -1
  117. package/dist/{chunk-HE4BIAOS.js → chunk-F7AQV62G.js} +5 -4
  118. package/dist/chunk-F7AQV62G.js.map +1 -0
  119. package/dist/{chunk-HSQ5Q3I5.js → chunk-FXEUP75G.js} +5 -5
  120. package/dist/chunk-FXEUP75G.js.map +1 -0
  121. package/dist/{chunk-2RW7K6FN.cjs → chunk-GHX4P3V2.cjs} +2 -2
  122. package/dist/chunk-GHX4P3V2.cjs.map +1 -0
  123. package/dist/{chunk-B6HOIWQ6.js → chunk-GJ6RK75E.js} +5 -5
  124. package/dist/chunk-GJ6RK75E.js.map +1 -0
  125. package/dist/{chunk-FOXKFTVZ.cjs → chunk-GNT35C5U.cjs} +13 -13
  126. package/dist/chunk-GNT35C5U.cjs.map +1 -0
  127. package/dist/{chunk-4NAKHID5.js → chunk-GTKFV7O5.js} +2 -2
  128. package/dist/chunk-GTKFV7O5.js.map +1 -0
  129. package/dist/{chunk-ELKO4ZLR.cjs → chunk-GWC3HADL.cjs} +4 -4
  130. package/dist/{chunk-ELKO4ZLR.cjs.map → chunk-GWC3HADL.cjs.map} +1 -1
  131. package/dist/{chunk-OXNYIMZZ.js → chunk-H73MEMQB.js} +2 -2
  132. package/dist/chunk-H73MEMQB.js.map +1 -0
  133. package/dist/{chunk-E7FJOO4G.cjs → chunk-HJBMA5MB.cjs} +11 -11
  134. package/dist/{chunk-E7FJOO4G.cjs.map → chunk-HJBMA5MB.cjs.map} +1 -1
  135. package/dist/{chunk-VW6M4B3Z.cjs → chunk-HY57ULY2.cjs} +5 -5
  136. package/dist/{chunk-VW6M4B3Z.cjs.map → chunk-HY57ULY2.cjs.map} +1 -1
  137. package/dist/{chunk-CAH3G4IS.js → chunk-HY66GLM6.js} +2 -2
  138. package/dist/chunk-HY66GLM6.js.map +1 -0
  139. package/dist/{chunk-C4H6PB5J.cjs → chunk-I6TGFUCO.cjs} +4 -4
  140. package/dist/{chunk-C4H6PB5J.cjs.map → chunk-I6TGFUCO.cjs.map} +1 -1
  141. package/dist/{chunk-U4UJHOSH.js → chunk-IDCKSLYH.js} +3 -3
  142. package/dist/{chunk-U4UJHOSH.js.map → chunk-IDCKSLYH.js.map} +1 -1
  143. package/dist/{chunk-WQ53UQL4.cjs → chunk-ILCGLTSA.cjs} +4 -4
  144. package/dist/{chunk-WQ53UQL4.cjs.map → chunk-ILCGLTSA.cjs.map} +1 -1
  145. package/dist/{chunk-SZHU7A5B.cjs → chunk-IWBGCBR6.cjs} +4 -4
  146. package/dist/{chunk-SZHU7A5B.cjs.map → chunk-IWBGCBR6.cjs.map} +1 -1
  147. package/dist/{chunk-Q4RESANI.cjs → chunk-J24VJOH3.cjs} +20 -4
  148. package/dist/chunk-J24VJOH3.cjs.map +1 -0
  149. package/dist/{chunk-Y4AXQOT4.cjs → chunk-JHPGF3FP.cjs} +8 -8
  150. package/dist/{chunk-Y4AXQOT4.cjs.map → chunk-JHPGF3FP.cjs.map} +1 -1
  151. package/dist/{chunk-BM6N4KHO.cjs → chunk-JTB5Q42C.cjs} +6 -22
  152. package/dist/chunk-JTB5Q42C.cjs.map +1 -0
  153. package/dist/{chunk-LPVIRJVF.cjs → chunk-K3FW2XZD.cjs} +9 -9
  154. package/dist/{chunk-LPVIRJVF.cjs.map → chunk-K3FW2XZD.cjs.map} +1 -1
  155. package/dist/{chunk-XPR366DL.cjs → chunk-NGESVVJN.cjs} +17 -17
  156. package/dist/chunk-NGESVVJN.cjs.map +1 -0
  157. package/dist/{chunk-VC5ABJXC.js → chunk-NLTVXLGT.js} +3 -3
  158. package/dist/{chunk-VC5ABJXC.js.map → chunk-NLTVXLGT.js.map} +1 -1
  159. package/dist/chunk-NUKRL3I6.cjs +23 -0
  160. package/dist/chunk-NUKRL3I6.cjs.map +1 -0
  161. package/dist/{chunk-R5YZACGK.js → chunk-OC4NTGMN.js} +3 -3
  162. package/dist/{chunk-R5YZACGK.js.map → chunk-OC4NTGMN.js.map} +1 -1
  163. package/dist/{chunk-FPYT5WZP.cjs → chunk-P6A3M6VD.cjs} +10 -10
  164. package/dist/{chunk-FPYT5WZP.cjs.map → chunk-P6A3M6VD.cjs.map} +1 -1
  165. package/dist/{chunk-OKLYRPKL.cjs → chunk-Q47R5E2X.cjs} +8 -8
  166. package/dist/chunk-Q47R5E2X.cjs.map +1 -0
  167. package/dist/{chunk-2XLKLVVR.js → chunk-Q5EWJPRY.js} +2 -2
  168. package/dist/chunk-Q5EWJPRY.js.map +1 -0
  169. package/dist/{chunk-SK4QLUBK.js → chunk-QARJGQSA.js} +16 -7
  170. package/dist/chunk-QARJGQSA.js.map +1 -0
  171. package/dist/{chunk-CZ2GKKYL.cjs → chunk-QDED6YO6.cjs} +5 -5
  172. package/dist/{chunk-CZ2GKKYL.cjs.map → chunk-QDED6YO6.cjs.map} +1 -1
  173. package/dist/{chunk-VK7MAV65.cjs → chunk-QKLOP4VC.cjs} +2 -2
  174. package/dist/{chunk-VK7MAV65.cjs.map → chunk-QKLOP4VC.cjs.map} +1 -1
  175. package/dist/{chunk-FIOCJYLA.js → chunk-QRSUA2CV.js} +3 -3
  176. package/dist/{chunk-FIOCJYLA.js.map → chunk-QRSUA2CV.js.map} +1 -1
  177. package/dist/{chunk-ZT57WTUJ.cjs → chunk-R3UPQFKK.cjs} +21 -12
  178. package/dist/chunk-R3UPQFKK.cjs.map +1 -0
  179. package/dist/{chunk-X2FR4OIT.js → chunk-R7WIIPUR.js} +2 -2
  180. package/dist/chunk-R7WIIPUR.js.map +1 -0
  181. package/dist/{chunk-VUKQL3L2.cjs → chunk-RM7Y65IG.cjs} +13 -13
  182. package/dist/chunk-RM7Y65IG.cjs.map +1 -0
  183. package/dist/{chunk-RP5HQVLD.js → chunk-RNB4APBZ.js} +30 -7
  184. package/dist/chunk-RNB4APBZ.js.map +1 -0
  185. package/dist/{chunk-GD63JPGC.cjs → chunk-ROYPRJH4.cjs} +9 -9
  186. package/dist/{chunk-GD63JPGC.cjs.map → chunk-ROYPRJH4.cjs.map} +1 -1
  187. package/dist/{chunk-V26QVGUG.js → chunk-RUDY2GTT.js} +59 -23
  188. package/dist/chunk-RUDY2GTT.js.map +1 -0
  189. package/dist/{chunk-JIQRXKTA.cjs → chunk-SKXBJ2NU.cjs} +7 -7
  190. package/dist/chunk-SKXBJ2NU.cjs.map +1 -0
  191. package/dist/chunk-SSQZA3DZ.js +15 -0
  192. package/dist/chunk-SSQZA3DZ.js.map +1 -0
  193. package/dist/{chunk-XROIW6BH.js → chunk-SUKXXLWD.js} +6 -6
  194. package/dist/chunk-SUKXXLWD.js.map +1 -0
  195. package/dist/{chunk-LTSTGCL6.js → chunk-T73NA43R.js} +3 -3
  196. package/dist/{chunk-LTSTGCL6.js.map → chunk-T73NA43R.js.map} +1 -1
  197. package/dist/chunk-T7O6K6PX.js +20 -0
  198. package/dist/chunk-T7O6K6PX.js.map +1 -0
  199. package/dist/{chunk-5F5NWKPN.js → chunk-T7XEKOVW.js} +5 -20
  200. package/dist/chunk-T7XEKOVW.js.map +1 -0
  201. package/dist/{chunk-G3JWXOGY.js → chunk-TPTZA6NI.js} +250 -103
  202. package/dist/chunk-TPTZA6NI.js.map +1 -0
  203. package/dist/{chunk-QBTVATSF.cjs → chunk-TTHBHAJI.cjs} +44 -47
  204. package/dist/chunk-TTHBHAJI.cjs.map +1 -0
  205. package/dist/{chunk-HAWE74GQ.cjs → chunk-U2AC6JUP.cjs} +8 -8
  206. package/dist/chunk-U2AC6JUP.cjs.map +1 -0
  207. package/dist/{chunk-3WVMJY7F.js → chunk-UC3HT2S4.js} +3 -3
  208. package/dist/{chunk-3WVMJY7F.js.map → chunk-UC3HT2S4.js.map} +1 -1
  209. package/dist/{chunk-F77UENR6.cjs → chunk-UFAO4T7Z.cjs} +526 -379
  210. package/dist/chunk-UFAO4T7Z.cjs.map +1 -0
  211. package/dist/{chunk-2FYEVT2B.cjs → chunk-UNDROG5N.cjs} +201 -154
  212. package/dist/chunk-UNDROG5N.cjs.map +1 -0
  213. package/dist/{chunk-PBZ7HMBP.js → chunk-UPRJR6IP.js} +4 -4
  214. package/dist/chunk-UPRJR6IP.js.map +1 -0
  215. package/dist/{chunk-3V7UJLQT.js → chunk-UQGQFBRL.js} +3 -3
  216. package/dist/chunk-UQGQFBRL.js.map +1 -0
  217. package/dist/{chunk-LS3LMQ23.js → chunk-VDEWG5TV.js} +88 -43
  218. package/dist/chunk-VDEWG5TV.js.map +1 -0
  219. package/dist/{chunk-6AZDM6LK.js → chunk-VF7EWVDG.js} +3 -3
  220. package/dist/{chunk-6AZDM6LK.js.map → chunk-VF7EWVDG.js.map} +1 -1
  221. package/dist/{chunk-PNVDQL5Y.cjs → chunk-VTYY7XL5.cjs} +2 -2
  222. package/dist/chunk-VTYY7XL5.cjs.map +1 -0
  223. package/dist/{chunk-Y4I4EQFK.js → chunk-WKRSH2VR.js} +3 -3
  224. package/dist/{chunk-Y4I4EQFK.js.map → chunk-WKRSH2VR.js.map} +1 -1
  225. package/dist/{chunk-4QEC4CCS.js → chunk-WTMU7J4U.js} +2 -2
  226. package/dist/{chunk-4QEC4CCS.js.map → chunk-WTMU7J4U.js.map} +1 -1
  227. package/dist/{chunk-KSWHTR54.js → chunk-XN7NOENA.js} +6 -6
  228. package/dist/chunk-XN7NOENA.js.map +1 -0
  229. package/dist/{chunk-ADLLFY3H.cjs → chunk-XSX2UU6Y.cjs} +10 -9
  230. package/dist/chunk-XSX2UU6Y.cjs.map +1 -0
  231. package/dist/{chunk-LD4MOBFX.js → chunk-XV4IZNV4.js} +9 -9
  232. package/dist/chunk-XV4IZNV4.js.map +1 -0
  233. package/dist/{chunk-EZ2YEF4F.cjs → chunk-XWL6O3SW.cjs} +4 -4
  234. package/dist/chunk-XWL6O3SW.cjs.map +1 -0
  235. package/dist/{chunk-PGP7IOJ2.js → chunk-YMA4S2WO.js} +4 -4
  236. package/dist/{chunk-PGP7IOJ2.js.map → chunk-YMA4S2WO.js.map} +1 -1
  237. package/dist/{chunk-OUOXM36O.cjs → chunk-YPJ5NH5N.cjs} +11 -11
  238. package/dist/chunk-YPJ5NH5N.cjs.map +1 -0
  239. package/dist/{chunk-YLQQX5W2.cjs → chunk-ZF2LDKQQ.cjs} +2 -2
  240. package/dist/chunk-ZF2LDKQQ.cjs.map +1 -0
  241. package/dist/{chunk-L5YO6PWL.cjs → chunk-ZNW6V4Y6.cjs} +2 -2
  242. package/dist/chunk-ZNW6V4Y6.cjs.map +1 -0
  243. package/dist/client/index.cjs.map +1 -1
  244. package/dist/client/index.js.map +1 -1
  245. package/dist/client/theokit-client.d.cts +36 -0
  246. package/dist/client/theokit-client.d.ts +36 -0
  247. package/dist/client/types.d.cts +30 -0
  248. package/dist/client/types.d.ts +30 -0
  249. package/dist/compact-session-K5LXTBPJ.js +22 -0
  250. package/dist/{compact-session-4MNKNMO2.js.map → compact-session-K5LXTBPJ.js.map} +1 -1
  251. package/dist/compact-session-YCT6JMBX.cjs +59 -0
  252. package/dist/{compact-session-EPFBQ46Z.cjs.map → compact-session-YCT6JMBX.cjs.map} +1 -1
  253. package/dist/compaction.cjs +17 -16
  254. package/dist/compaction.d.cts +13 -13
  255. package/dist/compaction.d.ts +13 -13
  256. package/dist/compaction.js +4 -3
  257. package/dist/concurrency.cjs +7 -6
  258. package/dist/concurrency.cjs.map +1 -1
  259. package/dist/concurrency.js +5 -4
  260. package/dist/concurrency.js.map +1 -1
  261. package/dist/context/index.cjs +7 -7
  262. package/dist/context/index.js +3 -3
  263. package/dist/context-FDOON2DB.js +6 -0
  264. package/dist/{context-ENXZNF6J.js.map → context-FDOON2DB.js.map} +1 -1
  265. package/dist/context-VMIE4BMD.cjs +23 -0
  266. package/dist/{context-7USNN6LP.cjs.map → context-VMIE4BMD.cjs.map} +1 -1
  267. package/dist/cron-CRwy2JBF.d.ts +240 -0
  268. package/dist/cron-DxxeQ-sK.d.cts +240 -0
  269. package/dist/cron.cjs +43 -41
  270. package/dist/cron.d.cts +5 -3
  271. package/dist/cron.d.ts +5 -3
  272. package/dist/cron.js +42 -40
  273. package/dist/define-tool.d.ts +14 -6
  274. package/dist/{errors-BSoXcl3F.d.cts → errors-BgJH9PHi.d.cts} +39 -24
  275. package/dist/{errors-CHllybaU.d.ts → errors-C5fJUqLk.d.ts} +39 -24
  276. package/dist/errors.cjs +22 -21
  277. package/dist/errors.d.cts +2 -2
  278. package/dist/errors.d.ts +2 -2
  279. package/dist/errors.js +3 -2
  280. package/dist/eval.cjs +61 -58
  281. package/dist/eval.cjs.map +1 -1
  282. package/dist/eval.d.cts +38 -0
  283. package/dist/eval.d.ts +38 -0
  284. package/dist/eval.js +51 -48
  285. package/dist/eval.js.map +1 -1
  286. package/dist/event-bus.d.ts +16 -0
  287. package/dist/{executor-2Z6XJJJG.js → executor-BMEHFOXZ.js} +8 -7
  288. package/dist/executor-BMEHFOXZ.js.map +1 -0
  289. package/dist/{executor-2Z3LGG3I.cjs → executor-ZERJ3DGN.cjs} +25 -24
  290. package/dist/executor-ZERJ3DGN.cjs.map +1 -0
  291. package/dist/filesystem/index.cjs +8 -7
  292. package/dist/filesystem/index.cjs.map +1 -1
  293. package/dist/filesystem/index.js +4 -3
  294. package/dist/filesystem/index.js.map +1 -1
  295. package/dist/filesystem/local-filesystem.d.cts +18 -0
  296. package/dist/filesystem/local-filesystem.d.ts +18 -0
  297. package/dist/filesystem/types.d.cts +12 -0
  298. package/dist/filesystem/types.d.ts +12 -0
  299. package/dist/fs-session-store-3MOJQGP2.cjs +20 -0
  300. package/dist/{fs-session-store-VVY2AHWG.cjs.map → fs-session-store-3MOJQGP2.cjs.map} +1 -1
  301. package/dist/fs-session-store-IN7JTTXD.js +11 -0
  302. package/dist/{fs-session-store-R5FD3EN6.js.map → fs-session-store-IN7JTTXD.js.map} +1 -1
  303. package/dist/generate-object-N5MDZUJI.js +8 -0
  304. package/dist/{generate-object-WQRCXFD2.js.map → generate-object-N5MDZUJI.js.map} +1 -1
  305. package/dist/generate-object-PGSP5U7N.cjs +21 -0
  306. package/dist/{generate-object-AVXOJK2I.cjs.map → generate-object-PGSP5U7N.cjs.map} +1 -1
  307. package/dist/generate-object.d.ts +20 -0
  308. package/dist/index-manager-NG5YENWO.cjs +22 -0
  309. package/dist/{index-manager-VRU3A2YL.cjs.map → index-manager-NG5YENWO.cjs.map} +1 -1
  310. package/dist/index-manager-ZMRJ6ZII.js +13 -0
  311. package/dist/{index-manager-WS7TVKUW.js.map → index-manager-ZMRJ6ZII.js.map} +1 -1
  312. package/dist/index.cjs +169 -155
  313. package/dist/index.cjs.map +1 -1
  314. package/dist/index.d.cts +702 -54
  315. package/dist/index.d.ts +702 -54
  316. package/dist/index.js +61 -58
  317. package/dist/index.js.map +1 -1
  318. package/dist/{inject-session-GMBMJVNZ.js → inject-session-DDR6X6PC.js} +9 -8
  319. package/dist/inject-session-DDR6X6PC.js.map +1 -0
  320. package/dist/inject-session-XLO3KTBM.cjs +29 -0
  321. package/dist/inject-session-XLO3KTBM.cjs.map +1 -0
  322. package/dist/internal/auth/auth-types.d.ts +83 -1
  323. package/dist/internal/auth/credential-store.d.ts +34 -6
  324. package/dist/internal/auth/oauth-device.d.ts +0 -1
  325. package/dist/internal/auth/resolve-credential.d.ts +40 -0
  326. package/dist/internal/budget/tracker/budget.d.ts +12 -14
  327. package/dist/internal/budget/usage-accumulator.d.ts +15 -0
  328. package/dist/internal/llm/anthropic-shared.d.ts +8 -4
  329. package/dist/internal/llm/model-identifier.d.ts +26 -0
  330. package/dist/internal/llm/openai.d.ts +8 -0
  331. package/dist/internal/llm/router.d.ts +8 -0
  332. package/dist/internal/llm/types.d.ts +12 -1
  333. package/dist/internal/local-agent/real-local-run-provider.d.ts +8 -3
  334. package/dist/internal/local-agent/real-local-run-tools.d.ts +8 -0
  335. package/dist/internal/mcp/oauth.d.ts +5 -0
  336. package/dist/internal/mcp/token-storage.d.ts +34 -0
  337. package/dist/internal/memory/adapters/index.cjs +12 -11
  338. package/dist/internal/memory/adapters/index.d.cts +3 -1
  339. package/dist/internal/memory/adapters/index.d.ts +3 -1
  340. package/dist/internal/memory/adapters/index.js +9 -8
  341. package/dist/internal/memory/adapters/openai-compatible.d.cts +45 -0
  342. package/dist/internal/memory/adapters/openai-compatible.d.ts +45 -0
  343. package/dist/internal/memory/embedding-cache.d.ts +42 -1
  344. package/dist/internal/memory/escape-like-pattern.d.ts +22 -0
  345. package/dist/internal/memory/sqlite-vec-loader.d.ts +1 -3
  346. package/dist/internal/memory/storage/markdown-store.d.ts +0 -5
  347. package/dist/internal/persistence/cwd-mutex.d.cts +34 -0
  348. package/dist/internal/persistence/cwd-mutex.d.ts +34 -0
  349. package/dist/internal/persistence/exclusive-create.d.cts +31 -0
  350. package/dist/internal/persistence/exclusive-create.d.ts +31 -0
  351. package/dist/internal/persistence/file-lock.d.cts +28 -0
  352. package/dist/internal/persistence/file-lock.d.ts +28 -0
  353. package/dist/internal/persistence/fs-session-store.d.cts +3 -0
  354. package/dist/internal/persistence/fs-session-store.d.ts +3 -0
  355. package/dist/internal/persistence/fts5-sanitize.d.cts +20 -0
  356. package/dist/internal/persistence/fts5-sanitize.d.ts +20 -0
  357. package/dist/internal/persistence/index.cjs +40 -39
  358. package/dist/internal/persistence/index.cjs.map +1 -1
  359. package/dist/internal/persistence/index.d.cts +6 -1
  360. package/dist/internal/persistence/index.d.ts +6 -1
  361. package/dist/internal/persistence/index.js +9 -8
  362. package/dist/internal/persistence/index.js.map +1 -1
  363. package/dist/internal/persistence/paths.d.cts +54 -1
  364. package/dist/internal/persistence/paths.d.ts +54 -1
  365. package/dist/internal/persistence/persistence-schema.d.cts +9 -1
  366. package/dist/internal/persistence/persistence-schema.d.ts +9 -1
  367. package/dist/internal/persistence/schema-version.d.cts +215 -1
  368. package/dist/internal/persistence/schema-version.d.ts +215 -1
  369. package/dist/internal/persistence/session-writer.d.cts +7 -7
  370. package/dist/internal/persistence/session-writer.d.ts +7 -7
  371. package/dist/internal/persistence/sqlite-cas.d.cts +37 -1
  372. package/dist/internal/persistence/sqlite-cas.d.ts +37 -1
  373. package/dist/internal/persistence/sqlite-open.d.cts +14 -0
  374. package/dist/internal/persistence/sqlite-open.d.ts +14 -0
  375. package/dist/internal/persistence/sqlite-wal.d.cts +45 -0
  376. package/dist/internal/persistence/sqlite-wal.d.ts +45 -0
  377. package/dist/internal/persistence/transcript-ops.d.cts +7 -1
  378. package/dist/internal/persistence/transcript-ops.d.ts +7 -1
  379. package/dist/internal/plugins/types.d.cts +1 -1
  380. package/dist/internal/plugins/types.d.ts +1 -1
  381. package/dist/internal/providers/builtin/openai-chatgpt.d.ts +12 -0
  382. package/dist/internal/providers/catalog-loader.d.ts +8 -0
  383. package/dist/internal/providers/catalog-schema.d.ts +55 -0
  384. package/dist/internal/providers/catalog-source-models-dev.d.ts +36 -0
  385. package/dist/internal/runtime/concurrency/delegation-depth.d.ts +27 -0
  386. package/dist/internal/runtime/concurrency/subagent-credentials.d.ts +33 -1
  387. package/dist/internal/runtime/context/context-discovery-runner.d.ts +44 -0
  388. package/dist/internal/runtime/context/context-discovery.d.ts +58 -0
  389. package/dist/internal/runtime/context/context-rules-frontmatter.d.ts +70 -1
  390. package/dist/internal/runtime/fixtures/fixture-mode.d.ts +15 -1
  391. package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +15 -0
  392. package/dist/internal/runtime/registry/agent-registry-store.d.ts +12 -0
  393. package/dist/internal/runtime/registry/live-agent-registry.d.ts +37 -0
  394. package/dist/internal/scorers/llm-judge.d.ts +6 -1
  395. package/dist/internal/security/index.cjs +14 -13
  396. package/dist/internal/security/index.d.cts +4 -1
  397. package/dist/internal/security/index.d.ts +4 -1
  398. package/dist/internal/security/index.js +4 -3
  399. package/dist/internal/security/path-guard.d.cts +46 -0
  400. package/dist/internal/security/path-guard.d.ts +46 -0
  401. package/dist/internal/security/redact.d.cts +71 -0
  402. package/dist/internal/security/redact.d.ts +71 -0
  403. package/dist/internal/session/agent-session.d.ts +15 -4
  404. package/dist/internal/session/session-cache.d.ts +5 -0
  405. package/dist/internal/task/store.d.ts +91 -5
  406. package/dist/internal/telemetry/span-names.d.ts +0 -1
  407. package/dist/internal/telemetry/tracer.d.ts +14 -0
  408. package/dist/job-queue.d.ts +18 -0
  409. package/dist/judge-call-DWHAJATE.js +6 -0
  410. package/dist/{judge-call-MDIPTBJI.js.map → judge-call-DWHAJATE.js.map} +1 -1
  411. package/dist/judge-call-EGYRC2RE.cjs +23 -0
  412. package/dist/{judge-call-G5SGV2M2.cjs.map → judge-call-EGYRC2RE.cjs.map} +1 -1
  413. package/dist/mcp-auth.cjs +41 -25
  414. package/dist/mcp-auth.cjs.map +1 -1
  415. package/dist/mcp-auth.js +34 -18
  416. package/dist/mcp-auth.js.map +1 -1
  417. package/dist/models.cjs +42 -27
  418. package/dist/models.cjs.map +1 -1
  419. package/dist/models.js +25 -10
  420. package/dist/models.js.map +1 -1
  421. package/dist/oauth-transaction-store-BT4GLTLK.cjs +36 -0
  422. package/dist/{oauth-transaction-store-7CKHPQRN.cjs.map → oauth-transaction-store-BT4GLTLK.cjs.map} +1 -1
  423. package/dist/oauth-transaction-store-W52KVHQ4.js +3 -0
  424. package/dist/{oauth-transaction-store-W74I6EFD.js.map → oauth-transaction-store-W52KVHQ4.js.map} +1 -1
  425. package/dist/path-safety.cjs +11 -10
  426. package/dist/path-safety.js +4 -3
  427. package/dist/permission-engine.d.ts +55 -0
  428. package/dist/persistence.cjs +43 -42
  429. package/dist/persistence.cjs.map +1 -1
  430. package/dist/persistence.js +13 -12
  431. package/dist/persistence.js.map +1 -1
  432. package/dist/project.cjs +9 -8
  433. package/dist/project.cjs.map +1 -1
  434. package/dist/project.js +5 -4
  435. package/dist/project.js.map +1 -1
  436. package/dist/providers.cjs +23 -0
  437. package/dist/providers.cjs.map +1 -0
  438. package/dist/providers.d.cts +29 -0
  439. package/dist/providers.d.ts +29 -0
  440. package/dist/providers.js +10 -0
  441. package/dist/providers.js.map +1 -0
  442. package/dist/registry-VFKX7WOP.cjs +47 -0
  443. package/dist/{registry-63ASMXT4.cjs.map → registry-VFKX7WOP.cjs.map} +1 -1
  444. package/dist/registry-VFP3WWQP.js +10 -0
  445. package/dist/{registry-O7FJ2MPM.js.map → registry-VFP3WWQP.js.map} +1 -1
  446. package/dist/retry.cjs +5 -4
  447. package/dist/retry.js +4 -3
  448. package/dist/{run-C8FBAC8o.d.cts → run-BYSHf58D.d.cts} +185 -33
  449. package/dist/{run-C8FBAC8o.d.ts → run-BYSHf58D.d.ts} +185 -33
  450. package/dist/{run-to-completion-JDPIUKSH.js → run-to-completion-DRO77625.js} +3 -3
  451. package/dist/{run-to-completion-JDPIUKSH.js.map → run-to-completion-DRO77625.js.map} +1 -1
  452. package/dist/{run-to-completion-J73I6IY4.cjs → run-to-completion-X4OWM673.cjs} +13 -13
  453. package/dist/{run-to-completion-J73I6IY4.cjs.map → run-to-completion-X4OWM673.cjs.map} +1 -1
  454. package/dist/sandbox/bwrap.d.cts +27 -13
  455. package/dist/sandbox/bwrap.d.ts +27 -13
  456. package/dist/sandbox/index.cjs +20 -19
  457. package/dist/sandbox/index.cjs.map +1 -1
  458. package/dist/sandbox/index.js +5 -4
  459. package/dist/sandbox/index.js.map +1 -1
  460. package/dist/sandbox/linux-sandbox.d.cts +72 -0
  461. package/dist/sandbox/linux-sandbox.d.ts +72 -0
  462. package/dist/sandbox/local-sandbox.d.cts +41 -0
  463. package/dist/sandbox/local-sandbox.d.ts +41 -0
  464. package/dist/sandbox/seccomp.d.cts +6 -0
  465. package/dist/sandbox/seccomp.d.ts +6 -0
  466. package/dist/sandbox/types.d.cts +64 -0
  467. package/dist/sandbox/types.d.ts +64 -0
  468. package/dist/scorers.d.ts +38 -7
  469. package/dist/sdk-agent-D8qJVkuV.d.ts +860 -0
  470. package/dist/sdk-agent-DEoKhA8a.d.cts +860 -0
  471. package/dist/server/auth/errors.d.cts +1 -1
  472. package/dist/server/auth/errors.d.ts +1 -1
  473. package/dist/server/auth/index.cjs +29 -21
  474. package/dist/server/auth/index.cjs.map +1 -1
  475. package/dist/server/auth/index.d.cts +25 -15
  476. package/dist/server/auth/index.d.ts +25 -15
  477. package/dist/server/auth/index.js +15 -7
  478. package/dist/server/auth/index.js.map +1 -1
  479. package/dist/server/auth/oauth-transaction-store.d.cts +13 -1
  480. package/dist/server/auth/oauth-transaction-store.d.ts +13 -1
  481. package/dist/server/auth/orchestrator.d.cts +1 -1
  482. package/dist/server/auth/orchestrator.d.ts +1 -1
  483. package/dist/server/auth/types.d.cts +1 -1
  484. package/dist/server/auth/types.d.ts +1 -1
  485. package/dist/server/auth/validate-return-to.d.cts +21 -11
  486. package/dist/server/auth/validate-return-to.d.ts +21 -11
  487. package/dist/server/errors-envelope.cjs +15 -14
  488. package/dist/server/errors-envelope.cjs.map +1 -1
  489. package/dist/server/errors-envelope.d.cts +4 -4
  490. package/dist/server/errors-envelope.d.ts +4 -4
  491. package/dist/server/errors-envelope.js +4 -3
  492. package/dist/server/errors-envelope.js.map +1 -1
  493. package/dist/session-transcript-AKDYYGXQ.js +6 -0
  494. package/dist/{session-transcript-RAKEK76V.js.map → session-transcript-AKDYYGXQ.js.map} +1 -1
  495. package/dist/session-transcript-JXHFTB7G.cjs +51 -0
  496. package/dist/{session-transcript-DOM3UTXR.cjs.map → session-transcript-JXHFTB7G.cjs.map} +1 -1
  497. package/dist/skills.cjs +8 -7
  498. package/dist/skills.js +6 -5
  499. package/dist/stream-object-BUCF5PHO.cjs +21 -0
  500. package/dist/{stream-object-L3Q7PBMF.cjs.map → stream-object-BUCF5PHO.cjs.map} +1 -1
  501. package/dist/stream-object-L57K4OFS.js +8 -0
  502. package/dist/{stream-object-ZYXWS4B2.js.map → stream-object-L57K4OFS.js.map} +1 -1
  503. package/dist/{stream-to-completion-DFJ5T3BK.js → stream-to-completion-QV5HCL3J.js} +3 -3
  504. package/dist/{stream-to-completion-DFJ5T3BK.js.map → stream-to-completion-QV5HCL3J.js.map} +1 -1
  505. package/dist/{stream-to-completion-H2MHISSK.cjs → stream-to-completion-SRISU5AB.cjs} +10 -10
  506. package/dist/{stream-to-completion-H2MHISSK.cjs.map → stream-to-completion-SRISU5AB.cjs.map} +1 -1
  507. package/dist/subagents-loader-AZIXJ7D3.cjs +16 -0
  508. package/dist/{subagents-loader-VRW73QQT.cjs.map → subagents-loader-AZIXJ7D3.cjs.map} +1 -1
  509. package/dist/subagents-loader-J54ESLDV.js +7 -0
  510. package/dist/{subagents-loader-I56GSKAQ.js.map → subagents-loader-J54ESLDV.js.map} +1 -1
  511. package/dist/subagents-loader.cjs +7 -6
  512. package/dist/subagents-loader.cjs.map +1 -1
  513. package/dist/subagents-loader.d.cts +3 -2
  514. package/dist/subagents-loader.d.ts +3 -2
  515. package/dist/subagents-loader.js +5 -4
  516. package/dist/subagents-loader.js.map +1 -1
  517. package/dist/subscription/define-subscription.d.cts +1 -1
  518. package/dist/subscription/define-subscription.d.ts +1 -1
  519. package/dist/subscription/index.cjs +22 -9
  520. package/dist/subscription/index.cjs.map +1 -1
  521. package/dist/subscription/index.d.cts +1 -1
  522. package/dist/subscription/index.d.ts +1 -1
  523. package/dist/subscription/index.js +21 -8
  524. package/dist/subscription/index.js.map +1 -1
  525. package/dist/subscription/internal/adapter-types.d.cts +1 -1
  526. package/dist/subscription/internal/adapter-types.d.ts +1 -1
  527. package/dist/subscription/internal/server-integration.d.cts +1 -1
  528. package/dist/subscription/internal/server-integration.d.ts +1 -1
  529. package/dist/subscription/internal/sse-encoder.d.cts +1 -1
  530. package/dist/subscription/internal/sse-encoder.d.ts +1 -1
  531. package/dist/subscription/internal/sse-parser.d.cts +1 -1
  532. package/dist/subscription/internal/sse-parser.d.ts +1 -1
  533. package/dist/subscription/internal/subscription-runtime.d.cts +1 -1
  534. package/dist/subscription/internal/subscription-runtime.d.ts +1 -1
  535. package/dist/subscription/internal/ws-adapter-node.d.cts +1 -1
  536. package/dist/subscription/internal/ws-adapter-node.d.ts +1 -1
  537. package/dist/subscription/theokit-subscribe.d.cts +14 -1
  538. package/dist/subscription/theokit-subscribe.d.ts +14 -1
  539. package/dist/subscription/types.d.cts +19 -1
  540. package/dist/subscription/types.d.ts +19 -1
  541. package/dist/task-store.cjs +8 -7
  542. package/dist/task-store.js +5 -4
  543. package/dist/types/agent-prims.d.ts +14 -0
  544. package/dist/types/agent.d.ts +50 -11
  545. package/dist/types/batch.d.ts +7 -1
  546. package/dist/types/conversation.d.ts +18 -5
  547. package/dist/types/goal-events.d.ts +4 -8
  548. package/dist/types/memory-adapter.d.ts +12 -1
  549. package/dist/types/plugin.d.ts +101 -0
  550. package/dist/types/provider-profile.d.ts +19 -0
  551. package/dist/types/run-events.d.ts +28 -1
  552. package/dist/types/run.d.ts +35 -23
  553. package/dist/types/sdk-agent.d.ts +14 -0
  554. package/dist/types/session-record.d.ts +18 -1
  555. package/dist/types/task.d.ts +15 -1
  556. package/dist/types/theokit.d.ts +10 -1
  557. package/dist/types/updates.d.ts +35 -4
  558. package/dist/types/workflow.d.ts +155 -0
  559. package/dist/workflow.cjs +29 -28
  560. package/dist/workflow.d.cts +666 -17
  561. package/dist/workflow.d.ts +666 -17
  562. package/dist/workflow.js +8 -7
  563. package/docs/error-codes.md +215 -0
  564. package/docs/harness-capability-map.md +1357 -0
  565. package/package.json +29 -16
  566. package/bin/init-claude.mjs +0 -68
  567. package/claude-template/AGENTS.md +0 -157
  568. package/claude-template/CLAUDE.md +0 -66
  569. package/claude-template/dot-claude/rules/theokit-conventions.md +0 -32
  570. package/claude-template/dot-claude/settings.json +0 -16
  571. package/claude-template/dot-claude/skills/theokit-agent-core/SKILL.md +0 -209
  572. package/claude-template/dot-claude/skills/theokit-auth/SKILL.md +0 -102
  573. package/claude-template/dot-claude/skills/theokit-budget/SKILL.md +0 -176
  574. package/claude-template/dot-claude/skills/theokit-client/SKILL.md +0 -58
  575. package/claude-template/dot-claude/skills/theokit-compaction/SKILL.md +0 -102
  576. package/claude-template/dot-claude/skills/theokit-concurrency/SKILL.md +0 -68
  577. package/claude-template/dot-claude/skills/theokit-config/SKILL.md +0 -139
  578. package/claude-template/dot-claude/skills/theokit-cron/SKILL.md +0 -148
  579. package/claude-template/dot-claude/skills/theokit-di/SKILL.md +0 -233
  580. package/claude-template/dot-claude/skills/theokit-di-agent/SKILL.md +0 -294
  581. package/claude-template/dot-claude/skills/theokit-errors/SKILL.md +0 -172
  582. package/claude-template/dot-claude/skills/theokit-eval/SKILL.md +0 -179
  583. package/claude-template/dot-claude/skills/theokit-filesystem/SKILL.md +0 -74
  584. package/claude-template/dot-claude/skills/theokit-gateways/SKILL.md +0 -209
  585. package/claude-template/dot-claude/skills/theokit-memory/SKILL.md +0 -176
  586. package/claude-template/dot-claude/skills/theokit-messages/SKILL.md +0 -58
  587. package/claude-template/dot-claude/skills/theokit-models/SKILL.md +0 -79
  588. package/claude-template/dot-claude/skills/theokit-path-safety/SKILL.md +0 -60
  589. package/claude-template/dot-claude/skills/theokit-persistence/SKILL.md +0 -85
  590. package/claude-template/dot-claude/skills/theokit-project/SKILL.md +0 -55
  591. package/claude-template/dot-claude/skills/theokit-retry/SKILL.md +0 -50
  592. package/claude-template/dot-claude/skills/theokit-sandbox/SKILL.md +0 -93
  593. package/claude-template/dot-claude/skills/theokit-sanitize/SKILL.md +0 -66
  594. package/claude-template/dot-claude/skills/theokit-skills/SKILL.md +0 -68
  595. package/claude-template/dot-claude/skills/theokit-streaming/SKILL.md +0 -156
  596. package/claude-template/dot-claude/skills/theokit-subagents/SKILL.md +0 -109
  597. package/claude-template/dot-claude/skills/theokit-subscriptions/SKILL.md +0 -148
  598. package/claude-template/dot-claude/skills/theokit-task-store/SKILL.md +0 -75
  599. package/claude-template/dot-claude/skills/theokit-tools/SKILL.md +0 -170
  600. package/claude-template/dot-claude/skills/theokit-workflows/SKILL.md +0 -218
  601. package/dist/agent-FFVV4U5N.js +0 -50
  602. package/dist/agent-YLAHVHEH.cjs +0 -59
  603. package/dist/agent-session-store-DUGBAX5V.cjs +0 -23
  604. package/dist/agent-session-store-TNCGL5RN.js +0 -6
  605. package/dist/batch-UPKN4SG6.js.map +0 -1
  606. package/dist/batch-ZEFN5SO7.cjs.map +0 -1
  607. package/dist/chunk-2D43RD5D.cjs.map +0 -1
  608. package/dist/chunk-2FYEVT2B.cjs.map +0 -1
  609. package/dist/chunk-2RW7K6FN.cjs.map +0 -1
  610. package/dist/chunk-2XLKLVVR.js.map +0 -1
  611. package/dist/chunk-34XOCZJO.js.map +0 -1
  612. package/dist/chunk-3V7UJLQT.js.map +0 -1
  613. package/dist/chunk-4NAKHID5.js.map +0 -1
  614. package/dist/chunk-4Q4K4WB5.js.map +0 -1
  615. package/dist/chunk-5F5NWKPN.js.map +0 -1
  616. package/dist/chunk-5NBUH3NO.js.map +0 -1
  617. package/dist/chunk-5YKNEMXR.cjs.map +0 -1
  618. package/dist/chunk-7W7ZWMLQ.js.map +0 -1
  619. package/dist/chunk-ADLLFY3H.cjs.map +0 -1
  620. package/dist/chunk-B4YA6BRS.cjs.map +0 -1
  621. package/dist/chunk-B6HOIWQ6.js.map +0 -1
  622. package/dist/chunk-BDTVFIPB.cjs.map +0 -1
  623. package/dist/chunk-BFYGJGC5.js.map +0 -1
  624. package/dist/chunk-BM6N4KHO.cjs.map +0 -1
  625. package/dist/chunk-CAH3G4IS.js.map +0 -1
  626. package/dist/chunk-EZ2YEF4F.cjs.map +0 -1
  627. package/dist/chunk-F77UENR6.cjs.map +0 -1
  628. package/dist/chunk-FOXKFTVZ.cjs.map +0 -1
  629. package/dist/chunk-G3JWXOGY.js.map +0 -1
  630. package/dist/chunk-GOVJO4YE.js.map +0 -1
  631. package/dist/chunk-HAWE74GQ.cjs.map +0 -1
  632. package/dist/chunk-HE4BIAOS.js.map +0 -1
  633. package/dist/chunk-HSQ5Q3I5.js.map +0 -1
  634. package/dist/chunk-JIQRXKTA.cjs.map +0 -1
  635. package/dist/chunk-KSWHTR54.js.map +0 -1
  636. package/dist/chunk-L5YO6PWL.cjs.map +0 -1
  637. package/dist/chunk-LD4MOBFX.js.map +0 -1
  638. package/dist/chunk-LS3LMQ23.js.map +0 -1
  639. package/dist/chunk-MSFLYJDY.js.map +0 -1
  640. package/dist/chunk-NZL4BNFQ.js.map +0 -1
  641. package/dist/chunk-OKLYRPKL.cjs.map +0 -1
  642. package/dist/chunk-OUOXM36O.cjs.map +0 -1
  643. package/dist/chunk-OXNYIMZZ.js.map +0 -1
  644. package/dist/chunk-PBZ7HMBP.js.map +0 -1
  645. package/dist/chunk-PNVDQL5Y.cjs.map +0 -1
  646. package/dist/chunk-Q4RESANI.cjs.map +0 -1
  647. package/dist/chunk-QBTVATSF.cjs.map +0 -1
  648. package/dist/chunk-RAHSWE5C.cjs.map +0 -1
  649. package/dist/chunk-RP5HQVLD.js.map +0 -1
  650. package/dist/chunk-SEL2ZQMT.js.map +0 -1
  651. package/dist/chunk-SK4QLUBK.js.map +0 -1
  652. package/dist/chunk-TTJ54H3E.cjs.map +0 -1
  653. package/dist/chunk-V26QVGUG.js.map +0 -1
  654. package/dist/chunk-V6HWJQQV.js.map +0 -1
  655. package/dist/chunk-VGPXHHF3.cjs.map +0 -1
  656. package/dist/chunk-VUKQL3L2.cjs.map +0 -1
  657. package/dist/chunk-VYCKUKPA.cjs.map +0 -1
  658. package/dist/chunk-VYHJZVL5.cjs.map +0 -1
  659. package/dist/chunk-X2FR4OIT.js.map +0 -1
  660. package/dist/chunk-XPR366DL.cjs.map +0 -1
  661. package/dist/chunk-XROIW6BH.js.map +0 -1
  662. package/dist/chunk-YLQQX5W2.cjs.map +0 -1
  663. package/dist/chunk-ZT57WTUJ.cjs.map +0 -1
  664. package/dist/compact-session-4MNKNMO2.js +0 -21
  665. package/dist/compact-session-EPFBQ46Z.cjs +0 -58
  666. package/dist/context-7USNN6LP.cjs +0 -22
  667. package/dist/context-ENXZNF6J.js +0 -5
  668. package/dist/cron-BMjgFH-_.d.ts +0 -631
  669. package/dist/cron-DFDdCdMM.d.cts +0 -631
  670. package/dist/executor-2Z3LGG3I.cjs.map +0 -1
  671. package/dist/executor-2Z6XJJJG.js.map +0 -1
  672. package/dist/fs-session-store-R5FD3EN6.js +0 -10
  673. package/dist/fs-session-store-VVY2AHWG.cjs +0 -19
  674. package/dist/generate-object-AVXOJK2I.cjs +0 -20
  675. package/dist/generate-object-WQRCXFD2.js +0 -7
  676. package/dist/index-manager-VRU3A2YL.cjs +0 -21
  677. package/dist/index-manager-WS7TVKUW.js +0 -12
  678. package/dist/inject-session-AUQLBDRS.cjs +0 -28
  679. package/dist/inject-session-AUQLBDRS.cjs.map +0 -1
  680. package/dist/inject-session-GMBMJVNZ.js.map +0 -1
  681. package/dist/judge-call-G5SGV2M2.cjs +0 -22
  682. package/dist/judge-call-MDIPTBJI.js +0 -5
  683. package/dist/oauth-transaction-store-7CKHPQRN.cjs +0 -32
  684. package/dist/oauth-transaction-store-W74I6EFD.js +0 -3
  685. package/dist/registry-63ASMXT4.cjs +0 -46
  686. package/dist/registry-O7FJ2MPM.js +0 -9
  687. package/dist/session-transcript-DOM3UTXR.cjs +0 -50
  688. package/dist/session-transcript-RAKEK76V.js +0 -5
  689. package/dist/stream-object-L3Q7PBMF.cjs +0 -20
  690. package/dist/stream-object-ZYXWS4B2.js +0 -7
  691. package/dist/subagents-loader-I56GSKAQ.js +0 -6
  692. package/dist/subagents-loader-VRW73QQT.cjs +0 -15
@@ -1,8 +1,8 @@
1
- import { generateCronId } from './chunk-G3JWXOGY.js';
2
- import { submit } from './chunk-XROIW6BH.js';
1
+ import { generateCronId } from './chunk-TPTZA6NI.js';
2
+ import { submit } from './chunk-SUKXXLWD.js';
3
3
  import { getAgentFacade } from './chunk-6X6ID4MO.js';
4
- import { UnknownAgentError, ConfigurationError } from './chunk-U4UJHOSH.js';
5
- import { resolveApiKey } from './chunk-5F5NWKPN.js';
4
+ import { UnknownAgentError, ConfigurationError } from './chunk-IDCKSLYH.js';
5
+ import { resolveApiKey } from './chunk-T7XEKOVW.js';
6
6
  import { Cron as Cron$1 } from 'croner';
7
7
 
8
8
  // src/internal/cron/run-job.ts
@@ -198,27 +198,19 @@ function validateCronExpression(cron) {
198
198
  return;
199
199
  }
200
200
  const fields = cron.trim().split(/\s+/);
201
- if (fields.length !== 5) {
201
+ if (fields.length !== FIELD_RANGES.length) {
202
202
  throw new ConfigurationError(
203
- `Invalid cron expression: ${cron} (expected 5 fields, got ${fields.length})`,
203
+ `Invalid cron expression: ${cron} (expected ${FIELD_RANGES.length} fields, got ${fields.length})`,
204
204
  { code: "invalid_cron" }
205
205
  );
206
206
  }
207
- for (const [index, field] of fields.entries()) {
208
- validateFieldOrThrow(field, index, cron);
209
- }
210
- }
211
- function validateFieldOrThrow(field, index, cron) {
212
- const range = FIELD_RANGES[index];
213
- if (range === void 0) {
214
- throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {
215
- code: "invalid_cron"
216
- });
217
- }
218
- if (!isValidCronField(field, range)) {
219
- throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {
220
- code: "invalid_cron"
221
- });
207
+ for (const [index, range] of FIELD_RANGES.entries()) {
208
+ const field = fields[index];
209
+ if (!isValidCronField(field, range)) {
210
+ throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {
211
+ code: "invalid_cron"
212
+ });
213
+ }
222
214
  }
223
215
  }
224
216
  function isValidCronField(field, range) {
@@ -230,23 +222,28 @@ function isValidCronField(field, range) {
230
222
  if (field.includes("-")) return isValidRange(field, range);
231
223
  return isValidLiteral(field, range);
232
224
  }
225
+ var DIGITS_ONLY = /^\d+$/;
226
+ function parseFieldNumber(text) {
227
+ if (!DIGITS_ONLY.test(text)) return void 0;
228
+ return Number.parseInt(text, 10);
229
+ }
233
230
  function isValidStep(stepStr, range) {
234
- const step = Number.parseInt(stepStr, 10);
235
- return Number.isInteger(step) && String(step) === stepStr && step > 0 && step <= range.max;
231
+ const step = parseFieldNumber(stepStr);
232
+ return step !== void 0 && step > 0 && step <= range.max;
236
233
  }
237
234
  function isValidRange(field, range) {
238
235
  const parts = field.split("-");
239
236
  if (parts.length !== 2) return false;
240
237
  const [startStr, endStr] = parts;
241
238
  if (startStr === void 0 || endStr === void 0) return false;
242
- const start = Number.parseInt(startStr, 10);
243
- const end = Number.parseInt(endStr, 10);
244
- if (!Number.isInteger(start) || !Number.isInteger(end)) return false;
239
+ const start = parseFieldNumber(startStr);
240
+ const end = parseFieldNumber(endStr);
241
+ if (start === void 0 || end === void 0) return false;
245
242
  return start >= range.min && end <= range.max && start <= end;
246
243
  }
247
244
  function isValidLiteral(field, range) {
248
- const n = Number.parseInt(field, 10);
249
- return Number.isInteger(n) && String(n) === field && n >= range.min && n <= range.max;
245
+ const n = parseFieldNumber(field);
246
+ return n !== void 0 && n >= range.min && n <= range.max;
250
247
  }
251
248
  function validateTimezone(timezone) {
252
249
  try {
@@ -455,5 +452,5 @@ async function updateJobStatus(jobId, enabled) {
455
452
  }
456
453
 
457
454
  export { Cron };
458
- //# sourceMappingURL=chunk-V6HWJQQV.js.map
459
- //# sourceMappingURL=chunk-V6HWJQQV.js.map
455
+ //# sourceMappingURL=chunk-AGSBJD2L.js.map
456
+ //# sourceMappingURL=chunk-AGSBJD2L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/cron/run-job.ts","../src/internal/cron/fire-handler.ts","../src/internal/cron/store.ts","../src/internal/cron/scheduler.ts","../src/internal/cron/validate.ts","../src/cron.ts"],"names":["Croner"],"mappings":";;;;;;;;AAoBA,eAAsB,WAAW,GAAA,EAA0C;AAIzE,EAAA,IAAI,GAAA,CAAI,aAAa,MAAA,EAAW,OAAO,IAAI,QAAA,CAAS,GAAA,CAAI,IAAI,SAAS,CAAA;AACrE,EAAA,IAAI,GAAA,CAAI,UAAU,MAAA,EAAW,OAAO,sBAAsB,GAAA,CAAI,KAAA,EAAO,cAAA,CAAe,GAAG,CAAC,CAAA;AACxF,EAAA,IAAI,GAAA,CAAI,YAAY,MAAA,EAAW,OAAO,qBAAqB,GAAA,CAAI,OAAA,EAAS,cAAA,CAAe,GAAG,CAAC,CAAA;AAC3F,EAAA,MAAM,IAAI,kBAAA;AAAA,IACR,CAAA,SAAA,EAAY,IAAI,EAAE,CAAA,+DAAA,CAAA;AAAA,IAClB,EAAE,MAAM,gBAAA;AAAiB,GAC3B;AACF;AAOO,SAAS,WAAW,OAAA,EAA4C;AACrE,EAAA,OAAO,OAAQ,QAAgB,IAAA,KAAS,UAAA;AAC1C;AAGA,SAAS,eAAe,GAAA,EAAuC;AAC7D,EAAA,IAAI,GAAA,CAAI,YAAY,MAAA,EAAW;AAC7B,IAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,SAAA,EAAY,GAAA,CAAI,EAAE,CAAA,uCAAA,CAAA,EAA2C;AAAA,MACxF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,GAAA,CAAI,OAAA;AACb;AAEA,eAAe,oBAAA,CACb,SACA,OAAA,EACc;AACd,EAAA,MAAM,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AW;AAC1B,IAAA,MAAM,IAAI,kBAAkB,CAAA,SAAA,EAAY,KAAK,cAAc,EAAE,IAAA,EAAM,oBAAoB,CAAA;AAAA,EACzF;AACA,EAAA,MAAM,OAAA,GAAmB;AAAA,IACvB,GAAG,QAAA;AAAA,IACH,OAAA;AAAA,IACA,MAAA,EAAQ,UAAU,WAAA,GAAc;AAAA,GAClC;AACA,EAAA,SAAA,CAAU,OAAO,CAAA;AACjB,EAAA,IAAI,OAAA,CAAQ,YAAY,OAAA,EAAS;AAC/B,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,WAAA,CAAY,OAAO,CAAA;AAAA,IACrB,CAAA,MAAO;AACL,MAAA,aAAA,CAAc,QAAQ,EAAE,CAAA;AAAA,IAC1B;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-AGSBJD2L.js","sourcesContent":["import { ConfigurationError, UnknownAgentError } from \"../../errors.js\";\nimport type { AgentOptions } from \"../../types/agent.js\";\nimport type { CronJob } from \"../../types/cron.js\";\nimport type { Run, SDKUserMessage } from \"../../types/run.js\";\nimport type { WorkflowRun } from \"../../types/workflow.js\";\nimport { getAgentFacade } from \"../runtime/registry/agent-factory-registry.js\";\n\n/**\n * Execute a cron job. Dispatches to one of three targets:\n * - `workflow` (SE35) → `workflow.run(inputData)` on the held instance (the\n * instance carries its own `.run`, so this module never imports `workflow.ts`),\n * returning the already-terminal {@link WorkflowRun}.\n * - `agent` → an ephemeral agent per fire; `agent.send(message)` → {@link Run}.\n * - `agentId` → reuse an existing agent; `agent.send(message)` → {@link Run}.\n *\n * Used by both `Cron.run(jobId)` (manual off-schedule fire) and the scheduler's\n * default fire handler. ADR 0014.\n *\n * @internal\n */\nexport async function runCronJob(job: CronJob): Promise<Run | WorkflowRun> {\n // `Workflow.run()` resolves only on a TERMINAL run (completed/failed/suspended/\n // cancelled — the executor never returns `status: \"running\"`), so the fire\n // handler treats the returned WorkflowRun as terminal (no `.wait()`).\n if (job.workflow !== undefined) return job.workflow.run(job.inputData);\n if (job.agent !== undefined) return runWithEphemeralAgent(job.agent, requireMessage(job));\n if (job.agentId !== undefined) return runWithExistingAgent(job.agentId, requireMessage(job));\n throw new ConfigurationError(\n `Cron job ${job.id} has no target (agent, agentId, or workflow) — cannot run.`,\n { code: \"cron_no_target\" },\n );\n}\n\n/**\n * Discriminate the {@link runCronJob} union: an agent `Run` is deferred (carries\n * `.wait()`/`.cancel()`); a {@link WorkflowRun} is already terminal (no `.wait()`).\n * @internal\n */\nexport function isAgentRun(outcome: Run | WorkflowRun): outcome is Run {\n return typeof (outcome as Run).wait === \"function\";\n}\n\n/** Agent targets require a message; fail-loud if one somehow reached a fire without it. */\nfunction requireMessage(job: CronJob): string | SDKUserMessage {\n if (job.message === undefined) {\n throw new ConfigurationError(`Cron job ${job.id} is an agent target but has no message.`, {\n code: \"cron_missing_message\",\n });\n }\n return job.message;\n}\n\nasync function runWithExistingAgent(\n agentId: string,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const info = await getAgentFacade()\n .get(agentId)\n .catch(() => undefined);\n if (info === undefined) {\n throw new UnknownAgentError(\n `Cron job references agentId \"${agentId}\" but no such agent is registered. The agent may have been disposed or the process restarted without persisting the agent registry.`,\n { code: \"agent_not_registered\" },\n );\n }\n const agent = await getAgentFacade().resume(agentId);\n return agent.send(message);\n}\n\nasync function runWithEphemeralAgent(\n baseOptions: AgentOptions,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const agent = await getAgentFacade().create(baseOptions);\n return agent.send(message);\n}\n","/**\n * Default cron fire handler (extracted from `Cron.start` for testability + G8).\n *\n * Every fire registers as a Task (ADRs D363/D374) so callers observe it via\n * `Task.list` / `Task.subscribe`. SE35 (ADR 0014): the fire target may be an\n * agent (a deferred {@link Run} — abort-wire + `wait()`) OR a workflow (an\n * already-terminal {@link WorkflowRun} — no `wait()`); `isAgentRun` discriminates\n * so the handler records the correct terminal status/runId for each shape.\n *\n * @internal\n */\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { submit as taskRegistrySubmit } from \"../task/registry.js\";\nimport { isAgentRun, runCronJob } from \"./run-job.js\";\n\nexport async function fireCronJobAsTask(job: CronJob): Promise<void> {\n // The task id namespace `cron-{jobId}-{fireEpochMs}` honors D368/EC-5.\n const fireTs = Date.now();\n const taskId = `cron-${job.id}-${fireTs}`;\n try {\n await taskRegistrySubmit({\n kind: \"cron\",\n id: taskId,\n allowReservedPrefix: true,\n meta: { jobId: job.id, jobName: job.name, schedule: job.cron, firedAt: fireTs },\n work: async (ctx) => {\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) {\n // Agent target — the Run is deferred: abort-wire + await terminal.\n ctx.signal.addEventListener(\"abort\", () => void outcome.cancel().catch(() => {}), {\n once: true,\n });\n const result = await outcome.wait();\n ctx.emit({ status: result.status, runId: outcome.id });\n return { status: result.status, runId: outcome.id };\n }\n // SE35 workflow target — the WorkflowRun is ALREADY terminal (no wait()).\n ctx.emit({ status: outcome.status, runId: outcome.id });\n return { status: outcome.status, runId: outcome.id };\n },\n });\n } catch {\n // Task registry must not break cron — fall through to a direct run. No\n // double-execution: `taskRegistrySubmit` runs `work` (which calls\n // `runCronJob`) fire-and-forget, so a throw here means the SUBMIT itself\n // failed (id/registry setup) BEFORE `work` started — the job never ran, and\n // this is its first + only execution.\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) await outcome.wait();\n }\n}\n","import type { CronJob } from \"../../types/cron.js\";\n\n/**\n * Process-wide cron job store. In Phase 1 we keep all jobs in memory\n * (across local + cloud runtimes). Local-runtime persistence to\n * `.theokit/cron/jobs.json` lands when the local runtime adapter is wired.\n *\n * @internal\n */\nconst jobs = new Map<string, CronJob>();\n\n/** Snapshot of every known cron job. @internal */\nexport function listJobs(): CronJob[] {\n return Array.from(jobs.values());\n}\n\n/** Total job count across runtimes. @internal */\nexport function jobCount(): number {\n return jobs.size;\n}\n\n/** Fetch a single job by id, or `undefined` if it does not exist. @internal */\nexport function getJob(jobId: string): CronJob | undefined {\n return jobs.get(jobId);\n}\n\n/** Insert or replace a job. @internal */\nexport function upsertJob(job: CronJob): void {\n jobs.set(job.id, job);\n}\n\n/** Delete a job. Returns `true` if a job was removed. @internal */\nexport function deleteJob(jobId: string): boolean {\n return jobs.delete(jobId);\n}\n\n/** Test-only: drop every job. @internal */\nexport function clearJobs(): void {\n jobs.clear();\n}\n","import { Cron as Croner } from \"croner\";\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { listJobs, upsertJob } from \"./store.js\";\n\n/**\n * Real local cron scheduler. When `Cron.start()` is called the scheduler\n * installs a Croner timer per enabled local job; on fire the registered\n * fire handler runs the underlying agent. `Cron.stop()` tears every timer\n * down but keeps the jobs in the store.\n *\n * @internal\n */\n\nexport type CronFireHandler = (job: CronJob) => Promise<void> | void;\n\ninterface SchedulerState {\n running: boolean;\n cwd?: string;\n timers: Map<string, Croner>;\n fireHandler?: CronFireHandler;\n}\n\nconst state: SchedulerState = { running: false, timers: new Map() };\n\n/**\n * Register the callback invoked when a job fires. The runtime adapter\n * supplies a handler that actually executes the agent; fixture-mode tests\n * leave it unset so timers tick without side effects.\n *\n * @internal\n */\nexport function setCronFireHandler(handler: CronFireHandler | undefined): void {\n state.fireHandler = handler;\n}\n\n/** Activate the scheduler and install timers for every enabled local job. @internal */\nexport function startScheduler(cwd?: string): void {\n state.running = true;\n if (cwd !== undefined) state.cwd = cwd;\n for (const job of listJobs()) {\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n }\n}\n\n/** Deactivate the scheduler. Stops every timer; jobs remain in the store. @internal */\nexport function stopScheduler(): void {\n state.running = false;\n for (const timer of state.timers.values()) timer.stop();\n state.timers.clear();\n}\n\n/** Schedule a single job. No-op if the scheduler is not running. @internal */\nexport function scheduleJob(job: CronJob): void {\n if (!state.running) return;\n unscheduleJob(job.id);\n const expression = normalizeExpression(job.cron);\n const timer = new Croner(\n expression,\n { timezone: job.timezone, name: job.id, protect: true },\n () => {\n void fireJob(job.id);\n },\n );\n state.timers.set(job.id, timer);\n refreshNextRunAt(job.id, timer);\n}\n\n/** Tear down the timer for a single job. @internal */\nexport function unscheduleJob(jobId: string): boolean {\n const timer = state.timers.get(jobId);\n if (timer === undefined) return false;\n timer.stop();\n state.timers.delete(jobId);\n return true;\n}\n\n/** Snapshot of the scheduler's running flag and configured workspace. @internal */\nexport function getSchedulerState(): { running: boolean; cwd?: string } {\n const result: { running: boolean; cwd?: string } = { running: state.running };\n if (state.cwd !== undefined) result.cwd = state.cwd;\n return result;\n}\n\nasync function fireJob(jobId: string): Promise<void> {\n const fresh = listJobs().find((entry) => entry.id === jobId);\n if (fresh === undefined || fresh.enabled === false) return;\n const handler = state.fireHandler;\n upsertJob({ ...fresh, lastRunAt: Date.now() });\n if (handler === undefined) return;\n try {\n await handler(fresh);\n } catch {\n // Swallow handler errors — the scheduler must keep ticking. Real\n // surface for run failures lives on the Run.wait() result itself.\n }\n}\n\nfunction refreshNextRunAt(jobId: string, timer: Croner): void {\n const next = timer.nextRun();\n if (next === null) return;\n const existing = listJobs().find((entry) => entry.id === jobId);\n if (existing === undefined) return;\n upsertJob({ ...existing, nextRunAt: next.getTime() });\n}\n\nfunction normalizeExpression(cron: string): string {\n switch (cron) {\n case \"@hourly\":\n return \"0 * * * *\";\n case \"@daily\":\n return \"0 0 * * *\";\n case \"@weekly\":\n return \"0 0 * * 0\";\n case \"@monthly\":\n return \"0 0 1 * *\";\n case \"@yearly\":\n return \"0 0 1 1 *\";\n default:\n return cron;\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\n\n/**\n * POSIX-cron + shorthand validators used by `Cron.create()`. Throws\n * `ConfigurationError` with a stable message and code on invalid input.\n *\n * @internal\n */\n\nconst SHORTHANDS = new Set([\"@hourly\", \"@daily\", \"@weekly\", \"@monthly\", \"@yearly\"]);\n\ninterface FieldRange {\n min: number;\n max: number;\n}\n\nconst FIELD_RANGES: readonly FieldRange[] = [\n { min: 0, max: 59 }, // minute\n { min: 0, max: 23 }, // hour\n { min: 1, max: 31 }, // day-of-month\n { min: 1, max: 12 }, // month\n { min: 0, max: 6 }, // day-of-week\n];\n\n/**\n * Validate a cron expression. Accepts shorthand (`@hourly`, ..., `@yearly`)\n * or 5-field POSIX cron with star, literals, star/N step, N-M range, and\n * N,M,P list.\n *\n * @internal\n */\nexport function validateCronExpression(cron: string): void {\n if (typeof cron !== \"string\" || cron.length === 0) {\n throw new ConfigurationError(\"Invalid cron expression: empty\", {\n code: \"invalid_cron\",\n });\n }\n if (cron.startsWith(\"@\")) {\n if (!SHORTHANDS.has(cron)) {\n throw new ConfigurationError(`Invalid cron expression: unknown shorthand ${cron}`, {\n code: \"invalid_cron\",\n });\n }\n return;\n }\n\n const fields = cron.trim().split(/\\s+/);\n if (fields.length !== FIELD_RANGES.length) {\n throw new ConfigurationError(\n `Invalid cron expression: ${cron} (expected ${FIELD_RANGES.length} fields, got ${fields.length})`,\n { code: \"invalid_cron\" },\n );\n }\n for (const [index, range] of FIELD_RANGES.entries()) {\n // The length check above already established one field per range, so the lookup is total.\n // B-116: this replaces a `range === undefined` guard that no caller could reach — its single\n // caller only ran with exactly 5 fields, and FIELD_RANGES has exactly 5 entries, so the branch\n // stayed at 0 executions through 37 tests written specifically to enter it.\n const field = fields[index] as string;\n if (!isValidCronField(field, range)) {\n throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {\n code: \"invalid_cron\",\n });\n }\n }\n}\n\nfunction isValidCronField(field: string, range: FieldRange): boolean {\n if (field === \"*\") return true;\n if (field.startsWith(\"*/\")) return isValidStep(field.slice(2), range);\n if (field.includes(\",\")) {\n return field.split(\",\").every((part) => isValidCronField(part, range));\n }\n if (field.includes(\"-\")) return isValidRange(field, range);\n return isValidLiteral(field, range);\n}\n\n/**\n * Digits, and nothing else. `Number.parseInt` stops at the first non-digit, so it reads `\"5abc\"` as\n * `5` and `\"0x5\"` as `0` — a numeric field parsed that way accepts garbage that happens to start\n * with a digit.\n *\n * This replaces the `String(n) === field` round-trip the literal and step validators used to carry.\n * The round-trip refused the garbage correctly but also refused `\"07\"`, because `String(7) !== \"07\"`\n * — and `isValidRange` never had it at all, so `\"1-5abc\"` was accepted while `\"5abc\"` was refused\n * (B-121). One predicate, applied to every field shape, closes both halves.\n *\n * The boundary that matters is croner 9, the scheduler this SDK actually fires jobs with. Measured\n * 2026-08-19: it ACCEPTS `\"07 * * * *\"` (next run at :07) and REFUSES `\"5abc\"`, `\"1-5abc\"`,\n * `\"1abc-5\"`, `\"0x5\"`, `\"5.9\"`, `\"+5\"` and `\"1e1\"` as \"illegal character\" (B-122). Validating\n * stricter than the engine rejects schedules that would have run; validating looser only moves the\n * failure from `Cron.create()` to fire time, where nobody is watching.\n *\n * @internal\n */\nconst DIGITS_ONLY = /^\\d+$/;\n\nfunction parseFieldNumber(text: string): number | undefined {\n if (!DIGITS_ONLY.test(text)) return undefined;\n return Number.parseInt(text, 10);\n}\n\nfunction isValidStep(stepStr: string, range: FieldRange): boolean {\n const step = parseFieldNumber(stepStr);\n return step !== undefined && step > 0 && step <= range.max;\n}\n\nfunction isValidRange(field: string, range: FieldRange): boolean {\n const parts = field.split(\"-\");\n if (parts.length !== 2) return false;\n const [startStr, endStr] = parts;\n if (startStr === undefined || endStr === undefined) return false;\n const start = parseFieldNumber(startStr);\n const end = parseFieldNumber(endStr);\n if (start === undefined || end === undefined) return false;\n return start >= range.min && end <= range.max && start <= end;\n}\n\nfunction isValidLiteral(field: string, range: FieldRange): boolean {\n const n = parseFieldNumber(field);\n return n !== undefined && n >= range.min && n <= range.max;\n}\n\n/**\n * Validate an IANA timezone. Uses `Intl.DateTimeFormat`'s strict timezone\n * lookup; invalid values raise `RangeError` which we wrap.\n *\n * @internal\n */\nexport function validateTimezone(timezone: string): void {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n } catch {\n throw new ConfigurationError(`Invalid IANA timezone: ${timezone}`, {\n code: \"invalid_timezone\",\n });\n }\n}\n\n/**\n * Heuristic next-fire-at estimator for fixture mode. Returns a timestamp\n * one hour in the future for shorthand/POSIX inputs. Real scheduling uses\n * a proper evaluator wired in by the local scheduler.\n *\n * @internal\n */\nexport function estimateNextRunAt(_cron: string, _timezone: string): number {\n return Date.now() + 60 * 60 * 1000;\n}\n","// Bootstrap import: loading this facade must register the public Agent facade\n// into the agent-factory-registry seam, because `internal/cron/run-job.ts`\n// resolves it via `getAgentFacade()` at runtime instead of importing `agent.ts`\n// directly (which would invert the public-api -> internal dependency\n// direction). The `@theokit/sdk/cron` sub-path entry would otherwise throw\n// \"Agent facade not registered\" at runtime.\nimport \"./agent.js\";\nimport { ConfigurationError, UnknownAgentError } from \"./errors.js\";\nimport { fireCronJobAsTask } from \"./internal/cron/fire-handler.js\";\nimport { runCronJob } from \"./internal/cron/run-job.js\";\nimport {\n getSchedulerState,\n scheduleJob,\n setCronFireHandler,\n startScheduler,\n stopScheduler,\n unscheduleJob,\n} from \"./internal/cron/scheduler.js\";\nimport { deleteJob, getJob, jobCount, listJobs, upsertJob } from \"./internal/cron/store.js\";\nimport {\n estimateNextRunAt,\n validateCronExpression,\n validateTimezone,\n} from \"./internal/cron/validate.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { generateCronId } from \"./internal/ids.js\";\nimport type { AgentOptions, ListResult } from \"./types/agent.js\";\nimport type {\n CronCreateOptions,\n CronGetOptions,\n CronJob,\n CronListOptions,\n CronOperationOptions,\n CronRunOptions,\n CronRuntime,\n CronSchedulerStatus,\n CronStartOptions,\n} from \"./types/cron.js\";\nimport type { Run } from \"./types/run.js\";\n\n/**\n * Static façade for scheduling Theo agent runs on a cron expression.\n *\n * @public\n */\nexport class Cron {\n private constructor() {\n // Static-only façade.\n }\n\n /**\n * Create and persist a cron job.\n *\n * @public\n */\n static async create(options: CronCreateOptions): Promise<CronJob> {\n const job = await createCronJob(options);\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n return job;\n }\n\n /**\n * List cron jobs (local, cloud, or both).\n *\n * @public\n */\n static list(options: CronListOptions = {}): Promise<ListResult<CronJob>> {\n const runtimeFilter = options.runtime;\n const items = listJobs().filter((job) =>\n runtimeFilter === undefined ? true : job.runtime === runtimeFilter,\n );\n return Promise.resolve({ items });\n }\n\n /**\n * Get a single cron job by ID.\n *\n * @public\n */\n static get(jobId: string, _options: CronGetOptions = {}): Promise<CronJob> {\n const job = getJob(jobId);\n if (job === undefined) {\n return Promise.reject(\n new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" }),\n );\n }\n return Promise.resolve(job);\n }\n\n /**\n * Delete a cron job permanently.\n *\n * @public\n */\n static delete(jobId: string, _options: CronOperationOptions = {}): Promise<void> {\n unscheduleJob(jobId);\n deleteJob(jobId);\n return Promise.resolve();\n }\n\n /**\n * Re-enable a paused cron job.\n *\n * @public\n */\n static async enable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, true);\n }\n\n /**\n * Pause a cron job without deleting it.\n *\n * @public\n */\n static async disable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, false);\n }\n\n /**\n * Manually trigger a cron job off-schedule. Returns the resulting `Run`\n * (agent target) or `WorkflowRun` (workflow target — SE35).\n *\n * @public\n */\n static async run(\n jobId: string,\n _options: CronRunOptions = {},\n ): Promise<Run | import(\"./types/workflow.js\").WorkflowRun> {\n const job = getJob(jobId);\n if (job === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n return runCronJob(job);\n }\n\n /**\n * Activate the in-process scheduler for local cron jobs.\n *\n * @public\n */\n static start(options: CronStartOptions = {}): Promise<void> {\n // Install the default fire handler so timer ticks actually drive a real\n // agent/workflow run. Users can override via `setCronFireHandler` from\n // `@theokit/sdk/internal` (test-mode hook). Handler body lives in\n // `internal/cron/fire-handler.ts` (testable + G8).\n setCronFireHandler(fireCronJobAsTask);\n startScheduler(options.cwd);\n return Promise.resolve();\n }\n\n /**\n * Stop the in-process scheduler. Jobs are preserved.\n *\n * @public\n */\n static stop(): Promise<void> {\n stopScheduler();\n return Promise.resolve();\n }\n\n /**\n * Snapshot of the local scheduler.\n *\n * @public\n */\n static status(_options: CronStartOptions = {}): Promise<CronSchedulerStatus> {\n const scheduler = getSchedulerState();\n return Promise.resolve({ running: scheduler.running, jobCount: jobCount() });\n }\n}\n\nasync function createCronJob(options: CronCreateOptions): Promise<CronJob> {\n validateCronTarget(options);\n\n validateCronExpression(options.cron);\n const timezone = options.timezone ?? \"UTC\";\n validateTimezone(timezone);\n\n // apiKey is accepted but not required for cron-create in fixture mode.\n resolveApiKey(options.apiKey);\n\n const runtime = detectRuntime(options);\n const now = Date.now();\n const job: CronJob = {\n id: generateCronId(),\n cron: options.cron,\n timezone,\n enabled: options.enabled ?? true,\n status: options.enabled === false ? \"paused\" : \"scheduled\",\n runtime,\n createdAt: now,\n nextRunAt: estimateNextRunAt(options.cron, timezone),\n ...(options.name !== undefined ? { name: options.name } : {}),\n ...(options.message !== undefined ? { message: options.message } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n ...(options.agentId !== undefined ? { agentId: options.agentId } : {}),\n ...(options.workflow !== undefined ? { workflow: options.workflow } : {}),\n ...(options.inputData !== undefined ? { inputData: options.inputData } : {}),\n };\n upsertJob(job);\n return job;\n}\n\n/**\n * SE35 (ADR 0014) — exactly ONE target (`agent` | `agentId` | `workflow`).\n * Agent targets require `message`; a workflow target takes `inputData` and MUST\n * NOT set `message`.\n */\nfunction validateCronTarget(options: CronCreateOptions): void {\n const targets = [options.agent, options.agentId, options.workflow].filter(\n (t) => t !== undefined,\n ).length;\n if (targets > 1) {\n throw new ConfigurationError(\n \"agent, agentId, and workflow are mutually exclusive — pass exactly one target.\",\n { code: \"cron_ambiguous_target\" },\n );\n }\n if (targets === 0) {\n throw new ConfigurationError(\n \"Cron job requires exactly one target: agent, agentId, or workflow.\",\n { code: \"cron_no_target\" },\n );\n }\n if (options.workflow !== undefined && options.message !== undefined) {\n throw new ConfigurationError(\n \"A workflow cron target takes inputData, not a message — remove `message`.\",\n { code: \"cron_workflow_message\" },\n );\n }\n if (options.workflow === undefined && options.message === undefined) {\n throw new ConfigurationError(\"An agent cron target requires a message.\", {\n code: \"cron_missing_message\",\n });\n }\n}\n\nfunction detectRuntime(options: CronCreateOptions): CronRuntime {\n // SE35 — a workflow target is a held in-memory instance; it can only run in\n // the local (in-process) scheduler. A workflow instance cannot cross the\n // cloud process boundary (ADR 0014).\n if (options.workflow !== undefined) return \"local\";\n if (options.agentId !== undefined) {\n return options.agentId.startsWith(\"bc-\") ? \"cloud\" : \"local\";\n }\n const agent = options.agent as AgentOptions | undefined;\n if (agent?.cloud !== undefined) return \"cloud\";\n return \"local\";\n}\n\nasync function updateJobStatus(jobId: string, enabled: boolean): Promise<CronJob> {\n const existing = getJob(jobId);\n if (existing === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n const updated: CronJob = {\n ...existing,\n enabled,\n status: enabled ? \"scheduled\" : \"paused\",\n };\n upsertJob(updated);\n if (updated.runtime === \"local\") {\n if (enabled) {\n scheduleJob(updated);\n } else {\n unscheduleJob(updated.id);\n }\n }\n return updated;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { atomicWriteText } from './chunk-6AZDM6LK.js';
1
+ import { atomicWriteText } from './chunk-VF7EWVDG.js';
2
2
  import { mkdir, readFile, readdir } from 'fs/promises';
3
3
  import { join } from 'path';
4
4
 
@@ -249,5 +249,5 @@ function __resetSnapshotStoresForTests() {
249
249
  }
250
250
 
251
251
  export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests, getSnapshotStoreFor };
252
- //# sourceMappingURL=chunk-BFYGJGC5.js.map
253
- //# sourceMappingURL=chunk-BFYGJGC5.js.map
252
+ //# sourceMappingURL=chunk-AQLGBKNT.js.map
253
+ //# sourceMappingURL=chunk-AQLGBKNT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapshot-store.ts"],"names":[],"mappings":";;;;;AAkcO,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAEtD,YAA4B,MAAA,EAAgB;AAC1C,IAAA,KAAA,CAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,cAAA,CAAgB,CAAA;AADxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAE5B;AAAA,EAF4B,MAAA;AAAA,EADV,IAAA,GAAO,8BAAA;AAI3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,kCAAA,EAAqC,MAAM,CAAA,CAAE,CAAA;AAH5D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,oBAAA;AAO3B;AAMO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAE7C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,mCAAA,EAAsC,MAAM,CAAA,CAAE,CAAA;AAH7D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,qBAAA;AAO3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA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,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,KAAA,GAAQ,IAAI,8BAA8B,GAAG,CAAA;AAC7C,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-AQLGBKNT.js","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\n/**\n * Any node of a committed workflow, discriminated by `kind`.\n *\n * Build these with the helpers rather than by hand: `fn()` and `agentStep()` set the discriminator,\n * validate the id, and parse the retry policy at construction — where a mistake is cheap — while the\n * builder methods `.parallel()`, `.branch()`, `.foreach()`, `.dowhile()`, `.sleep()` and `.suspend()`\n * cover the remaining variants and mint a positional default id (`parallel_0`, `branch_1`, ...) when\n * you do not pass one.\n *\n * Every id, nested ones included, must match `^[a-z0-9][a-z0-9_-]*$` case-insensitively and be at\n * most 64 characters, and must be unique across the whole workflow. `.commit()` walks the tree —\n * parallel branches, branch predicates, the fallback, and the inner step of a `foreach`/`dowhile` —\n * and throws {@link WorkflowDuplicateStepIdError} on the second occurrence.\n */\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Reflection (theokit#161) ─── */\n\n/**\n * theokit#161 — one step of a workflow, as a reflection surface sees it.\n *\n * `id` and `kind` are the only fields every step variant shares, and they are what a reflection\n * endpoint renders. Everything else a step carries is an executable — a predicate, a condition, an\n * agent, a prompt template — which cannot cross a process boundary and means nothing to a caller\n * enumerating shape.\n *\n * @public\n */\nexport interface WorkflowStepDescription {\n readonly id: string;\n readonly kind: Step[\"kind\"];\n /**\n * Nested steps, for the variants that contain them: `parallel` (all branches, flattened — the\n * branch grouping is a scheduling detail, not shape a reader needs), `branch` (each predicate's\n * steps plus the fallback), `foreach` and `dowhile` (their single inner step).\n *\n * Absent for leaf steps. A flat list would misreport a parallel or branching workflow as linear.\n */\n readonly steps?: readonly WorkflowStepDescription[];\n}\n\n/**\n * theokit#161 — the read-only shape of a committed workflow.\n *\n * Returned by `Workflow.describe()`. There is deliberately NO workflow registry to enumerate: a\n * `Workflow` is a value the caller constructs and holds, so the caller already knows which ones\n * exist. What it lacked was a way to DESCRIBE one. A registry would have added process-global state\n * that nothing ever releases, to re-answer a question the host can answer itself.\n *\n * @public\n */\nexport interface WorkflowDescription {\n readonly name: string;\n readonly steps: readonly WorkflowStepDescription[];\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\n/**\n * The outcome of one step, appended to `WorkflowRun.stepResults` in execution order.\n *\n * A failing step does not throw out of `run()`. It lands here with `status: \"failed\"` and its error\n * flattened to `{ name, message }` — the thrown instance is gone by the time a caller sees it, so\n * match on `error.name` and never on `instanceof`.\n *\n * `\"skipped\"` occurs only for a `branch` step whose predicates all returned false and which declared\n * no fallback; its `output` is the step input, passed through unchanged. `\"suspended\"` marks the step\n * that called `StepContext.suspend()`, is always the last entry of the run, and carries no output.\n *\n * `attempts` means different things per kind. For `fn` and `agent` it counts execution attempts: 1\n * without a `retry` policy, and 0 when the step failed before its body ran — an `inputSchema`\n * rejection, a prompt template that threw, a `compensate` v1 refuses, or a cloud agent. For `dowhile`\n * it counts loop iterations instead.\n */\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\n/**\n * The terminal record of one run — what `Workflow.run()` resolves to, what `Workflow.resume()`\n * returns, and what the `result` promise of `Workflow.stream()` settles with.\n *\n * Read `status`; do not rely on `catch`. A step that throws does not reject the promise, it ends the\n * run with `status: \"failed\"` and the error in `error`. Only `completed` populates `output`; `failed`\n * and `cancelled` (an aborted `signal`) populate `error`; `suspended` populates neither and means a\n * snapshot exists under `id` for `Workflow.resume()`. `running` is part of the union for the benefit\n * of a host tracking a run in flight — the executor only ever assembles a terminal one.\n *\n * `stepResults` is cumulative across a resume: the executor seeds it with the snapshot's prior\n * results, so the record of a resumed run covers the steps that ran before the suspend as well.\n */\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\n/**\n * The persisted state of a suspended run: written when a step calls `StepContext.suspend()`, read\n * back by `Workflow.resume()`. Callers never construct one — the type is exported so a host can\n * inspect what the persistence backend wrote.\n *\n * Snapshots are single-shot. `resume()` deletes the snapshot before re-entering the executor, so the\n * same one cannot be resumed twice; a second attempt raises\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * Everything reachable from here must survive `JSON.stringify` — the store serializes on save even\n * for the memory backend, and raises `WorkflowNotSerializableError` rather than letting a `TypeError`\n * escape. That rules out BigInt, circular references and class instances in step outputs, in\n * `accumulatedInput` and in `state`.\n *\n * `currentStepId` is the suspending step, and resume continues from the step AFTER it. A workflow\n * definition edited between suspend and resume therefore either fails with\n * `WorkflowResumeStepNotFoundError` (the id is gone) or resumes at a position the author did not\n * intend (the id moved).\n */\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\n/**\n * Where suspend snapshots are kept. Omitting `WorkflowOptions.persistence` selects the same store\n * `backend: \"memory\"` selects explicitly.\n *\n * `\"memory\"` is one process-wide map shared by every workflow, so a run suspended under it can only\n * be resumed by the process that suspended it, and only until it exits. `\"json\"` writes one\n * `{runId}.json` per snapshot into `dir` through an atomic write and survives a restart. Any suspend\n * point that waits on a human or an external system needs `\"json\"`; `\"memory\"` is for tests and for\n * suspends resolved within the same process.\n *\n * `dir` is required when `backend` is `\"json\"` and ignored otherwise — `Workflow.create()` rejects\n * the options up front when it is missing or empty, rather than failing at the first suspend.\n */\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\n/**\n * Configuration for `Workflow.create()`, validated by Zod before the builder is handed back: a `name`\n * outside 1..128 characters, or `persistence.backend: \"json\"` without a `dir`, throws there rather\n * than at run time.\n *\n * `name` is an observability and error-message label, not an identity. Two workflows may share one;\n * the identity behind the single-flight lock is minted per `.commit()` call, so two separately\n * committed workflows never block each other however they are named.\n *\n * The three schemas are independent and each optional: `inputSchema` guards `run(input)` before step\n * 1, `outputSchema` guards the final value on the completed path only (a suspended or failed run\n * skips it), and `stateSchema` guards `initialState` plus every `StepContext.setState()` call. All\n * three must be synchronous — a schema carrying an async refinement is reported as a validation\n * failure with that explanation, never awaited.\n */\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\n/**\n * Per-run options for `Workflow.run()` and `Workflow.stream()`.\n *\n * `signal` is combined with the run's internal single-flight signal and reaches every step through\n * `StepContext.signal`. The executor itself checks it at step boundaries, so a step that ignores the\n * signal runs to completion before the run reports `status: \"cancelled\"` — a step doing long I/O\n * should pass `ctx.signal` down to make abort prompt.\n *\n * `runId` is minted per call (`wfr-` plus 8 hex) unless you pass it, which is why concurrent runs of\n * one workflow do not interfere. Pinning it buys a deterministic id for resume, and buys the\n * single-flight lock with it: starting a second run of the same committed workflow under a `runId`\n * that is still in flight throws {@link WorkflowAlreadyRunningError}.\n */\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\n/**\n * Arguments for `Workflow.resume()`.\n *\n * `workflow` is typed structurally as `{ run }`, but resume needs more than `run`: it reads the\n * committed steps and options off the instance and throws a plain `Error` — \"Workflow.resume requires\n * an instance from Workflow.create().commit()\" — for anything else. Pass the same committed\n * `Workflow` the suspended run came from, not a stand-in.\n *\n * `runId` selects the snapshot. An id with no snapshot throws\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * `payload` becomes the input of the step after the suspend point, and is parsed against the\n * suspending step's `payloadSchema` first when it declared one (a mismatch throws out of `resume`).\n * Omit it to resume from the accumulated input captured in the snapshot instead — the two are\n * alternatives, not a merge.\n */\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\n/**\n * Thrown by `.commit()` when one step id appears twice anywhere in the workflow — including inside a\n * parallel branch, a branch predicate, the fallback, and the inner step of a `foreach` or `dowhile`.\n *\n * Ids address steps in snapshots and on resume, so this is refused at build time rather than\n * discovered mid-run. Workflows nested with `workflowStep()` are exempt: the child runs in its own\n * executor with its own id-space, so its ids cannot collide with the parent's.\n */\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\n/**\n * Thrown out of `Workflow.run()` — one of the few workflow failures that rejects instead of arriving\n * as `run.status === \"failed\"` — when the committed workflow already has a run in flight under the\n * same run id.\n *\n * The lock key pairs the id minted at `.commit()` with the run id, not `WorkflowOptions.name`, so\n * two workflows sharing a name are independent and concurrent runs with distinct minted ids never\n * collide. In practice this only fires when a caller pins `WorkflowRunOptions.runId`, or resumes a\n * run id that is still executing. The registry is an in-process map: a crash releases every lock, and\n * it says nothing about runs in other processes.\n */\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\n/**\n * Thrown by `Workflow.resume()` when no snapshot exists for the given run id.\n *\n * The message suggests configuring persistence, which is the common cause but not the only one. The\n * run may never have suspended; it may have suspended under the default memory backend in a process\n * that has since exited; or the snapshot may already have been consumed, since resume deletes it\n * before re-entering the executor and a second resume of the same run id lands here.\n */\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\n/**\n * Raised when a `dowhile` step's condition kept returning true past `maxIterations` (default 100).\n *\n * It does not escape `run()`: the step fails, the run ends `status: \"failed\"`, and the error reaches\n * the caller flattened as `run.error` with `name: \"WorkflowMaxIterationsExceededError\"` — match on\n * the name, the instance does not survive. The guard is evaluated before each iteration, so the inner\n * step runs at most `maxIterations` times; raising the ceiling is a `maxIterations` on the step, and\n * there is no global default to change.\n */\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
@@ -94,6 +94,6 @@ function newTransaction(opts) {
94
94
  };
95
95
  }
96
96
 
97
- export { AuthSecretTooShortError, __TESTING__deriveKey, clearTransaction, encodeTransaction, getTransaction, newTransaction };
98
- //# sourceMappingURL=chunk-7W7ZWMLQ.js.map
99
- //# sourceMappingURL=chunk-7W7ZWMLQ.js.map
97
+ export { AuthSecretTooShortError, COOKIE_NAME, __TESTING__deriveKey, clearTransaction, encodeTransaction, getTransaction, newTransaction };
98
+ //# sourceMappingURL=chunk-AWO27VRZ.js.map
99
+ //# sourceMappingURL=chunk-AWO27VRZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/auth/oauth-transaction-store.ts"],"names":[],"mappings":";;;;AAyCO,IAAM,WAAA,GAAc;AAC3B,IAAM,cAAA,GAAiB,KAAK,EAAA,GAAK,GAAA;AAKjC,IAAM,SAAA,GAAY,qBAAA;AAmBlB,eAAe,UAAU,MAAA,EAA8C;AACrE,EAAA,MAAM,WAAA,GAAc,IAAI,WAAA,EAAY,CAAE,OAAO,MAAM,CAAA;AACnD,EAAA,IAAI,WAAA,CAAY,aAAa,EAAA,EAAI;AAC/B,IAAA,MAAM,IAAI,uBAAA,CAAwB,WAAA,CAAY,UAAU,CAAA;AAAA,EAC1D;AACA,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,qBAAA,IAAyB,EAAA;AACrD,EAAA,MAAM,IAAA,GAAO,IAAI,WAAA,EAAY,CAAE,OAAO,OAAO,CAAA;AAE7C,EAAA,MAAM,GAAA,GAAM,MAAM,SAAA,CAAU,MAAA,CAAO,SAAA,CAAU,KAAA,EAAO,WAAA,EAAa,MAAA,EAAQ,KAAA,EAAO,CAAC,YAAY,CAAC,CAAA;AAE9F,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,MAAA,CAAO,UAAA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,IAAA,CAAK,YAAA;AAAA,IACnB,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,SAAA,EAAW,GAAA;AAAA,IACX,WAAW,GAAA,GAAM;AAAA,GACnB;AACF","file":"chunk-AWO27VRZ.js","sourcesContent":["/**\n * Encrypted OAuth transaction cookie store — `@theokit/sdk/server/auth`.\n *\n * Per ADR D5 — cookie-state pattern (no Redis/db dependency in core).\n *\n * Stores OAuthTransaction (state + pkceVerifier + returnTo + expiry) in a\n * single signed+encrypted HttpOnly cookie. Stateless, works in edge/serverless.\n *\n * Cookie name: `__Host-theo_oauth_tx` (T5.3 — RFC 6265bis prefix)\n * Lifetime: 10 minutes (per D5 invariant)\n * Encryption: AES-256-GCM via Node's webcrypto subtle API\n *\n * Note: this is a minimal in-package implementation. Production deployments\n * may prefer using `theokit/server/auth/crypto`'s encrypt/decrypt helpers\n * via the SessionManager's existing secret rotation chain. For T1.2 we keep\n * it self-contained to avoid cross-package peer-dep complexity; T2+ may\n * refactor to share SessionManager's encrypt path.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { webcrypto } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OAuthTransaction } from \"./types.js\";\n\n// T5.3 — `__Host-` prefix per RFC 6265bis. Browsers enforce that any\n// cookie with this prefix MUST be set with `Secure`, MUST NOT carry a\n// `Domain` attribute, and MUST have `Path=/`. This blocks the\n// subdomain-fixation vector where a malicious page on\n// `evil.example.com` could plant a same-name cookie that the parent\n// app at `example.com` would happily decrypt.\n/**\n * The transaction cookie's name. EXPORTED so the orchestrator uses this and not a second literal.\n *\n * It was module-private, and `orchestrator.ts` therefore built its `Set-Cookie` header by hand and\n * wrote `theo_oauth_tx=` — losing the `__Host-` prefix. Every OAuth sign-in driven through the\n * orchestrator then failed at the callback, because this file reads the prefixed name. The defect\n * survived a major.\n *\n * RFC 6265bis makes `__Host-` a browser-enforced guarantee: the cookie must be `Secure`, have\n * `Path=/`, and carry no `Domain`, and a sibling subdomain cannot set it.\n */\nexport const COOKIE_NAME = \"__Host-theo_oauth_tx\";\nconst TX_LIFETIME_MS = 10 * 60 * 1000; // 10 minutes per D5\n\n// T5.1 — HKDF info string fixed per plan; bump version (v1 → v2) only when\n// the AES-GCM derivation contract itself changes (which would invalidate\n// all in-flight cookies).\nconst HKDF_INFO = \"theokit:oauth-tx-v1\";\n\n/**\n * T5.1 — Derive a 32-byte AES-256-GCM key from `secret` via HKDF-SHA256\n * (RFC 5869). Replaces the pre-T5.1 zero-padding scheme that was NOT a\n * KDF and produced near-identical keys for near-identical secrets.\n *\n * Contract:\n * - `secret` MUST be ≥ 32 bytes (256 bits) — throws otherwise.\n * - Salt is sourced from `THEOKIT_OAUTH_TX_SALT` env (UTF-8 string);\n * when unset, RFC 5869's zero-string fallback is used and operators\n * accept the default cross-app collision risk.\n * - `info` is fixed at \"theokit:oauth-tx-v1\" so v1 cookies decrypt\n * forever even if a future v2 derivation ships alongside.\n *\n * Throws `AuthSecretTooShortError` (typed) when secret < 32 bytes.\n *\n * @internal\n */\nasync function deriveKey(secret: string): Promise<webcrypto.CryptoKey> {\n const secretBytes = new TextEncoder().encode(secret);\n if (secretBytes.byteLength < 32) {\n throw new AuthSecretTooShortError(secretBytes.byteLength);\n }\n const saltRaw = process.env.THEOKIT_OAUTH_TX_SALT ?? \"\";\n const salt = new TextEncoder().encode(saltRaw);\n // Import the raw secret as HKDF input keying material.\n const ikm = await webcrypto.subtle.importKey(\"raw\", secretBytes, \"HKDF\", false, [\"deriveBits\"]);\n // Derive 256 bits via HKDF-SHA256.\n const derived = await webcrypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info: new TextEncoder().encode(HKDF_INFO) },\n ikm,\n 256,\n );\n // Wrap the derived bits as an AES-GCM key.\n return webcrypto.subtle.importKey(\"raw\", derived, { name: \"AES-GCM\" }, true, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\n/**\n * T5.1 — Typed error thrown when an OAuth tx-cookie secret has < 32\n * bytes of entropy. Surfaces the actual byte length so operators can\n * diagnose mis-configured env vars without leaking the secret itself.\n *\n * @public\n */\nexport class AuthSecretTooShortError extends Error {\n override readonly name = \"AuthSecretTooShortError\";\n constructor(actualBytes: number) {\n super(\n `OAuth transaction secret must be at least 32 bytes (got ${actualBytes}). ` +\n \"Generate a fresh value with: openssl rand -base64 33\",\n );\n }\n}\n\n/**\n * T5.1 — Test seam for the HKDF derivation. NOT included in the public\n * barrel — exposed only so unit tests can assert avalanche / determinism\n * properties without round-tripping through encodeTransaction.\n *\n * @internal\n */\nexport async function __TESTING__deriveKey(secret: string): Promise<webcrypto.CryptoKey> {\n return deriveKey(secret);\n}\n\nexport async function encodeTransaction(tx: OAuthTransaction, secret: string): Promise<string> {\n const key = await deriveKey(secret);\n const iv = webcrypto.getRandomValues(new Uint8Array(12));\n const plaintext = new TextEncoder().encode(JSON.stringify(tx));\n const ciphertext = await webcrypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, plaintext);\n const combined = new Uint8Array(iv.length + ciphertext.byteLength);\n combined.set(iv, 0);\n combined.set(new Uint8Array(ciphertext), iv.length);\n return Buffer.from(combined).toString(\"base64url\");\n}\n\nasync function decodeTransaction(\n encoded: string,\n secret: string,\n): Promise<OAuthTransaction | null> {\n try {\n const key = await deriveKey(secret);\n const combined = Buffer.from(encoded, \"base64url\");\n const iv = combined.slice(0, 12);\n const ciphertext = combined.slice(12);\n const plaintext = await webcrypto.subtle.decrypt({ name: \"AES-GCM\", iv }, key, ciphertext);\n const tx = JSON.parse(new TextDecoder().decode(plaintext)) as OAuthTransaction;\n return tx;\n } catch {\n return null;\n }\n}\n\nfunction getCookie(req: IncomingMessage, name: string): string | null {\n const header = req.headers.cookie;\n if (!header) return null;\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return v.join(\"=\");\n }\n return null;\n}\n\nfunction setCookie(res: ServerResponse, name: string, value: string): void {\n const existing = res.getHeader(\"Set-Cookie\");\n const cookie = `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${TX_LIFETIME_MS / 1000}`;\n if (Array.isArray(existing)) {\n res.setHeader(\"Set-Cookie\", [...existing, cookie]);\n } else if (typeof existing === \"string\") {\n res.setHeader(\"Set-Cookie\", [existing, cookie]);\n } else {\n res.setHeader(\"Set-Cookie\", cookie);\n }\n}\n\n/**\n * T5.3 — Clear the tx cookie deterministically. Emits exactly ONE\n * Set-Cookie line for `name` (filtering any prior occurrences of the\n * same name from a pre-existing Set-Cookie header) with:\n *\n * - empty value\n * - `Max-Age=0` (modern browsers — immediate delete)\n * - `Expires=Thu, 01 Jan 1970 00:00:00 GMT` (legacy fallback)\n * - `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/` — preserved so the\n * `__Host-` prefix contract is honored even on the clear path\n *\n * Pre-T5.3 this function called setCookie() with an empty value (which\n * still carried `Max-Age=600`) AND then issued a second explicit\n * `Max-Age=0` clear into the Set-Cookie header. The double-write\n * produced a duplicate response header that some legacy clients did\n * not handle deterministically.\n */\nfunction clearCookie(res: ServerResponse, name: string): void {\n const clear = `${name}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n const existing = res.getHeader(\"Set-Cookie\");\n const preserved = Array.isArray(existing)\n ? existing.filter((c) => !c.startsWith(`${name}=`))\n : typeof existing === \"string\" && !existing.startsWith(`${name}=`)\n ? [existing]\n : [];\n res.setHeader(\"Set-Cookie\", [...preserved, clear]);\n}\n\nasync function _setTransaction(\n res: ServerResponse,\n tx: OAuthTransaction,\n secret: string,\n): Promise<void> {\n const encoded = await encodeTransaction(tx, secret);\n setCookie(res, COOKIE_NAME, encoded);\n}\n// Reserved internal helper — not currently invoked (drop-in for future T2.x refactor that consolidates SessionManager + tx-store crypto paths). Underscore prefix per biome noUnusedVariables documented escape.\nvoid _setTransaction;\n\nexport async function getTransaction(\n req: IncomingMessage,\n secret: string,\n): Promise<OAuthTransaction | null> {\n const raw = getCookie(req, COOKIE_NAME);\n if (!raw) return null;\n const tx = await decodeTransaction(raw, secret);\n if (!tx) return null;\n // Check expiry\n if (tx.expiresAt < Date.now()) return null;\n return tx;\n}\n\nexport function clearTransaction(res: ServerResponse): void {\n clearCookie(res, COOKIE_NAME);\n}\n\nexport function newTransaction(opts: {\n state: string;\n pkceVerifier?: string;\n returnTo?: string;\n}): OAuthTransaction {\n const now = Date.now();\n return {\n state: opts.state,\n pkceVerifier: opts.pkceVerifier,\n returnTo: opts.returnTo,\n createdAt: now,\n expiresAt: now + TX_LIFETIME_MS,\n };\n}\n"]}
@@ -97,10 +97,11 @@ function newTransaction(opts) {
97
97
  }
98
98
 
99
99
  exports.AuthSecretTooShortError = AuthSecretTooShortError;
100
+ exports.COOKIE_NAME = COOKIE_NAME;
100
101
  exports.__TESTING__deriveKey = __TESTING__deriveKey;
101
102
  exports.clearTransaction = clearTransaction;
102
103
  exports.encodeTransaction = encodeTransaction;
103
104
  exports.getTransaction = getTransaction;
104
105
  exports.newTransaction = newTransaction;
105
- //# sourceMappingURL=chunk-VYCKUKPA.cjs.map
106
- //# sourceMappingURL=chunk-VYCKUKPA.cjs.map
106
+ //# sourceMappingURL=chunk-B2J4ZMZL.cjs.map
107
+ //# sourceMappingURL=chunk-B2J4ZMZL.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/auth/oauth-transaction-store.ts"],"names":["webcrypto","Buffer"],"mappings":";;;;;;AAyCO,IAAM,WAAA,GAAc;AAC3B,IAAM,cAAA,GAAiB,KAAK,EAAA,GAAK,GAAA;AAKjC,IAAM,SAAA,GAAY,qBAAA;AAmBlB,eAAe,UAAU,MAAA,EAA8C;AACrE,EAAA,MAAM,WAAA,GAAc,IAAI,WAAA,EAAY,CAAE,OAAO,MAAM,CAAA;AACnD,EAAA,IAAI,WAAA,CAAY,aAAa,EAAA,EAAI;AAC/B,IAAA,MAAM,IAAI,uBAAA,CAAwB,WAAA,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GAAA,EAAK,MAAM,CAAA;AAC9C,EAAA,IAAI,CAAC,IAAI,OAAO,IAAA;AAEhB,EAAA,IAAI,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,GAAA,IAAO,OAAO,IAAA;AACtC,EAAA,OAAO,EAAA;AACT;AAEO,SAAS,iBAAiB,GAAA,EAA2B;AAC1D,EAAA,WAAA,CAAY,KAAK,WAAW,CAAA;AAC9B;AAEO,SAAS,eAAe,IAAA,EAIV;AACnB,EAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AACrB,EAAA,OAAO;AAAA,IACL,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,SAAA,EAAW,GAAA;AAAA,IACX,WAAW,GAAA,GAAM;AAAA,GACnB;AACF","file":"chunk-B2J4ZMZL.cjs","sourcesContent":["/**\n * Encrypted OAuth transaction cookie store — `@theokit/sdk/server/auth`.\n *\n * Per ADR D5 — cookie-state pattern (no Redis/db dependency in core).\n *\n * Stores OAuthTransaction (state + pkceVerifier + returnTo + expiry) in a\n * single signed+encrypted HttpOnly cookie. Stateless, works in edge/serverless.\n *\n * Cookie name: `__Host-theo_oauth_tx` (T5.3 — RFC 6265bis prefix)\n * Lifetime: 10 minutes (per D5 invariant)\n * Encryption: AES-256-GCM via Node's webcrypto subtle API\n *\n * Note: this is a minimal in-package implementation. Production deployments\n * may prefer using `theokit/server/auth/crypto`'s encrypt/decrypt helpers\n * via the SessionManager's existing secret rotation chain. For T1.2 we keep\n * it self-contained to avoid cross-package peer-dep complexity; T2+ may\n * refactor to share SessionManager's encrypt path.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { webcrypto } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OAuthTransaction } from \"./types.js\";\n\n// T5.3 — `__Host-` prefix per RFC 6265bis. Browsers enforce that any\n// cookie with this prefix MUST be set with `Secure`, MUST NOT carry a\n// `Domain` attribute, and MUST have `Path=/`. This blocks the\n// subdomain-fixation vector where a malicious page on\n// `evil.example.com` could plant a same-name cookie that the parent\n// app at `example.com` would happily decrypt.\n/**\n * The transaction cookie's name. EXPORTED so the orchestrator uses this and not a second literal.\n *\n * It was module-private, and `orchestrator.ts` therefore built its `Set-Cookie` header by hand and\n * wrote `theo_oauth_tx=` — losing the `__Host-` prefix. Every OAuth sign-in driven through the\n * orchestrator then failed at the callback, because this file reads the prefixed name. The defect\n * survived a major.\n *\n * RFC 6265bis makes `__Host-` a browser-enforced guarantee: the cookie must be `Secure`, have\n * `Path=/`, and carry no `Domain`, and a sibling subdomain cannot set it.\n */\nexport const COOKIE_NAME = \"__Host-theo_oauth_tx\";\nconst TX_LIFETIME_MS = 10 * 60 * 1000; // 10 minutes per D5\n\n// T5.1 — HKDF info string fixed per plan; bump version (v1 → v2) only when\n// the AES-GCM derivation contract itself changes (which would invalidate\n// all in-flight cookies).\nconst HKDF_INFO = \"theokit:oauth-tx-v1\";\n\n/**\n * T5.1 — Derive a 32-byte AES-256-GCM key from `secret` via HKDF-SHA256\n * (RFC 5869). Replaces the pre-T5.1 zero-padding scheme that was NOT a\n * KDF and produced near-identical keys for near-identical secrets.\n *\n * Contract:\n * - `secret` MUST be ≥ 32 bytes (256 bits) — throws otherwise.\n * - Salt is sourced from `THEOKIT_OAUTH_TX_SALT` env (UTF-8 string);\n * when unset, RFC 5869's zero-string fallback is used and operators\n * accept the default cross-app collision risk.\n * - `info` is fixed at \"theokit:oauth-tx-v1\" so v1 cookies decrypt\n * forever even if a future v2 derivation ships alongside.\n *\n * Throws `AuthSecretTooShortError` (typed) when secret < 32 bytes.\n *\n * @internal\n */\nasync function deriveKey(secret: string): Promise<webcrypto.CryptoKey> {\n const secretBytes = new TextEncoder().encode(secret);\n if (secretBytes.byteLength < 32) {\n throw new AuthSecretTooShortError(secretBytes.byteLength);\n }\n const saltRaw = process.env.THEOKIT_OAUTH_TX_SALT ?? \"\";\n const salt = new TextEncoder().encode(saltRaw);\n // Import the raw secret as HKDF input keying material.\n const ikm = await webcrypto.subtle.importKey(\"raw\", secretBytes, \"HKDF\", false, [\"deriveBits\"]);\n // Derive 256 bits via HKDF-SHA256.\n const derived = await webcrypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info: new TextEncoder().encode(HKDF_INFO) },\n ikm,\n 256,\n );\n // Wrap the derived bits as an AES-GCM key.\n return webcrypto.subtle.importKey(\"raw\", derived, { name: \"AES-GCM\" }, true, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\n/**\n * T5.1 — Typed error thrown when an OAuth tx-cookie secret has < 32\n * bytes of entropy. Surfaces the actual byte length so operators can\n * diagnose mis-configured env vars without leaking the secret itself.\n *\n * @public\n */\nexport class AuthSecretTooShortError extends Error {\n override readonly name = \"AuthSecretTooShortError\";\n constructor(actualBytes: number) {\n super(\n `OAuth transaction secret must be at least 32 bytes (got ${actualBytes}). ` +\n \"Generate a fresh value with: openssl rand -base64 33\",\n );\n }\n}\n\n/**\n * T5.1 — Test seam for the HKDF derivation. NOT included in the public\n * barrel — exposed only so unit tests can assert avalanche / determinism\n * properties without round-tripping through encodeTransaction.\n *\n * @internal\n */\nexport async function __TESTING__deriveKey(secret: string): Promise<webcrypto.CryptoKey> {\n return deriveKey(secret);\n}\n\nexport async function encodeTransaction(tx: OAuthTransaction, secret: string): Promise<string> {\n const key = await deriveKey(secret);\n const iv = webcrypto.getRandomValues(new Uint8Array(12));\n const plaintext = new TextEncoder().encode(JSON.stringify(tx));\n const ciphertext = await webcrypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, plaintext);\n const combined = new Uint8Array(iv.length + ciphertext.byteLength);\n combined.set(iv, 0);\n combined.set(new Uint8Array(ciphertext), iv.length);\n return Buffer.from(combined).toString(\"base64url\");\n}\n\nasync function decodeTransaction(\n encoded: string,\n secret: string,\n): Promise<OAuthTransaction | null> {\n try {\n const key = await deriveKey(secret);\n const combined = Buffer.from(encoded, \"base64url\");\n const iv = combined.slice(0, 12);\n const ciphertext = combined.slice(12);\n const plaintext = await webcrypto.subtle.decrypt({ name: \"AES-GCM\", iv }, key, ciphertext);\n const tx = JSON.parse(new TextDecoder().decode(plaintext)) as OAuthTransaction;\n return tx;\n } catch {\n return null;\n }\n}\n\nfunction getCookie(req: IncomingMessage, name: string): string | null {\n const header = req.headers.cookie;\n if (!header) return null;\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return v.join(\"=\");\n }\n return null;\n}\n\nfunction setCookie(res: ServerResponse, name: string, value: string): void {\n const existing = res.getHeader(\"Set-Cookie\");\n const cookie = `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${TX_LIFETIME_MS / 1000}`;\n if (Array.isArray(existing)) {\n res.setHeader(\"Set-Cookie\", [...existing, cookie]);\n } else if (typeof existing === \"string\") {\n res.setHeader(\"Set-Cookie\", [existing, cookie]);\n } else {\n res.setHeader(\"Set-Cookie\", cookie);\n }\n}\n\n/**\n * T5.3 — Clear the tx cookie deterministically. Emits exactly ONE\n * Set-Cookie line for `name` (filtering any prior occurrences of the\n * same name from a pre-existing Set-Cookie header) with:\n *\n * - empty value\n * - `Max-Age=0` (modern browsers — immediate delete)\n * - `Expires=Thu, 01 Jan 1970 00:00:00 GMT` (legacy fallback)\n * - `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/` — preserved so the\n * `__Host-` prefix contract is honored even on the clear path\n *\n * Pre-T5.3 this function called setCookie() with an empty value (which\n * still carried `Max-Age=600`) AND then issued a second explicit\n * `Max-Age=0` clear into the Set-Cookie header. The double-write\n * produced a duplicate response header that some legacy clients did\n * not handle deterministically.\n */\nfunction clearCookie(res: ServerResponse, name: string): void {\n const clear = `${name}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n const existing = res.getHeader(\"Set-Cookie\");\n const preserved = Array.isArray(existing)\n ? existing.filter((c) => !c.startsWith(`${name}=`))\n : typeof existing === \"string\" && !existing.startsWith(`${name}=`)\n ? [existing]\n : [];\n res.setHeader(\"Set-Cookie\", [...preserved, clear]);\n}\n\nasync function _setTransaction(\n res: ServerResponse,\n tx: OAuthTransaction,\n secret: string,\n): Promise<void> {\n const encoded = await encodeTransaction(tx, secret);\n setCookie(res, COOKIE_NAME, encoded);\n}\n// Reserved internal helper — not currently invoked (drop-in for future T2.x refactor that consolidates SessionManager + tx-store crypto paths). Underscore prefix per biome noUnusedVariables documented escape.\nvoid _setTransaction;\n\nexport async function getTransaction(\n req: IncomingMessage,\n secret: string,\n): Promise<OAuthTransaction | null> {\n const raw = getCookie(req, COOKIE_NAME);\n if (!raw) return null;\n const tx = await decodeTransaction(raw, secret);\n if (!tx) return null;\n // Check expiry\n if (tx.expiresAt < Date.now()) return null;\n return tx;\n}\n\nexport function clearTransaction(res: ServerResponse): void {\n clearCookie(res, COOKIE_NAME);\n}\n\nexport function newTransaction(opts: {\n state: string;\n pkceVerifier?: string;\n returnTo?: string;\n}): OAuthTransaction {\n const now = Date.now();\n return {\n state: opts.state,\n pkceVerifier: opts.pkceVerifier,\n returnTo: opts.returnTo,\n createdAt: now,\n expiresAt: now + TX_LIFETIME_MS,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { reconstructMessages, SessionTranscript } from './chunk-N5CR3TJZ.js';
1
+ import { reconstructMessages, SessionTranscript } from './chunk-DZBSJX6J.js';
2
2
 
3
3
  // src/internal/session/agent-session-store.ts
4
4
  function seedTranscript(prior, opts) {
@@ -101,5 +101,5 @@ async function appendCompactBoundaryRecord(store, loc, sessionId, meta) {
101
101
  }
102
102
 
103
103
  export { appendCompactBoundaryRecord, persistTurn, readSessionMessages };
104
- //# sourceMappingURL=chunk-BERBYXFH.js.map
105
- //# sourceMappingURL=chunk-BERBYXFH.js.map
104
+ //# sourceMappingURL=chunk-BMAZLQQ4.js.map
105
+ //# sourceMappingURL=chunk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AA,CAAI,OAAA,EAAS,aAAa,UAAA,EAAY,KAAA,CAAM,MAAM,CAAC,CAAA;AAC/E","file":"chunk-BERBYXFH.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage, SessionMessagePart } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/**\n * theokit#122 — record the turn's thinking block, signature included.\n *\n * The signature is what makes the block replayable: without it the resumed turn is rejected by\n * Anthropic with `400 \"thinking blocks cannot be modified\"`.\n */\nfunction applyThinkingStep(\n assistant: AssistantTurn,\n message: { text: string; signature?: string },\n): void {\n assistant.thinking = message.text;\n if (message.signature !== undefined) assistant.thinkingSignature = message.signature;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") applyThinkingStep(assistant, step.message);\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = {\n type: string;\n text?: string;\n content?: unknown;\n name?: string;\n id?: string;\n toolUseId?: string;\n input?: unknown;\n isError?: boolean;\n};\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/**\n * theokit#146 — the same part, kept as STRUCTURE.\n *\n * `partToText` above is what the model replay wants; a host rendering tool cards needs the call id,\n * the tool name and the arguments, none of which survive `[tool call] NAME`. Both projections are\n * produced from the one reconstructed part, so they cannot drift apart.\n *\n * Returns `undefined` for a part with no display meaning (e.g. an image placeholder the session\n * projection does not model), which the caller filters out.\n */\nfunction partToStructured(p: NarrowPart): SessionMessagePart | undefined {\n if (p.type === \"text\") return { type: \"text\", text: p.text ?? \"\" };\n if (p.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: p.id ?? \"\",\n name: p.name ?? \"\",\n input: (p.input ?? {}) as Record<string, unknown>,\n };\n }\n if (p.type === \"tool_result\") {\n return {\n type: \"tool_result\",\n toolUseId: p.toolUseId ?? \"\",\n // Reconstructed tool results carry either a string or the SE7 content blocks; both are\n // already the session shape, so this narrows `unknown` rather than converting anything.\n content: p.content as string | ReadonlyArray<ToolResultContentBlock>,\n ...(p.isError === true ? { isError: true } : {}),\n };\n }\n return undefined;\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n const parts = m.content\n .map(partToStructured)\n .filter((p): p is SessionMessagePart => p !== undefined);\n return { role, text, parts };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/session/agent-session-store.ts"],"names":[],"mappings":";;;AA+BA,SAAS,cAAA,CACP,OACA,IAAA,EACmB;AACnB,EAAA,OAAO,iBAAA,CAAkB,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA;AAClD;AA8BA,SAAS,iBAAA,CACP,WACA,OAAA,EACM;AACN,EAAA,SAAA,CAAU,WAAW,OAAA,CAAQ,IAAA;AAC7B,EAAA,IAAI,OAAA,CAAQ,SAAA,KAAc,MAAA,EAAW,SAAA,CAAU,oBAAoB,OAAA,CAAQ,SAAA;AAC7E;AAGA,SAAS,aAAa,KAAA,EAAgD;AACpE,EAAA,MAAM,YAA2B,EAAC;AAClC,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,YAAqD,EAAC;AAC5D,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,KAAK,IAAA,KAAS,iBAAA,EAAmB,iBAAA,CAAkB,SAAA,EAAW,KAAK,OAAO,CAAA;AAAA,SAAA,IACrE,KAAK,IAAA,KAAS,kBAAA,EAAoB,SAAA,CAAU,IAAA,GAAO,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAChE,KAAK,IAAA,KAAS,UAAA;AACrB,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,EAAA,EAAI,KAAK,OAAA,CAAQ,MAAA;AAAA,QACjB,IAAA,EAAM,KAAK,OAAA,CAAQ,IAAA;AAAA,QACnB,KAAA,EAAQ,IAAA,CAAK,OAAA,CAAQ,IAAA,IAAgD;AAAC,OACvE,CAAA;AAAA;AAED,MAAA,WAAA,CAAY,IAAA,CAAK;AAAA,QACf,SAAA,EAAW,K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GAAA,EAAK,SAAA,EAAW,KAAA,EAAO,GAAA,CAAI,KAAA,EAAO,CAAA;AACtF,EAAA,UAAA,CAAW,sBAAsB,IAAI,CAAA;AACrC,EAAA,MAAM,KAAA,CAAM,cAAc,GAAA,CAAI,OAAA,EAAS,aAAa,UAAA,EAAY,KAAA,CAAM,MAAM,CAAC,CAAA;AAC/E","file":"chunk-BMAZLQQ4.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage, SessionMessagePart } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/**\n * theokit#122 — record the turn's thinking block, signature included.\n *\n * The signature is what makes the block replayable: without it the resumed turn is rejected by\n * Anthropic with `400 \"thinking blocks cannot be modified\"`.\n */\nfunction applyThinkingStep(\n assistant: AssistantTurn,\n message: { text: string; signature?: string },\n): void {\n assistant.thinking = message.text;\n if (message.signature !== undefined) assistant.thinkingSignature = message.signature;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") applyThinkingStep(assistant, step.message);\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = {\n type: string;\n text?: string;\n content?: unknown;\n name?: string;\n id?: string;\n toolUseId?: string;\n input?: unknown;\n isError?: boolean;\n};\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/**\n * theokit#146 — the same part, kept as STRUCTURE.\n *\n * `partToText` above is what the model replay wants; a host rendering tool cards needs the call id,\n * the tool name and the arguments, none of which survive `[tool call] NAME`. Both projections are\n * produced from the one reconstructed part, so they cannot drift apart.\n *\n * Returns `undefined` for a part with no display meaning (e.g. an image placeholder the session\n * projection does not model), which the caller filters out.\n */\nfunction partToStructured(p: NarrowPart): SessionMessagePart | undefined {\n if (p.type === \"text\") return { type: \"text\", text: p.text ?? \"\" };\n if (p.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: p.id ?? \"\",\n name: p.name ?? \"\",\n input: (p.input ?? {}) as Record<string, unknown>,\n };\n }\n if (p.type === \"tool_result\") {\n return {\n type: \"tool_result\",\n toolUseId: p.toolUseId ?? \"\",\n // Reconstructed tool results carry either a string or the SE7 content blocks; both are\n // already the session shape, so this narrows `unknown` rather than converting anything.\n content: p.content as string | ReadonlyArray<ToolResultContentBlock>,\n ...(p.isError === true ? { isError: true } : {}),\n };\n }\n return undefined;\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n const parts = m.content\n .map(partToStructured)\n .filter((p): p is SessionMessagePart => p !== undefined);\n return { role, text, parts };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
3
+ var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
4
4
  var crypto = require('crypto');
5
5
  var fs = require('fs');
6
6
  var path = require('path');
@@ -13,7 +13,7 @@ function credentialHome(config, env = {}) {
13
13
  function authFilePath(config, env = {}) {
14
14
  return path.join(credentialHome(config, env), config.fileName);
15
15
  }
16
- var CredentialError = class extends chunkLPVIRJVF_cjs.AuthenticationError {
16
+ var CredentialError = class extends chunkK3FW2XZD_cjs.AuthenticationError {
17
17
  // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`
18
18
  // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the
19
19
  // suite was green with the broken assignment because the transpiler strips the type.
@@ -151,5 +151,5 @@ exports.credentialHome = credentialHome;
151
151
  exports.readAuthFile = readAuthFile;
152
152
  exports.readStoredOAuth = readStoredOAuth;
153
153
  exports.writeCredential = writeCredential;
154
- //# sourceMappingURL=chunk-5YKNEMXR.cjs.map
155
- //# sourceMappingURL=chunk-5YKNEMXR.cjs.map
154
+ //# sourceMappingURL=chunk-BVZW2B5V.cjs.map
155
+ //# sourceMappingURL=chunk-BVZW2B5V.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/auth/credential-store.ts"],"names":["join","AuthenticationError","z","statSync","readFile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A,aAAA,EAAgB,IAAI,CAAA,EAAA,EAAM,GAAA,CAAc,OAAO,CAAA,CAAE,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-BVZW2B5V.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { AuthenticationError } from \"../../errors.js\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * Re-exported from `@theokit/sdk/auth`, and therefore PUBLIC, under semver.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/**\n * A credential problem the caller can act on. Never carries the key value.\n *\n * M78 — this used to extend bare `Error`, which quietly disabled classification for the entire auth\n * path: `isTransientError` is `err instanceof TheokitAgentError && err.isRetryable === true`\n * (`errors.ts:443`), so a credential failure could never be judged transient OR permanent. The\n * predicate was not \"forgotten\" downstream — it was unusable there by construction.\n *\n * Extending `AuthenticationError` is ADDITIVE: the class still exists, still reports\n * `name: \"CredentialError\"`, and every existing `instanceof CredentialError` stays true. It only\n * gains ancestors. `AuthenticationError` pins `isRetryable: false`, so gaining the ability to be\n * classified does NOT turn a revoked credential into a retry loop.\n *\n * The single reference does the same thing with one root type: Codex routes every domain failure\n * through `CodexErr` with `is_retryable()` as a method (`protocol/src/error.rs:176`), rather than\n * parallel classes extending the language's `Error`.\n */\nexport class CredentialError extends AuthenticationError {\n // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`\n // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the\n // suite was green with the broken assignment because the transpiler strips the type.\n override readonly name: string = \"CredentialError\";\n}\n\n/**\n * The on-disk store — a discriminated union on `type`. A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nexport function assertSecureModes(dirPath: string, path: string): void {\n // Windows has no POSIX mode bits. `statSync().mode` there is SYNTHETIC — 0666 for any writable\n // entry, whatever the ACLs actually say — so `mode & 0o022` was non-zero for every valid store and\n // this gate refused all of them, which made the credential path unreadable on that platform\n // rather than protected. A check that cannot observe the real permission system must not report a\n // verdict about it; ACL enforcement is a separate mechanism and not one this function can fake.\n if (process.platform === \"win32\") return;\n\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { ConfigurationError } from './chunk-U4UJHOSH.js';
2
- import { diag } from './chunk-5F5NWKPN.js';
1
+ import { ConfigurationError } from './chunk-IDCKSLYH.js';
2
+ import { diag } from './chunk-T7O6K6PX.js';
3
3
  import { mkdir, rename } from 'fs/promises';
4
4
  import { dirname } from 'path';
5
5
 
@@ -162,5 +162,5 @@ async function renameAside(filePath, label) {
162
162
  }
163
163
 
164
164
  export { applyWalWithFallback, containsCjk, isCorruptionError, openSqliteResilient, sanitizeFts5Query };
165
- //# sourceMappingURL=chunk-MSFLYJDY.js.map
166
- //# sourceMappingURL=chunk-MSFLYJDY.js.map
165
+ //# sourceMappingURL=chunk-CQ2TQ32Y.js.map
166
+ //# sourceMappingURL=chunk-CQ2TQ32Y.js.map