@theokit/sdk 4.53.1 → 4.55.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 (694) hide show
  1. package/CHANGELOG.md +1184 -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-D3Xr_-6Z.d.cts} +245 -850
  16. package/dist/{agent-nLqeXKIX.d.cts → agent-DIu6FooJ.d.ts} +245 -850
  17. package/dist/agent-HDEVVUBS.js +52 -0
  18. package/dist/{agent-FFVV4U5N.js.map → agent-HDEVVUBS.js.map} +1 -1
  19. package/dist/agent-R2HOJFZJ.cjs +61 -0
  20. package/dist/{agent-YLAHVHEH.cjs.map → agent-R2HOJFZJ.cjs.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-2BDH744Z.js +15 -0
  38. package/dist/chunk-2BDH744Z.js.map +1 -0
  39. package/dist/{chunk-VGPXHHF3.cjs → chunk-2C72DXQF.cjs} +63 -27
  40. package/dist/chunk-2C72DXQF.cjs.map +1 -0
  41. package/dist/{chunk-4Q4K4WB5.js → chunk-2D34UTDC.js} +20 -4
  42. package/dist/chunk-2D34UTDC.js.map +1 -0
  43. package/dist/{chunk-UFIXH26P.js → chunk-2QKTVKH3.js} +4 -4
  44. package/dist/{chunk-UFIXH26P.js.map → chunk-2QKTVKH3.js.map} +1 -1
  45. package/dist/{chunk-GBBDINFK.js → chunk-3E77SX4H.js} +4 -4
  46. package/dist/{chunk-GBBDINFK.js.map → chunk-3E77SX4H.js.map} +1 -1
  47. package/dist/{chunk-VYHJZVL5.cjs → chunk-3EE6LVWT.cjs} +2 -2
  48. package/dist/chunk-3EE6LVWT.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-FFM3SJTQ.js → chunk-5JLFFPCH.js} +4 -4
  70. package/dist/{chunk-FFM3SJTQ.js.map → chunk-5JLFFPCH.js.map} +1 -1
  71. package/dist/{chunk-34XOCZJO.js → chunk-5PHVENFV.js} +3 -3
  72. package/dist/chunk-5PHVENFV.js.map +1 -0
  73. package/dist/{chunk-BDTVFIPB.cjs → chunk-5UOVYM3P.cjs} +36 -31
  74. package/dist/chunk-5UOVYM3P.cjs.map +1 -0
  75. package/dist/{chunk-VF7X6HDR.cjs → chunk-5USCYPPI.cjs} +15 -15
  76. package/dist/{chunk-VF7X6HDR.cjs.map → chunk-5USCYPPI.cjs.map} +1 -1
  77. package/dist/chunk-6HTXPPHK.cjs +18 -0
  78. package/dist/chunk-6HTXPPHK.cjs.map +1 -0
  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-BFYGJGC5.js → chunk-AQLGBKNT.js} +3 -3
  84. package/dist/chunk-AQLGBKNT.js.map +1 -0
  85. package/dist/{chunk-7W7ZWMLQ.js → chunk-AWO27VRZ.js} +3 -3
  86. package/dist/chunk-AWO27VRZ.js.map +1 -0
  87. package/dist/{chunk-VYCKUKPA.cjs → chunk-B2J4ZMZL.cjs} +3 -2
  88. package/dist/chunk-B2J4ZMZL.cjs.map +1 -0
  89. package/dist/{chunk-BERBYXFH.js → chunk-BMAZLQQ4.js} +3 -3
  90. package/dist/{chunk-BERBYXFH.js.map → chunk-BMAZLQQ4.js.map} +1 -1
  91. package/dist/{chunk-5YKNEMXR.cjs → chunk-BVZW2B5V.cjs} +4 -4
  92. package/dist/chunk-BVZW2B5V.cjs.map +1 -0
  93. package/dist/{chunk-MSFLYJDY.js → chunk-CQ2TQ32Y.js} +4 -4
  94. package/dist/chunk-CQ2TQ32Y.js.map +1 -0
  95. package/dist/{chunk-C5DEO6OI.cjs → chunk-CQGYNZ3K.cjs} +4 -4
  96. package/dist/{chunk-C5DEO6OI.cjs.map → chunk-CQGYNZ3K.cjs.map} +1 -1
  97. package/dist/{chunk-D75S2X6I.cjs → chunk-CTCGWIUD.cjs} +5 -5
  98. package/dist/{chunk-D75S2X6I.cjs.map → chunk-CTCGWIUD.cjs.map} +1 -1
  99. package/dist/{chunk-NZL4BNFQ.js → chunk-CV7XMBHP.js} +4 -4
  100. package/dist/chunk-CV7XMBHP.js.map +1 -0
  101. package/dist/{chunk-SEL2ZQMT.js → chunk-DAPSQZT4.js} +15 -10
  102. package/dist/chunk-DAPSQZT4.js.map +1 -0
  103. package/dist/{chunk-SVO5WPZX.cjs → chunk-DQKERTND.cjs} +11 -11
  104. package/dist/{chunk-SVO5WPZX.cjs.map → chunk-DQKERTND.cjs.map} +1 -1
  105. package/dist/{chunk-N5CR3TJZ.js → chunk-DZBSJX6J.js} +4 -4
  106. package/dist/{chunk-N5CR3TJZ.js.map → chunk-DZBSJX6J.js.map} +1 -1
  107. package/dist/{chunk-RAHSWE5C.cjs → chunk-EI2Q7SJ5.cjs} +12 -12
  108. package/dist/chunk-EI2Q7SJ5.cjs.map +1 -0
  109. package/dist/{chunk-UCFONJBG.js → chunk-EPSICJLZ.js} +2 -2
  110. package/dist/{chunk-UCFONJBG.js.map → chunk-EPSICJLZ.js.map} +1 -1
  111. package/dist/{chunk-3X6PM7DU.cjs → chunk-F3YZMOAU.cjs} +8 -8
  112. package/dist/{chunk-3X6PM7DU.cjs.map → chunk-F3YZMOAU.cjs.map} +1 -1
  113. package/dist/{chunk-F77UENR6.cjs → chunk-F5WMX4EA.cjs} +586 -398
  114. package/dist/chunk-F5WMX4EA.cjs.map +1 -0
  115. package/dist/{chunk-HE4BIAOS.js → chunk-F7AQV62G.js} +5 -4
  116. package/dist/chunk-F7AQV62G.js.map +1 -0
  117. package/dist/{chunk-2RW7K6FN.cjs → chunk-GHX4P3V2.cjs} +2 -2
  118. package/dist/chunk-GHX4P3V2.cjs.map +1 -0
  119. package/dist/{chunk-B6HOIWQ6.js → chunk-GJ6RK75E.js} +5 -5
  120. package/dist/chunk-GJ6RK75E.js.map +1 -0
  121. package/dist/{chunk-FOXKFTVZ.cjs → chunk-GNT35C5U.cjs} +13 -13
  122. package/dist/chunk-GNT35C5U.cjs.map +1 -0
  123. package/dist/{chunk-4NAKHID5.js → chunk-GTKFV7O5.js} +2 -2
  124. package/dist/chunk-GTKFV7O5.js.map +1 -0
  125. package/dist/{chunk-ELKO4ZLR.cjs → chunk-GWC3HADL.cjs} +4 -4
  126. package/dist/{chunk-ELKO4ZLR.cjs.map → chunk-GWC3HADL.cjs.map} +1 -1
  127. package/dist/{chunk-OXNYIMZZ.js → chunk-H73MEMQB.js} +2 -2
  128. package/dist/chunk-H73MEMQB.js.map +1 -0
  129. package/dist/{chunk-E7FJOO4G.cjs → chunk-HJBMA5MB.cjs} +11 -11
  130. package/dist/{chunk-E7FJOO4G.cjs.map → chunk-HJBMA5MB.cjs.map} +1 -1
  131. package/dist/{chunk-2FYEVT2B.cjs → chunk-HLPSLDGL.cjs} +275 -160
  132. package/dist/chunk-HLPSLDGL.cjs.map +1 -0
  133. package/dist/{chunk-VW6M4B3Z.cjs → chunk-HY57ULY2.cjs} +5 -5
  134. package/dist/{chunk-VW6M4B3Z.cjs.map → chunk-HY57ULY2.cjs.map} +1 -1
  135. package/dist/{chunk-CAH3G4IS.js → chunk-HY66GLM6.js} +2 -2
  136. package/dist/chunk-HY66GLM6.js.map +1 -0
  137. package/dist/{chunk-G3JWXOGY.js → chunk-I5BE5M5L.js} +310 -122
  138. package/dist/chunk-I5BE5M5L.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-QBTVATSF.cjs → chunk-ITSSOVOB.cjs} +44 -47
  146. package/dist/chunk-ITSSOVOB.cjs.map +1 -0
  147. package/dist/{chunk-V6HWJQQV.js → chunk-IVNNSANC.js} +27 -30
  148. package/dist/chunk-IVNNSANC.js.map +1 -0
  149. package/dist/{chunk-SZHU7A5B.cjs → chunk-IWBGCBR6.cjs} +4 -4
  150. package/dist/{chunk-SZHU7A5B.cjs.map → chunk-IWBGCBR6.cjs.map} +1 -1
  151. package/dist/{chunk-Q4RESANI.cjs → chunk-J24VJOH3.cjs} +20 -4
  152. package/dist/chunk-J24VJOH3.cjs.map +1 -0
  153. package/dist/{chunk-Y4AXQOT4.cjs → chunk-JHPGF3FP.cjs} +8 -8
  154. package/dist/{chunk-Y4AXQOT4.cjs.map → chunk-JHPGF3FP.cjs.map} +1 -1
  155. package/dist/{chunk-BM6N4KHO.cjs → chunk-JTB5Q42C.cjs} +6 -22
  156. package/dist/chunk-JTB5Q42C.cjs.map +1 -0
  157. package/dist/{chunk-LPVIRJVF.cjs → chunk-K3FW2XZD.cjs} +9 -9
  158. package/dist/{chunk-LPVIRJVF.cjs.map → chunk-K3FW2XZD.cjs.map} +1 -1
  159. package/dist/{chunk-LS3LMQ23.js → chunk-MVAPK2BX.js} +162 -49
  160. package/dist/chunk-MVAPK2BX.js.map +1 -0
  161. package/dist/{chunk-XPR366DL.cjs → chunk-NGESVVJN.cjs} +17 -17
  162. package/dist/chunk-NGESVVJN.cjs.map +1 -0
  163. package/dist/{chunk-VUKQL3L2.cjs → chunk-NIRE5CNO.cjs} +20 -13
  164. package/dist/chunk-NIRE5CNO.cjs.map +1 -0
  165. package/dist/{chunk-VC5ABJXC.js → chunk-NLTVXLGT.js} +3 -3
  166. package/dist/{chunk-VC5ABJXC.js.map → chunk-NLTVXLGT.js.map} +1 -1
  167. package/dist/chunk-NUKRL3I6.cjs +23 -0
  168. package/dist/chunk-NUKRL3I6.cjs.map +1 -0
  169. package/dist/{chunk-R5YZACGK.js → chunk-OC4NTGMN.js} +3 -3
  170. package/dist/{chunk-R5YZACGK.js.map → chunk-OC4NTGMN.js.map} +1 -1
  171. package/dist/{chunk-GOVJO4YE.js → chunk-OHBIUXKM.js} +6 -6
  172. package/dist/chunk-OHBIUXKM.js.map +1 -0
  173. package/dist/{chunk-FPYT5WZP.cjs → chunk-P6A3M6VD.cjs} +10 -10
  174. package/dist/{chunk-FPYT5WZP.cjs.map → chunk-P6A3M6VD.cjs.map} +1 -1
  175. package/dist/{chunk-OKLYRPKL.cjs → chunk-Q47R5E2X.cjs} +8 -8
  176. package/dist/chunk-Q47R5E2X.cjs.map +1 -0
  177. package/dist/{chunk-HSQ5Q3I5.js → chunk-Q4CMI2LP.js} +12 -5
  178. package/dist/chunk-Q4CMI2LP.js.map +1 -0
  179. package/dist/{chunk-2XLKLVVR.js → chunk-Q5EWJPRY.js} +2 -2
  180. package/dist/chunk-Q5EWJPRY.js.map +1 -0
  181. package/dist/{chunk-SK4QLUBK.js → chunk-QARJGQSA.js} +16 -7
  182. package/dist/chunk-QARJGQSA.js.map +1 -0
  183. package/dist/{chunk-CZ2GKKYL.cjs → chunk-QDED6YO6.cjs} +5 -5
  184. package/dist/{chunk-CZ2GKKYL.cjs.map → chunk-QDED6YO6.cjs.map} +1 -1
  185. package/dist/{chunk-VK7MAV65.cjs → chunk-QKLOP4VC.cjs} +2 -2
  186. package/dist/{chunk-VK7MAV65.cjs.map → chunk-QKLOP4VC.cjs.map} +1 -1
  187. package/dist/{chunk-FIOCJYLA.js → chunk-QRSUA2CV.js} +3 -3
  188. package/dist/{chunk-FIOCJYLA.js.map → chunk-QRSUA2CV.js.map} +1 -1
  189. package/dist/{chunk-ZT57WTUJ.cjs → chunk-R3UPQFKK.cjs} +21 -12
  190. package/dist/chunk-R3UPQFKK.cjs.map +1 -0
  191. package/dist/{chunk-X2FR4OIT.js → chunk-R7WIIPUR.js} +2 -2
  192. package/dist/chunk-R7WIIPUR.js.map +1 -0
  193. package/dist/{chunk-RP5HQVLD.js → chunk-RNB4APBZ.js} +30 -7
  194. package/dist/chunk-RNB4APBZ.js.map +1 -0
  195. package/dist/{chunk-GD63JPGC.cjs → chunk-ROYPRJH4.cjs} +9 -9
  196. package/dist/{chunk-GD63JPGC.cjs.map → chunk-ROYPRJH4.cjs.map} +1 -1
  197. package/dist/{chunk-V26QVGUG.js → chunk-RUDY2GTT.js} +59 -23
  198. package/dist/chunk-RUDY2GTT.js.map +1 -0
  199. package/dist/{chunk-JIQRXKTA.cjs → chunk-SKXBJ2NU.cjs} +7 -7
  200. package/dist/chunk-SKXBJ2NU.cjs.map +1 -0
  201. package/dist/{chunk-XROIW6BH.js → chunk-SUKXXLWD.js} +6 -6
  202. package/dist/chunk-SUKXXLWD.js.map +1 -0
  203. package/dist/{chunk-LTSTGCL6.js → chunk-T73NA43R.js} +3 -3
  204. package/dist/{chunk-LTSTGCL6.js.map → chunk-T73NA43R.js.map} +1 -1
  205. package/dist/chunk-T7O6K6PX.js +20 -0
  206. package/dist/chunk-T7O6K6PX.js.map +1 -0
  207. package/dist/{chunk-5F5NWKPN.js → chunk-T7XEKOVW.js} +5 -20
  208. package/dist/chunk-T7XEKOVW.js.map +1 -0
  209. package/dist/{chunk-HAWE74GQ.cjs → chunk-U2AC6JUP.cjs} +8 -8
  210. package/dist/chunk-U2AC6JUP.cjs.map +1 -0
  211. package/dist/{chunk-3WVMJY7F.js → chunk-UC3HT2S4.js} +3 -3
  212. package/dist/{chunk-3WVMJY7F.js.map → chunk-UC3HT2S4.js.map} +1 -1
  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-2D43RD5D.cjs → chunk-V2UUGUY4.cjs} +27 -27
  218. package/dist/chunk-V2UUGUY4.cjs.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-FUJDVF7B.js +22 -0
  250. package/dist/{compact-session-4MNKNMO2.js.map → compact-session-FUJDVF7B.js.map} +1 -1
  251. package/dist/compact-session-LEWF554G.cjs +59 -0
  252. package/dist/{compact-session-EPFBQ46Z.cjs.map → compact-session-LEWF554G.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-BcWmzWzT.d.cts +240 -0
  268. package/dist/cron-De6hzWCF.d.ts +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-BJMJH5BX.js} +9 -8
  319. package/dist/inject-session-BJMJH5BX.js.map +1 -0
  320. package/dist/inject-session-WQGGMCQY.cjs +29 -0
  321. package/dist/inject-session-WQGGMCQY.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/prompt-cache-key.d.ts +1 -0
  332. package/dist/internal/llm/responses.d.ts +67 -1
  333. package/dist/internal/llm/router.d.ts +8 -0
  334. package/dist/internal/llm/types.d.ts +27 -1
  335. package/dist/internal/local-agent/real-local-run-provider.d.ts +8 -3
  336. package/dist/internal/local-agent/real-local-run-tools.d.ts +23 -4
  337. package/dist/internal/mcp/oauth.d.ts +5 -0
  338. package/dist/internal/mcp/token-storage.d.ts +34 -0
  339. package/dist/internal/memory/adapters/index.cjs +12 -11
  340. package/dist/internal/memory/adapters/index.d.cts +3 -1
  341. package/dist/internal/memory/adapters/index.d.ts +3 -1
  342. package/dist/internal/memory/adapters/index.js +9 -8
  343. package/dist/internal/memory/adapters/openai-compatible.d.cts +45 -0
  344. package/dist/internal/memory/adapters/openai-compatible.d.ts +45 -0
  345. package/dist/internal/memory/embedding-cache.d.ts +42 -1
  346. package/dist/internal/memory/escape-like-pattern.d.ts +22 -0
  347. package/dist/internal/memory/sqlite-vec-loader.d.ts +1 -3
  348. package/dist/internal/memory/storage/markdown-store.d.ts +0 -5
  349. package/dist/internal/persistence/cwd-mutex.d.cts +34 -0
  350. package/dist/internal/persistence/cwd-mutex.d.ts +34 -0
  351. package/dist/internal/persistence/exclusive-create.d.cts +31 -0
  352. package/dist/internal/persistence/exclusive-create.d.ts +31 -0
  353. package/dist/internal/persistence/file-lock.d.cts +28 -0
  354. package/dist/internal/persistence/file-lock.d.ts +28 -0
  355. package/dist/internal/persistence/fs-session-store.d.cts +3 -0
  356. package/dist/internal/persistence/fs-session-store.d.ts +3 -0
  357. package/dist/internal/persistence/fts5-sanitize.d.cts +20 -0
  358. package/dist/internal/persistence/fts5-sanitize.d.ts +20 -0
  359. package/dist/internal/persistence/index.cjs +40 -39
  360. package/dist/internal/persistence/index.cjs.map +1 -1
  361. package/dist/internal/persistence/index.d.cts +6 -1
  362. package/dist/internal/persistence/index.d.ts +6 -1
  363. package/dist/internal/persistence/index.js +9 -8
  364. package/dist/internal/persistence/index.js.map +1 -1
  365. package/dist/internal/persistence/paths.d.cts +54 -1
  366. package/dist/internal/persistence/paths.d.ts +54 -1
  367. package/dist/internal/persistence/persistence-schema.d.cts +9 -1
  368. package/dist/internal/persistence/persistence-schema.d.ts +9 -1
  369. package/dist/internal/persistence/schema-version.d.cts +215 -1
  370. package/dist/internal/persistence/schema-version.d.ts +215 -1
  371. package/dist/internal/persistence/session-writer.d.cts +7 -7
  372. package/dist/internal/persistence/session-writer.d.ts +7 -7
  373. package/dist/internal/persistence/sqlite-cas.d.cts +37 -1
  374. package/dist/internal/persistence/sqlite-cas.d.ts +37 -1
  375. package/dist/internal/persistence/sqlite-open.d.cts +14 -0
  376. package/dist/internal/persistence/sqlite-open.d.ts +14 -0
  377. package/dist/internal/persistence/sqlite-wal.d.cts +45 -0
  378. package/dist/internal/persistence/sqlite-wal.d.ts +45 -0
  379. package/dist/internal/persistence/transcript-ops.d.cts +7 -1
  380. package/dist/internal/persistence/transcript-ops.d.ts +7 -1
  381. package/dist/internal/plugins/types.d.cts +1 -1
  382. package/dist/internal/plugins/types.d.ts +1 -1
  383. package/dist/internal/providers/builtin/openai-chatgpt.d.ts +12 -0
  384. package/dist/internal/providers/catalog-loader.d.ts +8 -0
  385. package/dist/internal/providers/catalog-schema.d.ts +55 -0
  386. package/dist/internal/providers/catalog-source-models-dev.d.ts +36 -0
  387. package/dist/internal/runtime/concurrency/delegation-depth.d.ts +27 -0
  388. package/dist/internal/runtime/concurrency/subagent-credentials.d.ts +33 -1
  389. package/dist/internal/runtime/context/context-discovery-runner.d.ts +44 -0
  390. package/dist/internal/runtime/context/context-discovery.d.ts +58 -0
  391. package/dist/internal/runtime/context/context-rules-frontmatter.d.ts +70 -1
  392. package/dist/internal/runtime/fixtures/fixture-mode.d.ts +15 -1
  393. package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +15 -0
  394. package/dist/internal/runtime/registry/agent-registry-store.d.ts +12 -0
  395. package/dist/internal/runtime/registry/live-agent-registry.d.ts +37 -0
  396. package/dist/internal/scorers/llm-judge.d.ts +6 -1
  397. package/dist/internal/security/index.cjs +14 -13
  398. package/dist/internal/security/index.d.cts +4 -1
  399. package/dist/internal/security/index.d.ts +4 -1
  400. package/dist/internal/security/index.js +4 -3
  401. package/dist/internal/security/path-guard.d.cts +46 -0
  402. package/dist/internal/security/path-guard.d.ts +46 -0
  403. package/dist/internal/security/redact.d.cts +71 -0
  404. package/dist/internal/security/redact.d.ts +71 -0
  405. package/dist/internal/session/agent-session.d.ts +15 -4
  406. package/dist/internal/session/session-cache.d.ts +5 -0
  407. package/dist/internal/task/store.d.ts +91 -5
  408. package/dist/internal/telemetry/span-names.d.ts +0 -1
  409. package/dist/internal/telemetry/tracer.d.ts +14 -0
  410. package/dist/job-queue.d.ts +18 -0
  411. package/dist/judge-call-DWHAJATE.js +6 -0
  412. package/dist/{judge-call-MDIPTBJI.js.map → judge-call-DWHAJATE.js.map} +1 -1
  413. package/dist/judge-call-EGYRC2RE.cjs +23 -0
  414. package/dist/{judge-call-G5SGV2M2.cjs.map → judge-call-EGYRC2RE.cjs.map} +1 -1
  415. package/dist/mcp-auth.cjs +41 -25
  416. package/dist/mcp-auth.cjs.map +1 -1
  417. package/dist/mcp-auth.js +34 -18
  418. package/dist/mcp-auth.js.map +1 -1
  419. package/dist/models.cjs +42 -27
  420. package/dist/models.cjs.map +1 -1
  421. package/dist/models.js +25 -10
  422. package/dist/models.js.map +1 -1
  423. package/dist/oauth-transaction-store-BT4GLTLK.cjs +36 -0
  424. package/dist/{oauth-transaction-store-7CKHPQRN.cjs.map → oauth-transaction-store-BT4GLTLK.cjs.map} +1 -1
  425. package/dist/oauth-transaction-store-W52KVHQ4.js +3 -0
  426. package/dist/{oauth-transaction-store-W74I6EFD.js.map → oauth-transaction-store-W52KVHQ4.js.map} +1 -1
  427. package/dist/path-safety.cjs +11 -10
  428. package/dist/path-safety.js +4 -3
  429. package/dist/permission-engine.d.ts +55 -0
  430. package/dist/persistence.cjs +43 -42
  431. package/dist/persistence.cjs.map +1 -1
  432. package/dist/persistence.js +13 -12
  433. package/dist/persistence.js.map +1 -1
  434. package/dist/project.cjs +9 -8
  435. package/dist/project.cjs.map +1 -1
  436. package/dist/project.js +5 -4
  437. package/dist/project.js.map +1 -1
  438. package/dist/providers.cjs +23 -0
  439. package/dist/providers.cjs.map +1 -0
  440. package/dist/providers.d.cts +29 -0
  441. package/dist/providers.d.ts +29 -0
  442. package/dist/providers.js +10 -0
  443. package/dist/providers.js.map +1 -0
  444. package/dist/registry-VFKX7WOP.cjs +47 -0
  445. package/dist/{registry-63ASMXT4.cjs.map → registry-VFKX7WOP.cjs.map} +1 -1
  446. package/dist/registry-VFP3WWQP.js +10 -0
  447. package/dist/{registry-O7FJ2MPM.js.map → registry-VFP3WWQP.js.map} +1 -1
  448. package/dist/retry.cjs +5 -4
  449. package/dist/retry.js +4 -3
  450. package/dist/{run-C8FBAC8o.d.cts → run-BYSHf58D.d.cts} +185 -33
  451. package/dist/{run-C8FBAC8o.d.ts → run-BYSHf58D.d.ts} +185 -33
  452. package/dist/{run-to-completion-JDPIUKSH.js → run-to-completion-DRO77625.js} +3 -3
  453. package/dist/{run-to-completion-JDPIUKSH.js.map → run-to-completion-DRO77625.js.map} +1 -1
  454. package/dist/{run-to-completion-J73I6IY4.cjs → run-to-completion-X4OWM673.cjs} +13 -13
  455. package/dist/{run-to-completion-J73I6IY4.cjs.map → run-to-completion-X4OWM673.cjs.map} +1 -1
  456. package/dist/sandbox/bwrap.d.cts +27 -13
  457. package/dist/sandbox/bwrap.d.ts +27 -13
  458. package/dist/sandbox/index.cjs +20 -19
  459. package/dist/sandbox/index.cjs.map +1 -1
  460. package/dist/sandbox/index.js +5 -4
  461. package/dist/sandbox/index.js.map +1 -1
  462. package/dist/sandbox/linux-sandbox.d.cts +72 -0
  463. package/dist/sandbox/linux-sandbox.d.ts +72 -0
  464. package/dist/sandbox/local-sandbox.d.cts +41 -0
  465. package/dist/sandbox/local-sandbox.d.ts +41 -0
  466. package/dist/sandbox/seccomp.d.cts +6 -0
  467. package/dist/sandbox/seccomp.d.ts +6 -0
  468. package/dist/sandbox/types.d.cts +64 -0
  469. package/dist/sandbox/types.d.ts +64 -0
  470. package/dist/scorers.d.ts +38 -7
  471. package/dist/sdk-agent-D8qJVkuV.d.ts +860 -0
  472. package/dist/sdk-agent-DEoKhA8a.d.cts +860 -0
  473. package/dist/server/auth/errors.d.cts +1 -1
  474. package/dist/server/auth/errors.d.ts +1 -1
  475. package/dist/server/auth/index.cjs +29 -21
  476. package/dist/server/auth/index.cjs.map +1 -1
  477. package/dist/server/auth/index.d.cts +25 -15
  478. package/dist/server/auth/index.d.ts +25 -15
  479. package/dist/server/auth/index.js +15 -7
  480. package/dist/server/auth/index.js.map +1 -1
  481. package/dist/server/auth/oauth-transaction-store.d.cts +13 -1
  482. package/dist/server/auth/oauth-transaction-store.d.ts +13 -1
  483. package/dist/server/auth/orchestrator.d.cts +1 -1
  484. package/dist/server/auth/orchestrator.d.ts +1 -1
  485. package/dist/server/auth/types.d.cts +1 -1
  486. package/dist/server/auth/types.d.ts +1 -1
  487. package/dist/server/auth/validate-return-to.d.cts +21 -11
  488. package/dist/server/auth/validate-return-to.d.ts +21 -11
  489. package/dist/server/errors-envelope.cjs +15 -14
  490. package/dist/server/errors-envelope.cjs.map +1 -1
  491. package/dist/server/errors-envelope.d.cts +4 -4
  492. package/dist/server/errors-envelope.d.ts +4 -4
  493. package/dist/server/errors-envelope.js +4 -3
  494. package/dist/server/errors-envelope.js.map +1 -1
  495. package/dist/session-transcript-AKDYYGXQ.js +6 -0
  496. package/dist/{session-transcript-RAKEK76V.js.map → session-transcript-AKDYYGXQ.js.map} +1 -1
  497. package/dist/session-transcript-JXHFTB7G.cjs +51 -0
  498. package/dist/{session-transcript-DOM3UTXR.cjs.map → session-transcript-JXHFTB7G.cjs.map} +1 -1
  499. package/dist/skills.cjs +8 -7
  500. package/dist/skills.js +6 -5
  501. package/dist/stream-object-BUCF5PHO.cjs +21 -0
  502. package/dist/{stream-object-L3Q7PBMF.cjs.map → stream-object-BUCF5PHO.cjs.map} +1 -1
  503. package/dist/stream-object-L57K4OFS.js +8 -0
  504. package/dist/{stream-object-ZYXWS4B2.js.map → stream-object-L57K4OFS.js.map} +1 -1
  505. package/dist/{stream-to-completion-DFJ5T3BK.js → stream-to-completion-QV5HCL3J.js} +3 -3
  506. package/dist/{stream-to-completion-DFJ5T3BK.js.map → stream-to-completion-QV5HCL3J.js.map} +1 -1
  507. package/dist/{stream-to-completion-H2MHISSK.cjs → stream-to-completion-SRISU5AB.cjs} +10 -10
  508. package/dist/{stream-to-completion-H2MHISSK.cjs.map → stream-to-completion-SRISU5AB.cjs.map} +1 -1
  509. package/dist/subagents-loader-AZIXJ7D3.cjs +16 -0
  510. package/dist/{subagents-loader-VRW73QQT.cjs.map → subagents-loader-AZIXJ7D3.cjs.map} +1 -1
  511. package/dist/subagents-loader-J54ESLDV.js +7 -0
  512. package/dist/{subagents-loader-I56GSKAQ.js.map → subagents-loader-J54ESLDV.js.map} +1 -1
  513. package/dist/subagents-loader.cjs +7 -6
  514. package/dist/subagents-loader.cjs.map +1 -1
  515. package/dist/subagents-loader.d.cts +3 -2
  516. package/dist/subagents-loader.d.ts +3 -2
  517. package/dist/subagents-loader.js +5 -4
  518. package/dist/subagents-loader.js.map +1 -1
  519. package/dist/subscription/define-subscription.d.cts +1 -1
  520. package/dist/subscription/define-subscription.d.ts +1 -1
  521. package/dist/subscription/index.cjs +22 -9
  522. package/dist/subscription/index.cjs.map +1 -1
  523. package/dist/subscription/index.d.cts +1 -1
  524. package/dist/subscription/index.d.ts +1 -1
  525. package/dist/subscription/index.js +21 -8
  526. package/dist/subscription/index.js.map +1 -1
  527. package/dist/subscription/internal/adapter-types.d.cts +1 -1
  528. package/dist/subscription/internal/adapter-types.d.ts +1 -1
  529. package/dist/subscription/internal/server-integration.d.cts +1 -1
  530. package/dist/subscription/internal/server-integration.d.ts +1 -1
  531. package/dist/subscription/internal/sse-encoder.d.cts +1 -1
  532. package/dist/subscription/internal/sse-encoder.d.ts +1 -1
  533. package/dist/subscription/internal/sse-parser.d.cts +1 -1
  534. package/dist/subscription/internal/sse-parser.d.ts +1 -1
  535. package/dist/subscription/internal/subscription-runtime.d.cts +1 -1
  536. package/dist/subscription/internal/subscription-runtime.d.ts +1 -1
  537. package/dist/subscription/internal/ws-adapter-node.d.cts +1 -1
  538. package/dist/subscription/internal/ws-adapter-node.d.ts +1 -1
  539. package/dist/subscription/theokit-subscribe.d.cts +14 -1
  540. package/dist/subscription/theokit-subscribe.d.ts +14 -1
  541. package/dist/subscription/types.d.cts +19 -1
  542. package/dist/subscription/types.d.ts +19 -1
  543. package/dist/task-store.cjs +8 -7
  544. package/dist/task-store.js +5 -4
  545. package/dist/types/agent-prims.d.ts +14 -0
  546. package/dist/types/agent.d.ts +92 -11
  547. package/dist/types/batch.d.ts +7 -1
  548. package/dist/types/conversation.d.ts +18 -5
  549. package/dist/types/goal-events.d.ts +4 -8
  550. package/dist/types/memory-adapter.d.ts +12 -1
  551. package/dist/types/plugin.d.ts +101 -0
  552. package/dist/types/provider-profile.d.ts +32 -0
  553. package/dist/types/run-events.d.ts +28 -1
  554. package/dist/types/run.d.ts +35 -23
  555. package/dist/types/sdk-agent.d.ts +14 -0
  556. package/dist/types/session-record.d.ts +18 -1
  557. package/dist/types/task.d.ts +15 -1
  558. package/dist/types/theokit.d.ts +10 -1
  559. package/dist/types/updates.d.ts +35 -4
  560. package/dist/types/workflow.d.ts +155 -0
  561. package/dist/workflow.cjs +29 -28
  562. package/dist/workflow.d.cts +666 -17
  563. package/dist/workflow.d.ts +666 -17
  564. package/dist/workflow.js +8 -7
  565. package/docs/error-codes.md +215 -0
  566. package/docs/harness-capability-map.md +1358 -0
  567. package/package.json +29 -16
  568. package/bin/init-claude.mjs +0 -68
  569. package/claude-template/AGENTS.md +0 -157
  570. package/claude-template/CLAUDE.md +0 -66
  571. package/claude-template/dot-claude/rules/theokit-conventions.md +0 -32
  572. package/claude-template/dot-claude/settings.json +0 -16
  573. package/claude-template/dot-claude/skills/theokit-agent-core/SKILL.md +0 -209
  574. package/claude-template/dot-claude/skills/theokit-auth/SKILL.md +0 -102
  575. package/claude-template/dot-claude/skills/theokit-budget/SKILL.md +0 -176
  576. package/claude-template/dot-claude/skills/theokit-client/SKILL.md +0 -58
  577. package/claude-template/dot-claude/skills/theokit-compaction/SKILL.md +0 -102
  578. package/claude-template/dot-claude/skills/theokit-concurrency/SKILL.md +0 -68
  579. package/claude-template/dot-claude/skills/theokit-config/SKILL.md +0 -139
  580. package/claude-template/dot-claude/skills/theokit-cron/SKILL.md +0 -148
  581. package/claude-template/dot-claude/skills/theokit-di/SKILL.md +0 -233
  582. package/claude-template/dot-claude/skills/theokit-di-agent/SKILL.md +0 -294
  583. package/claude-template/dot-claude/skills/theokit-errors/SKILL.md +0 -172
  584. package/claude-template/dot-claude/skills/theokit-eval/SKILL.md +0 -179
  585. package/claude-template/dot-claude/skills/theokit-filesystem/SKILL.md +0 -74
  586. package/claude-template/dot-claude/skills/theokit-gateways/SKILL.md +0 -209
  587. package/claude-template/dot-claude/skills/theokit-memory/SKILL.md +0 -176
  588. package/claude-template/dot-claude/skills/theokit-messages/SKILL.md +0 -58
  589. package/claude-template/dot-claude/skills/theokit-models/SKILL.md +0 -79
  590. package/claude-template/dot-claude/skills/theokit-path-safety/SKILL.md +0 -60
  591. package/claude-template/dot-claude/skills/theokit-persistence/SKILL.md +0 -85
  592. package/claude-template/dot-claude/skills/theokit-project/SKILL.md +0 -55
  593. package/claude-template/dot-claude/skills/theokit-retry/SKILL.md +0 -50
  594. package/claude-template/dot-claude/skills/theokit-sandbox/SKILL.md +0 -93
  595. package/claude-template/dot-claude/skills/theokit-sanitize/SKILL.md +0 -66
  596. package/claude-template/dot-claude/skills/theokit-skills/SKILL.md +0 -68
  597. package/claude-template/dot-claude/skills/theokit-streaming/SKILL.md +0 -156
  598. package/claude-template/dot-claude/skills/theokit-subagents/SKILL.md +0 -109
  599. package/claude-template/dot-claude/skills/theokit-subscriptions/SKILL.md +0 -148
  600. package/claude-template/dot-claude/skills/theokit-task-store/SKILL.md +0 -75
  601. package/claude-template/dot-claude/skills/theokit-tools/SKILL.md +0 -170
  602. package/claude-template/dot-claude/skills/theokit-workflows/SKILL.md +0 -218
  603. package/dist/agent-FFVV4U5N.js +0 -50
  604. package/dist/agent-YLAHVHEH.cjs +0 -59
  605. package/dist/agent-session-store-DUGBAX5V.cjs +0 -23
  606. package/dist/agent-session-store-TNCGL5RN.js +0 -6
  607. package/dist/batch-UPKN4SG6.js.map +0 -1
  608. package/dist/batch-ZEFN5SO7.cjs.map +0 -1
  609. package/dist/chunk-2D43RD5D.cjs.map +0 -1
  610. package/dist/chunk-2FYEVT2B.cjs.map +0 -1
  611. package/dist/chunk-2RW7K6FN.cjs.map +0 -1
  612. package/dist/chunk-2XLKLVVR.js.map +0 -1
  613. package/dist/chunk-34XOCZJO.js.map +0 -1
  614. package/dist/chunk-3V7UJLQT.js.map +0 -1
  615. package/dist/chunk-4NAKHID5.js.map +0 -1
  616. package/dist/chunk-4Q4K4WB5.js.map +0 -1
  617. package/dist/chunk-5F5NWKPN.js.map +0 -1
  618. package/dist/chunk-5NBUH3NO.js.map +0 -1
  619. package/dist/chunk-5YKNEMXR.cjs.map +0 -1
  620. package/dist/chunk-7W7ZWMLQ.js.map +0 -1
  621. package/dist/chunk-ADLLFY3H.cjs.map +0 -1
  622. package/dist/chunk-B4YA6BRS.cjs.map +0 -1
  623. package/dist/chunk-B6HOIWQ6.js.map +0 -1
  624. package/dist/chunk-BDTVFIPB.cjs.map +0 -1
  625. package/dist/chunk-BFYGJGC5.js.map +0 -1
  626. package/dist/chunk-BM6N4KHO.cjs.map +0 -1
  627. package/dist/chunk-CAH3G4IS.js.map +0 -1
  628. package/dist/chunk-EZ2YEF4F.cjs.map +0 -1
  629. package/dist/chunk-F77UENR6.cjs.map +0 -1
  630. package/dist/chunk-FOXKFTVZ.cjs.map +0 -1
  631. package/dist/chunk-G3JWXOGY.js.map +0 -1
  632. package/dist/chunk-GOVJO4YE.js.map +0 -1
  633. package/dist/chunk-HAWE74GQ.cjs.map +0 -1
  634. package/dist/chunk-HE4BIAOS.js.map +0 -1
  635. package/dist/chunk-HSQ5Q3I5.js.map +0 -1
  636. package/dist/chunk-JIQRXKTA.cjs.map +0 -1
  637. package/dist/chunk-KSWHTR54.js.map +0 -1
  638. package/dist/chunk-L5YO6PWL.cjs.map +0 -1
  639. package/dist/chunk-LD4MOBFX.js.map +0 -1
  640. package/dist/chunk-LS3LMQ23.js.map +0 -1
  641. package/dist/chunk-MSFLYJDY.js.map +0 -1
  642. package/dist/chunk-NZL4BNFQ.js.map +0 -1
  643. package/dist/chunk-OKLYRPKL.cjs.map +0 -1
  644. package/dist/chunk-OUOXM36O.cjs.map +0 -1
  645. package/dist/chunk-OXNYIMZZ.js.map +0 -1
  646. package/dist/chunk-PBZ7HMBP.js.map +0 -1
  647. package/dist/chunk-PNVDQL5Y.cjs.map +0 -1
  648. package/dist/chunk-Q4RESANI.cjs.map +0 -1
  649. package/dist/chunk-QBTVATSF.cjs.map +0 -1
  650. package/dist/chunk-RAHSWE5C.cjs.map +0 -1
  651. package/dist/chunk-RP5HQVLD.js.map +0 -1
  652. package/dist/chunk-SEL2ZQMT.js.map +0 -1
  653. package/dist/chunk-SK4QLUBK.js.map +0 -1
  654. package/dist/chunk-TTJ54H3E.cjs.map +0 -1
  655. package/dist/chunk-V26QVGUG.js.map +0 -1
  656. package/dist/chunk-V6HWJQQV.js.map +0 -1
  657. package/dist/chunk-VGPXHHF3.cjs.map +0 -1
  658. package/dist/chunk-VUKQL3L2.cjs.map +0 -1
  659. package/dist/chunk-VYCKUKPA.cjs.map +0 -1
  660. package/dist/chunk-VYHJZVL5.cjs.map +0 -1
  661. package/dist/chunk-X2FR4OIT.js.map +0 -1
  662. package/dist/chunk-XPR366DL.cjs.map +0 -1
  663. package/dist/chunk-XROIW6BH.js.map +0 -1
  664. package/dist/chunk-YLQQX5W2.cjs.map +0 -1
  665. package/dist/chunk-ZT57WTUJ.cjs.map +0 -1
  666. package/dist/compact-session-4MNKNMO2.js +0 -21
  667. package/dist/compact-session-EPFBQ46Z.cjs +0 -58
  668. package/dist/context-7USNN6LP.cjs +0 -22
  669. package/dist/context-ENXZNF6J.js +0 -5
  670. package/dist/cron-BMjgFH-_.d.ts +0 -631
  671. package/dist/cron-DFDdCdMM.d.cts +0 -631
  672. package/dist/executor-2Z3LGG3I.cjs.map +0 -1
  673. package/dist/executor-2Z6XJJJG.js.map +0 -1
  674. package/dist/fs-session-store-R5FD3EN6.js +0 -10
  675. package/dist/fs-session-store-VVY2AHWG.cjs +0 -19
  676. package/dist/generate-object-AVXOJK2I.cjs +0 -20
  677. package/dist/generate-object-WQRCXFD2.js +0 -7
  678. package/dist/index-manager-VRU3A2YL.cjs +0 -21
  679. package/dist/index-manager-WS7TVKUW.js +0 -12
  680. package/dist/inject-session-AUQLBDRS.cjs +0 -28
  681. package/dist/inject-session-AUQLBDRS.cjs.map +0 -1
  682. package/dist/inject-session-GMBMJVNZ.js.map +0 -1
  683. package/dist/judge-call-G5SGV2M2.cjs +0 -22
  684. package/dist/judge-call-MDIPTBJI.js +0 -5
  685. package/dist/oauth-transaction-store-7CKHPQRN.cjs +0 -32
  686. package/dist/oauth-transaction-store-W74I6EFD.js +0 -3
  687. package/dist/registry-63ASMXT4.cjs +0 -46
  688. package/dist/registry-O7FJ2MPM.js +0 -9
  689. package/dist/session-transcript-DOM3UTXR.cjs +0 -50
  690. package/dist/session-transcript-RAKEK76V.js +0 -5
  691. package/dist/stream-object-L3Q7PBMF.cjs +0 -20
  692. package/dist/stream-object-ZYXWS4B2.js +0 -7
  693. package/dist/subagents-loader-I56GSKAQ.js +0 -6
  694. package/dist/subagents-loader-VRW73QQT.cjs +0 -15
@@ -2,6 +2,13 @@ import { getAgentFacade } from './chunk-6X6ID4MO.js';
2
2
  import { z } from 'zod';
3
3
  import { AsyncLocalStorage } from 'async_hooks';
4
4
 
5
+ var depthStore = new AsyncLocalStorage();
6
+ async function withDelegationDepth(depth, fn) {
7
+ return depthStore.run(depth, fn);
8
+ }
9
+ function currentDelegationDepth() {
10
+ return depthStore.getStore() ?? 0;
11
+ }
5
12
  var credentialsStore = new AsyncLocalStorage();
6
13
  async function withInheritedSubAgentCredentials(credentials, fn) {
7
14
  return credentialsStore.run(credentials, fn);
@@ -60,7 +67,13 @@ function buildChildCreateOptions(spec, inherited) {
60
67
  tools: spec.tools ?? []
61
68
  };
62
69
  }
63
- async function runChildAgent(spec, input, signal, maxSteps, inherited) {
70
+ async function runChildAgent(spec, input, signal, maxSteps, inherited, depth) {
71
+ return withDelegationDepth(
72
+ depth,
73
+ () => runChildAgentInScope(spec, input, signal, maxSteps, inherited)
74
+ );
75
+ }
76
+ async function runChildAgentInScope(spec, input, signal, maxSteps, inherited) {
64
77
  const agent = await getAgentFacade().create(buildChildCreateOptions(spec, inherited));
65
78
  try {
66
79
  const sendOptions = {
@@ -108,10 +121,9 @@ async function applyDelegationComplete(spec, input, result, iteration) {
108
121
  return completion?.feedback !== void 0 ? result + completion.feedback : result;
109
122
  }
110
123
  function defineSubAgent(spec, _parentDepth = 0) {
111
- const currentDepth = _parentDepth + 1;
112
124
  const maxDepth = spec.maxDelegationDepth ?? 3;
113
- if (currentDepth > maxDepth) {
114
- throw new MaxDelegationDepthError(currentDepth, maxDepth);
125
+ if (_parentDepth + 1 > maxDepth) {
126
+ throw new MaxDelegationDepthError(_parentDepth + 1, maxDepth);
115
127
  }
116
128
  const inputZod = z.object({
117
129
  input: z.string().describe("Task for the subagent")
@@ -132,6 +144,10 @@ function defineSubAgent(spec, _parentDepth = 0) {
132
144
  handler: async (rawInput, ctx) => {
133
145
  const { input: parsed } = inputZod.parse(rawInput);
134
146
  const inherited = currentInheritedSubAgentCredentials();
147
+ const currentDepth = _parentDepth + currentDelegationDepth() + 1;
148
+ if (currentDepth > maxDepth) {
149
+ throw new MaxDelegationDepthError(currentDepth, maxDepth);
150
+ }
135
151
  iteration += 1;
136
152
  const capturedIteration = iteration;
137
153
  const start = await applyDelegationStart(spec, parsed, capturedIteration);
@@ -139,7 +155,14 @@ function defineSubAgent(spec, _parentDepth = 0) {
139
155
  const input = applyMessageFilter(spec, start.input, ctx?.messages);
140
156
  let result;
141
157
  try {
142
- result = await runChildAgent(spec, input, ctx?.signal, start.maxSteps, inherited);
158
+ result = await runChildAgent(
159
+ spec,
160
+ input,
161
+ ctx?.signal,
162
+ start.maxSteps,
163
+ inherited,
164
+ currentDepth
165
+ );
143
166
  } catch (error) {
144
167
  await notifyDelegationError(spec, input, error, capturedIteration);
145
168
  throw error;
@@ -174,5 +197,5 @@ function subAgentToolsFromDefinitions(agents, parentTools) {
174
197
  }
175
198
 
176
199
  export { MaxDelegationDepthError, SubAgent, subAgentToolsFromDefinitions, withInheritedSubAgentCredentials };
177
- //# sourceMappingURL=chunk-RP5HQVLD.js.map
178
- //# sourceMappingURL=chunk-RP5HQVLD.js.map
200
+ //# sourceMappingURL=chunk-RNB4APBZ.js.map
201
+ //# sourceMappingURL=chunk-RNB4APBZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/concurrency/delegation-depth.ts","../src/internal/runtime/concurrency/subagent-credentials.ts","../src/a2a/subagent.ts"],"names":["AsyncLocalStorage"],"mappings":";;;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GAAA,CAAI,OAAA,EAAQ,GAAI,EAAC;AAAA,MAC5D,KAAA,EAAO,CAAC,GAAG,UAAU;AAAA,KACtB,CAAA;AAAA,EACH,CAAC,CAAA;AACH","file":"chunk-RNB4APBZ.js","sourcesContent":["/**\n * #364 — how deep the current delegation chain already is, delivered through the CALL.\n *\n * ## The bug this replaces\n *\n * `maxDelegationDepth` was checked once, at tool-CONSTRUCTION time, against a `_parentDepth`\n * argument that nothing in the SDK ever incremented. Constructing a tool says nothing about how\n * deep it will later be invoked, so with the documented call — `SubAgent.create(spec)` — the test\n * was `1 > maxDepth`, false for every spec that did not ask for depth 0. A subagent whose tools\n * include another subagent recursed unbounded, which is precisely what the guard exists to stop.\n * The only path that ever tripped it was a caller threading the number by hand.\n *\n * ## Why the async scope closes it\n *\n * Depth is a property of the RUN, not of the object. A child's run loop — and therefore every tool\n * it dispatches — executes inside the async continuation of its parent's handler, so a value\n * published on that context is exactly what a nested dispatch needs to read. This is the same seam\n * `subagent-credentials.ts` uses, and for the same reason: what survives every layer that rebuilds\n * a tool object is the call, never the object.\n *\n * It is kept in its own module rather than folded into the credentials payload because depth is a\n * separate concern with a separate lifetime — the credentials scope is opened once per run by the\n * run loop, while depth is opened per delegation by the dispatching tool.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst depthStore = new AsyncLocalStorage<number>();\n\n/**\n * Run `fn` with `depth` published as the delegation depth of the current chain.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so two sibling\n * delegations from the same parent each start from the parent's depth rather than from each\n * other's.\n *\n * @internal\n */\nexport async function withDelegationDepth<T>(depth: number, fn: () => Promise<T>): Promise<T> {\n return depthStore.run(depth, fn);\n}\n\n/**\n * The delegation depth of the current chain — `0` outside any delegation.\n *\n * `0` is the honest default rather than a fallback to some previous chain's value: a subagent\n * dispatched with no parent delegation IS at depth zero.\n *\n * @internal\n */\nexport function currentDelegationDepth(): number {\n return depthStore.getStore() ?? 0;\n}\n","/**\n * theokit#148 — the parent's credentials, delivered through the CALL, not through the tool object.\n *\n * ## The class of bug this replaces\n *\n * Credential inheritance used to ride a property installed on the subagent tool object — first a\n * unique `Symbol()`, then `Symbol.for` after #143. Both are the same shape of contract: \"this\n * object will reach the dispatcher with an extra property intact\". Nothing enforces that, and it\n * broke twice for two different reasons:\n *\n * - **Module duplication** (#142/#143): `tsup splitting: false` inlined a separate copy of the\n * module into each public entry, so the two copies disagreed on a unique `Symbol()` key. Fixed at\n * the build level by M78's `splitting: true`, but the fragile contract remained.\n * - **Object normalization** (#148): any layer that rebuilds the tool from its known fields drops\n * the property. `@theokit/agents`' `toCompiledTool` does exactly that, and had to add an explicit\n * `Object.getOwnPropertySymbols` copy loop to compensate — a band-aid the SDK's contract forced\n * onto a consumer. A named field would have been dropped by the same four-field rebuild, which is\n * why \"make it a typed field\" alone does not close this.\n *\n * ## Why the async scope closes it\n *\n * What survives a rebuild is not the object — it is the CALL. A normalizing wrapper builds a new\n * object but still invokes the original handler, inside the parent run's async context. So\n * credentials published on that context reach the handler regardless of what the tool object looks\n * like by then. There is no property left for a layer to drop.\n *\n * It also fixes a defect the per-object slot could not: credentials were stored per tool INSTANCE,\n * so one subagent tool shared by two agents got last-writer-wins. The scope is per run.\n *\n * Nothing is exposed to third-party tool code: the store is module-private, credentials never touch\n * a handler's `ctx`, and `currentInheritedSubAgentCredentials` is `@internal`.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport type { Plugin } from \"../../plugins/types.js\";\n\n/**\n * Credentials a parent agent hands down to its subagent tools so the child inherits the parent's\n * auth (and, absent an explicit `spec.model`, its model).\n *\n * Declared here rather than in `a2a/subagent.ts` so the delivery mechanism owns the payload shape\n * and the dependency runs one way (`a2a/subagent` -> this module). `a2a/subagent.ts` briefly\n * re-exported it \"for back-compat\"; knip proved there was no back-compat surface to preserve — the\n * type was never in the public barrel nor the exports map — so the re-export was deleted.\n *\n * Emitted rather than erased: `a2a/subagent.d.ts` imports it by name, and that entry IS published,\n * so erasing this declaration ships a `.d.ts` that does not compile. Not being in the exports map\n * is what keeps it out of the semver contract; erasure is not what does that.\n */\nexport interface InheritedCredentials {\n readonly apiKey?: string;\n readonly model?: ModelSelection;\n /**\n * The parent's shell-sandbox posture (`local.sandboxOptions.enabled`), handed down so a delegated\n * child of a sandboxed parent stays sandboxed unless its role explicitly opts out. Without this a\n * child ran unsandboxed whenever its role omitted `sandbox` — a default-open the sandbox wiring\n * exists to prevent.\n */\n readonly sandbox?: boolean;\n /**\n * #55 — the parent's code-registered plugins (e.g. a `PermissionPlugin`) handed down so the child\n * runs under the SAME policy. Without this, a delegated child's inner tool calls escape the\n * parent's argument-level permission gate. First-party delegation path only — never exposed to\n * third-party tool `ctx`.\n */\n readonly plugins?: readonly Plugin[];\n}\n\nconst credentialsStore = new AsyncLocalStorage<InheritedCredentials>();\n\n/**\n * Run `fn` with `credentials` published as the delegation credentials of the current run.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so a delegated child that\n * itself delegates hands down ITS credentials, not its parent's.\n *\n * @internal\n */\nexport async function withInheritedSubAgentCredentials<T>(\n credentials: InheritedCredentials,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialsStore.run(credentials, fn);\n}\n\n/**\n * The delegation credentials of the current run, or `undefined` outside a run scope.\n *\n * `undefined` is deliberately NOT a fallback to some previous run's value: a subagent dispatched\n * with no parent context must create its child without an inherited key rather than reuse a\n * credential that belonged to someone else.\n *\n * @internal\n */\nexport function currentInheritedSubAgentCredentials(): InheritedCredentials | undefined {\n return credentialsStore.getStore();\n}\n","/**\n * Subagent delegation — declarative child agent invocable as a tool.\n *\n * Per ADR D2: `defineSubAgent(spec)` returns a `CustomTool` that, when\n * invoked by the LLM, creates a child agent and sends the input as a\n * message. EC-2: delegation depth is tracked across the RUN (#364) — each\n * delegation publishes its depth on the async scope its child executes in, so a\n * subagent that delegates to a subagent is bounded by `maxDelegationDepth`\n * without the caller threading a counter by hand.\n *\n * SE10 — the handler forwards the parent run's `AbortSignal` to the child.\n * SE11 — optional `onDelegationStart` / `onDelegationComplete` lifecycle hooks\n * let the caller reject, rewrite, observe, or annotate a delegation.\n *\n * @public\n */\n\nimport { z } from \"zod\";\nimport {\n currentDelegationDepth,\n withDelegationDepth,\n} from \"../internal/runtime/concurrency/delegation-depth.js\";\nimport {\n currentInheritedSubAgentCredentials,\n type InheritedCredentials,\n} from \"../internal/runtime/concurrency/subagent-credentials.js\";\nimport { getAgentFacade } from \"../internal/runtime/registry/agent-factory-registry.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n CustomTool,\n ToolContextMessage,\n} from \"../types/agent.js\";\nimport type { ModelSelection } from \"../types/agent-prims.js\";\nimport type { Run } from \"../types/run.js\";\n\n/** Arguments passed to {@link SubAgentSpec.messageFilter} (SE12). */\nexport interface MessageFilterArgs {\n /** The supervisor transcript (read-only text projection) available to this delegation. */\n messages: readonly ToolContextMessage[];\n /** The prompt about to be delegated (after any `onDelegationStart` rewrite). */\n input: string;\n /** The subagent's name. */\n name: string;\n}\n\n/** Context passed to {@link SubAgentSpec.onDelegationStart} before the child runs. */\nexport interface DelegationStartContext {\n input: string;\n name: string;\n /**\n * SE15 — 1-based count of times THIS subagent tool has been invoked (a\n * per-`defineSubAgent`-instance counter). Incremented before this hook runs;\n * a rejected delegation still counts. Enables reject-after-N patterns.\n */\n iteration: number;\n}\n\n/**\n * Decision returned from {@link SubAgentSpec.onDelegationStart}. Discriminated on\n * `proceed` so a rejection (`proceed: false` + `rejectionReason`) and an approval\n * (`modifiedInput`) cannot be mixed into one nonsensical object.\n */\nexport type DelegationStartDecision =\n | { proceed: false; rejectionReason?: string }\n | {\n proceed?: true;\n modifiedInput?: string;\n /** SE13 — cap the child's iteration count (forwarded as `SendOptions.maxIterations`). */\n modifiedMaxSteps?: number;\n };\n\n/** Context passed to {@link SubAgentSpec.onDelegationComplete} after the child settles. */\nexport interface DelegationCompleteContext {\n input: string;\n name: string;\n /** The child's text result (present on success). */\n result?: string;\n /** The error the child threw (present on failure); the error is still re-thrown. */\n error?: unknown;\n /** SE15 — the same 1-based iteration this delegation's `onDelegationStart` saw. */\n iteration: number;\n}\n\n/**\n * The return of a delegation hook: a decision, a promise of one, or nothing —\n * `void` lets a side-effect-only callback (`(ctx) => { log(ctx) }`) type-check,\n * which is the common case (mirrors a peer framework's `async ctx => { ... }` hooks).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: `void` is the idiomatic return for an optional-return callback; the rule false-positives on callback return unions.\ntype DelegationHookResult<T> = T | void | Promise<T | void>;\n\n/** Decision returned from {@link SubAgentSpec.onDelegationComplete}. */\nexport interface DelegationCompleteDecision {\n /** Appended to the child's result string. */\n feedback?: string;\n}\n\n/**\n * The declaration of a delegating child agent, handed to `SubAgent.create(spec)`.\n *\n * `name`, `description` and `instructions` are the only required fields: the first\n * two become the tool the supervisor's model sees, the third becomes the child's\n * system prompt. Everything else narrows what the child inherits.\n *\n * const research = SubAgent.create({\n * name: \"research\",\n * description: \"Look a fact up\",\n * instructions: \"You answer with one sentence.\",\n * });\n * const agent = await Agent.create({ tools: [research] });\n *\n * The tool's own input schema is fixed — one required string property, `input`.\n * It is not derived from this spec and cannot be widened here.\n *\n * What the child inherits from the parent AT DISPATCH TIME, not from this object:\n * the API key, the model (unless `model` is set), the parent's plugins, and the\n * parent's sandbox posture (unless `sandbox` is set). An absent `sandbox` inherits;\n * an explicit `sandbox: false` turns confinement OFF for a child of a confined\n * parent, which is not the same thing.\n *\n * How it fails: the child's failure is re-thrown to the supervisor as a tool error\n * — a run ending in `status: \"error\"` becomes\n * `subagent \"<name>\" run failed: <cause>`. `onDelegationStart` and `messageFilter`\n * propagate their own throws; only a throw from `onDelegationComplete` ON THE\n * ERROR PATH is suppressed, so it cannot mask the real cause.\n *\n * Traps:\n * - `model` as a bare string drops reasoning parameters. Pass the\n * {@link ModelSelection} object form when the child needs `params`.\n * - `maxDelegationDepth` (default 3) bounds the delegation CHAIN, counted at\n * dispatch across the run (#364) — the depth is not something you thread. The\n * `parentDepth` argument of `SubAgent.create` still offsets it, for a supervisor\n * that wants a lower ceiling than the chain it sits in.\n * - Context isolation is the DEFAULT. Without `messageFilter` the child sees only\n * the delegated string; without `includeToolResults` the supervisor gets only\n * the child's final text.\n */\nexport interface SubAgentSpec {\n name: string;\n description: string;\n instructions: string;\n /**\n * A bare id string (back-compat) OR a full {@link ModelSelection} carrying\n * `params` (e.g. `[{ id: \"thinking\", value: \"low\" }]` for reasoning effort). The\n * object form is required for per-subagent reasoning effort to survive to the child\n * — the pre-M33 path took only `.id` and dropped params.\n */\n model?: string | ModelSelection;\n tools?: CustomTool[];\n /** Per-subagent shell sandbox toggle (M33). `true` ⇒ child `local.sandboxOptions.enabled`. */\n sandbox?: boolean;\n /**\n * Maximum length of the delegation CHAIN rooted at this tool, counted at dispatch\n * (default 3). Depth 1 is this subagent; a subagent it delegates to is depth 2.\n * Exceeding it throws {@link MaxDelegationDepthError} from the tool handler.\n */\n maxDelegationDepth?: number;\n /**\n * SE11 — called before the supervisor delegates. Return `{ proceed: false }`\n * to reject (the child never runs and `rejectionReason` becomes the tool\n * result), or `{ modifiedInput }` to rewrite the delegated prompt. A throwing\n * hook surfaces (never silently swallowed).\n */\n onDelegationStart?: (\n ctx: DelegationStartContext,\n ) => DelegationHookResult<DelegationStartDecision>;\n /**\n * SE11 — called after the delegation settles. On success `ctx.result` is set\n * and an optional `{ feedback }` is appended to it. On failure `ctx.error` is\n * set and the original error is ALWAYS re-thrown after this hook runs — a throw\n * from this hook on the error path is suppressed so it cannot mask the\n * delegation's real failure (on the success path a throw does propagate).\n */\n onDelegationComplete?: (\n ctx: DelegationCompleteContext,\n ) => DelegationHookResult<DelegationCompleteDecision>;\n /**\n * SE12 — opt-in parent-context forwarding. When set, the supervisor transcript\n * (`ctx.messages`, a read-only text projection) is passed to this filter and the\n * returned subset is forwarded to the child as a role-tagged context preamble\n * prepended to the delegated input. When ABSENT the child runs input-only —\n * memory isolation stays the default. A filter returning `[]` forwards nothing.\n * A throwing filter propagates (fail-fast, never swallowed — same contract as\n * `onDelegationStart`); the delegation surfaces as a tool error.\n */\n messageFilter?: (args: MessageFilterArgs) => readonly ToolContextMessage[];\n /**\n * SE14 — opt-in subagent result-context control. When `true`, the child's\n * completed tool-call results (name + result) are appended to the delegation\n * payload returned to the supervisor, inside a `<subagent-tool-results>` block.\n * When absent/`false` the delegation returns the child's final text only —\n * text-only stays the default (a peer framework's scoped posture). See ADR 0006.\n */\n includeToolResults?: boolean;\n}\n\n/**\n * Raised by `SubAgent.create(spec, parentDepth)` when `parentDepth + 1` exceeds\n * `spec.maxDelegationDepth` (default 3). Carries `currentDepth`, `maxDepth` and a\n * stable `code: \"max_delegation_depth\"`.\n *\n * Thrown from the subagent tool's handler when a delegation would exceed\n * `maxDelegationDepth` (default 3), so it surfaces as the tool call's failure —\n * catching it around the dispatching `agent.send()` works.\n *\n * Also thrown eagerly at TOOL-CONSTRUCTION time when a caller threads its own\n * `parentDepth` that is already past the limit; such a tool could never be\n * dispatched, so refusing to build it fails earlier and clearer.\n *\n * Before #364 the construction-time check was the ONLY one, against a depth\n * nothing in the SDK incremented — so under the documented `SubAgent.create(spec)`\n * call this error could not fire at all and nested delegation was unbounded. The\n * chain length now travels with the run (`internal/runtime/concurrency/delegation-depth.ts`),\n * and a caller-threaded `parentDepth` still adds to it.\n */\nexport class MaxDelegationDepthError extends Error {\n readonly code = \"max_delegation_depth\" as const;\n constructor(\n public readonly currentDepth: number,\n public readonly maxDepth: number,\n ) {\n super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`);\n this.name = \"MaxDelegationDepthError\";\n }\n}\n\n/**\n * Run the `onDelegationStart` hook; returns either a rejection or the (possibly\n * rewritten) input plus the optional SE13 `maxSteps` cap.\n */\nasync function applyDelegationStart(\n spec: SubAgentSpec,\n input: string,\n iteration: number,\n): Promise<{ reject: string } | { input: string; maxSteps?: number }> {\n if (spec.onDelegationStart === undefined) return { input };\n const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });\n if (decision === undefined) return { input };\n if (decision.proceed === false)\n return { reject: decision.rejectionReason ?? \"(delegation rejected)\" };\n return {\n input: decision.modifiedInput ?? input,\n ...(decision.modifiedMaxSteps !== undefined ? { maxSteps: decision.modifiedMaxSteps } : {}),\n };\n}\n\n/**\n * SE14 — replay the child run's stream (a safe post-`wait()` idiom — the run buffers\n * events, `stream()` replays them) and collect every completed tool-call result into\n * a delimited block. Returns `\"\"` when the child ran no completed tool calls. See ADR 0006.\n */\nasync function collectChildToolResults(run: Run): Promise<string> {\n const lines: string[] = [];\n for await (const event of run.stream()) {\n if (event.type === \"tool_call\" && event.status === \"completed\") {\n const rendered =\n typeof event.result === \"string\" ? event.result : JSON.stringify(event.result ?? null);\n lines.push(`${event.name}: ${rendered}`);\n }\n }\n if (lines.length === 0) return \"\";\n return `\\n\\n<subagent-tool-results>\\n${lines.join(\"\\n\")}\\n</subagent-tool-results>`;\n}\n\n/**\n * Build the child agent's `Agent.create` options: the child inherits the parent's\n * apiKey (else `Agent.create` throws \"Missing API key\"), its model (unless the spec\n * overrides it), and — #55 — the parent's plugins (permission gate/guards) so the\n * child's inner tool calls run under the same policy.\n */\nexport function buildChildCreateOptions(\n spec: SubAgentSpec,\n inherited: InheritedCredentials | undefined,\n): AgentOptions {\n // M33 — carry the WHOLE model (a bare id becomes `{ id }`; a ModelSelection with\n // `params` keeps its reasoning effort). The pre-M33 path wrapped `spec.model` as\n // `{ id: spec.model }`, which only worked because spec.model was a string and\n // silently dropped reasoning params.\n const model: string | ModelSelection | undefined =\n spec.model !== undefined\n ? typeof spec.model === \"string\"\n ? { id: spec.model }\n : spec.model\n : inherited?.model;\n // M33 — the role's own `sandbox` wins; when it omits the field, inherit the parent's posture. A role's\n // explicit `sandbox: false` therefore confines-OFF a child of a sandboxed parent (distinct from absent).\n const sandbox = spec.sandbox ?? inherited?.sandbox;\n return {\n ...(inherited?.apiKey !== undefined ? { apiKey: inherited.apiKey } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(sandbox !== undefined ? { local: { sandboxOptions: { enabled: sandbox } } } : {}),\n ...(inherited?.plugins !== undefined ? { plugins: inherited.plugins } : {}),\n systemPrompt: spec.instructions,\n tools: spec.tools ?? [],\n };\n}\n\n/**\n * Create the transient child agent and send the input, composing every forwarded\n * `SendOptions` onto ONE `send` call — SE10 `signal` + SE13 `maxIterations`. Absent\n * every option ⇒ the pre-SE10 single-arg `send(input)` shape. SE14 — when\n * `includeToolResults` is set, append the child's completed tool results. Dispose in `finally`.\n */\nasync function runChildAgent(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n depth: number,\n): Promise<string> {\n // #364 — publish THIS delegation's depth for the whole child run. The child's loop, and every\n // tool it dispatches, runs inside this scope, so a nested subagent reads the real chain length\n // instead of the 0 every construction-time check saw.\n return withDelegationDepth(depth, () =>\n runChildAgentInScope(spec, input, signal, maxSteps, inherited),\n );\n}\n\nasync function runChildAgentInScope(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n): Promise<string> {\n // SE45 cycle 3 — use the registered Agent facade via the DIP seam\n // (agent-factory-registry) instead of a dynamic `import(\"../agent.js\")`.\n // This removes the last madge cycle (a2a/subagent -> agent -> ... -> real-local-run-tools\n // -> a2a/subagent): the facade registers itself at module-init via setAgentFacade,\n // so subagent depends only on the registry port, never on the facade module.\n const agent = await getAgentFacade().create(buildChildCreateOptions(spec, inherited));\n try {\n const sendOptions: {\n signal?: AbortSignal;\n maxIterations?: number;\n origin?: import(\"../types/run.js\").MessageOrigin;\n } = {\n ...(signal !== undefined ? { signal } : {}),\n ...(maxSteps !== undefined ? { maxIterations: maxSteps } : {}),\n // SE3 — a delegated child's turn is initiated by the coordinating parent.\n origin: { kind: \"coordinator\" },\n };\n const run = await agent.send(input, sendOptions);\n const result = await run.wait();\n // Fail-fast, don't swallow (Rule 8): a child that ended in error must surface — otherwise a real\n // failure (e.g. `provider_unresolved`) is hidden behind \"(no response)\" and the parent loops on it.\n if (result.status === \"error\") {\n const cause = (result as { error?: { message?: string } }).error;\n throw new Error(\n `subagent \"${spec.name}\" run failed: ${cause?.message ?? \"unknown error\"}`,\n cause !== undefined ? { cause } : undefined,\n );\n }\n const text = result.result ?? \"(no response)\";\n // SE14 — text-only by default; opt-in appends the child's tool results.\n return spec.includeToolResults === true ? text + (await collectChildToolResults(run)) : text;\n } finally {\n agent.dispose();\n }\n}\n\n/**\n * Best-effort error-path notification: run `onDelegationComplete` with the child's\n * error so the caller can observe the failure. The observer's own throw (sync or\n * async) is suppressed here so it cannot mask the delegation's real error, which the\n * handler re-throws next.\n */\nasync function notifyDelegationError(\n spec: SubAgentSpec,\n input: string,\n error: unknown,\n iteration: number,\n): Promise<void> {\n if (spec.onDelegationComplete === undefined) return;\n try {\n await spec.onDelegationComplete({ input, name: spec.name, error, iteration });\n } catch {\n // Subordinate to `error`; the child's real cause wins.\n }\n}\n\n/**\n * SE12 — apply `messageFilter` (if set) and prepend the filtered supervisor\n * transcript to the delegated input as a role-tagged context preamble. Absent\n * filter OR no messages OR an empty filtered subset ⇒ the original input\n * (isolation-by-default preserved).\n */\nfunction applyMessageFilter(\n spec: SubAgentSpec,\n input: string,\n messages: readonly ToolContextMessage[] | undefined,\n): string {\n if (spec.messageFilter === undefined || messages === undefined) return input;\n const filtered = spec.messageFilter({ messages, input, name: spec.name });\n if (filtered.length === 0) return input;\n const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join(\"\\n\");\n return `Prior conversation:\\n${preamble}\\n\\nTask:\\n${input}`;\n}\n\n/** Run the success-path `onDelegationComplete` hook; appends its `feedback` to the result. */\nasync function applyDelegationComplete(\n spec: SubAgentSpec,\n input: string,\n result: string,\n iteration: number,\n): Promise<string> {\n if (spec.onDelegationComplete === undefined) return result;\n const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });\n return completion?.feedback !== undefined ? result + completion.feedback : result;\n}\n\nfunction defineSubAgent(spec: SubAgentSpec, _parentDepth = 0): CustomTool {\n const maxDepth = spec.maxDelegationDepth ?? 3;\n\n // A caller that threads its own depth still gets the eager failure it always got: a spec that is\n // already too deep to ever be dispatchable is worth refusing at construction. What this check\n // CANNOT see is the runtime chain — constructing a tool says nothing about how deep it will later\n // be invoked — which is why the guard that actually bounds recursion lives at dispatch (#364).\n if (_parentDepth + 1 > maxDepth) {\n throw new MaxDelegationDepthError(_parentDepth + 1, maxDepth);\n }\n\n // Zod for RUNTIME validation of the tool_use input …\n const inputZod = z.object({\n input: z.string().describe(\"Task for the subagent\"),\n });\n // … and a real Draft-7 JSON Schema for the LLM. `CustomTool.inputSchema` is sent\n // to the model verbatim; a raw Zod object would serialize to garbage, so the\n // model emits malformed input that fails `inputZod.parse` and the delegation\n // never runs (the previous bug — the schema and the validator are now distinct).\n const inputSchema: Record<string, unknown> = {\n type: \"object\",\n properties: {\n input: { type: \"string\", description: \"Task for the subagent\" },\n },\n required: [\"input\"],\n additionalProperties: false,\n };\n\n // SE15 — per-instance delegation counter, surfaced as `iteration` on the hook\n // contexts. Incremented once per handler invocation before onDelegationStart.\n let iteration = 0;\n\n const tool: CustomTool = {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (\n rawInput: Record<string, unknown>,\n ctx?: {\n signal?: AbortSignal;\n context?: unknown;\n messages?: readonly ToolContextMessage[];\n },\n ): Promise<string> => {\n const { input: parsed } = inputZod.parse(rawInput);\n // theokit#148 — read the parent's credentials from the RUN's async scope, at dispatch time.\n // They used to be stashed on this tool object by the runtime, which meant any layer that\n // rebuilt the object (e.g. `@theokit/agents`' `toCompiledTool`) silently dropped them and the\n // child failed with `provider_unresolved`. The scope travels with the call, so nothing about\n // the object's shape matters — and two concurrent runs sharing one tool each read their own.\n const inherited = currentInheritedSubAgentCredentials();\n // #364 — the real bound. `currentDelegationDepth()` is the length of the chain that led here,\n // published by each ancestor's `runChildAgent`; a caller-threaded `_parentDepth` still adds to\n // it, so the pre-#364 hand-threaded behaviour is unchanged when the ambient depth is 0.\n const currentDepth = _parentDepth + currentDelegationDepth() + 1;\n if (currentDepth > maxDepth) {\n throw new MaxDelegationDepthError(currentDepth, maxDepth);\n }\n iteration += 1; // SE15 — before onDelegationStart; a rejected delegation still counts.\n // Pin THIS invocation's iteration before any await so a concurrent invocation\n // bumping the shared counter cannot change the value onDelegationComplete /\n // notifyDelegationError observe — they see the same iteration onDelegationStart did.\n const capturedIteration = iteration;\n\n const start = await applyDelegationStart(spec, parsed, capturedIteration);\n if (\"reject\" in start) return start.reject;\n // SE12 — opt-in: forward the filtered supervisor transcript as a preamble.\n const input = applyMessageFilter(spec, start.input, ctx?.messages);\n\n let result: string;\n try {\n // SE13 — apply the optional onDelegationStart maxSteps cap on the child send.\n result = await runChildAgent(\n spec,\n input,\n ctx?.signal,\n start.maxSteps,\n inherited,\n currentDepth,\n );\n } catch (error) {\n // SE11 — notify the completion hook of the failure (best-effort observer),\n // then re-throw the ORIGINAL error (Rule 8: never swallow the delegation's\n // own failure).\n await notifyDelegationError(spec, input, error, capturedIteration);\n throw error;\n }\n return applyDelegationComplete(spec, input, result, capturedIteration);\n },\n };\n\n // theokit#148 — nothing is installed on the tool. The credentials arrive through the run's async\n // scope (see `internal/runtime/concurrency/subagent-credentials.ts`), so there is no extra\n // property for a normalizing layer to drop.\n return tool;\n}\n\n/** SE36 — `SubAgent.create` replaces `defineSubAgent` (ADR 0015). @public */\nexport class SubAgent {\n private constructor() {}\n static create(spec: SubAgentSpec, parentDepth = 0): CustomTool {\n return defineSubAgent(spec, parentDepth);\n }\n}\n\n/**\n * Convert a parent's declarative `agents` map ({@link AgentDefinition} per key)\n * into delegation tools for the LOCAL runtime — the counterpart of the\n * cloud/fixture subagent wiring. Each child inherits the parent's `apiKey`/model\n * from the CALL, not from the tool object: `inheritSubAgentCredentials` used to\n * attach them to the tool, and any layer that rebuilt that object dropped them —\n * including the SDK's own rebuild (theokit#148). Credentials now ride the\n * dispatch, so a rebuilt tool cannot lose them. `def.model` overrides the model\n * (`\"inherit\"` keeps the parent's), and `def.tools` scopes the child to that\n * subset of the parent's tools (absent → the parent's full toolset, per the\n * `AgentDefinition.tools` contract).\n *\n * M33 — per-subagent `model` (with reasoning `params`) and `sandbox` are now wired\n * into local delegation: each is carried onto the {@link SubAgentSpec} and applied to\n * the child in {@link buildChildCreateOptions}. `\"inherit\"` (or an absent field) keeps\n * the parent's value. Per-subagent `mcp` is rejected at load (see subagents-loader) —\n * resolving server names→config on the local path is a follow-up.\n *\n * @internal\n */\nexport function subAgentToolsFromDefinitions(\n agents: Record<string, AgentDefinition>,\n parentTools: readonly CustomTool[],\n): CustomTool[] {\n return Object.entries(agents).map(([name, def]) => {\n const whitelist =\n Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : undefined;\n const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;\n return defineSubAgent({\n name,\n description: def.description,\n instructions: def.prompt,\n // Carry the FULL ModelSelection (id + reasoning params), not just the id, so\n // per-subagent reasoning effort survives to buildChildCreateOptions.\n ...(def.model !== undefined && def.model !== \"inherit\" ? { model: def.model } : {}),\n ...(def.sandbox !== undefined ? { sandbox: def.sandbox } : {}),\n tools: [...childTools],\n });\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkCZ2GKKYL_cjs = require('./chunk-CZ2GKKYL.cjs');
3
+ var chunkQDED6YO6_cjs = require('./chunk-QDED6YO6.cjs');
4
4
 
5
5
  // src/stream-object.ts
6
6
  var StreamObjectError = class extends Error {
@@ -14,19 +14,19 @@ var StreamObjectError = class extends Error {
14
14
  }
15
15
  };
16
16
  async function* streamObjectImpl(options, deps) {
17
- const { jsonSchema, maxRetries, initialUsage } = chunkCZ2GKKYL_cjs.setupStructuredOutput(
17
+ const { jsonSchema, maxRetries, initialUsage } = chunkQDED6YO6_cjs.setupStructuredOutput(
18
18
  options.schema,
19
19
  options.maxRetries
20
20
  );
21
21
  let capturedRaw;
22
22
  let lastUsage = initialUsage;
23
- const outputTool = chunkCZ2GKKYL_cjs.makeOutputTool(jsonSchema, (input) => {
23
+ const outputTool = chunkQDED6YO6_cjs.makeOutputTool(jsonSchema, (input) => {
24
24
  if (capturedRaw === void 0) {
25
25
  capturedRaw = input;
26
26
  }
27
27
  return JSON.stringify({ ok: true });
28
28
  });
29
- const agentOptions = chunkCZ2GKKYL_cjs.buildTransientAgentOptions({
29
+ const agentOptions = chunkQDED6YO6_cjs.buildTransientAgentOptions({
30
30
  model: options.model,
31
31
  local: options.local,
32
32
  outputTool,
@@ -35,7 +35,7 @@ async function* streamObjectImpl(options, deps) {
35
35
  ...options.providers !== void 0 ? { providers: options.providers } : {}
36
36
  });
37
37
  const agent = await deps.create(agentOptions);
38
- const userMessage = chunkCZ2GKKYL_cjs.buildToolPrompt(options.prompt);
38
+ const userMessage = chunkQDED6YO6_cjs.buildToolPrompt(options.prompt);
39
39
  try {
40
40
  let lastParseError;
41
41
  let attemptCounter = 0;
@@ -61,7 +61,7 @@ async function* streamObjectImpl(options, deps) {
61
61
  }
62
62
  }
63
63
  const result = await run.wait();
64
- lastUsage = chunkCZ2GKKYL_cjs.extractUsage(result);
64
+ lastUsage = chunkQDED6YO6_cjs.extractUsage(result);
65
65
  if (capturedRaw === void 0) {
66
66
  if (result.status === "error" && result.error !== void 0) {
67
67
  throw new StreamObjectError(
@@ -97,7 +97,7 @@ async function* streamObjectImpl(options, deps) {
97
97
  lastParseError
98
98
  );
99
99
  } finally {
100
- await chunkCZ2GKKYL_cjs.disposeAndDeleteTransient(agent, deps.delete);
100
+ await chunkQDED6YO6_cjs.disposeAndDeleteTransient(agent, deps.delete);
101
101
  }
102
102
  }
103
103
  function bestEffortPartialParse(text, schema) {
@@ -144,5 +144,5 @@ function bestEffortPartialParse(text, schema) {
144
144
 
145
145
  exports.StreamObjectError = StreamObjectError;
146
146
  exports.streamObjectImpl = streamObjectImpl;
147
- //# sourceMappingURL=chunk-GD63JPGC.cjs.map
148
- //# sourceMappingURL=chunk-GD63JPGC.cjs.map
147
+ //# sourceMappingURL=chunk-ROYPRJH4.cjs.map
148
+ //# sourceMappingURL=chunk-ROYPRJH4.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stream-object.ts"],"names":["setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage","disposeAndDeleteTransient"],"mappings":";;;;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AAgBA,gBAAuB,gBAAA,CACrB,SACA,IAAA,EACsE;AACtE,EAAA,MAAM,EAAE,UAAA,EAAY,UAAA,EAAY,YAAA,EAAa,GAAIA,uCAAA;AAAA,IAC/C,OAAA,CAAQ,MAAA;AAAA,IACR,OAAA,CAAQ;AAAA,GACV;AACA,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,SAAA,GAAY,YAAA;AAEhB,EAAA,MAAM,UAAA,GAAaC,gCAAA,CAAe,UAAA,EAAY,CAAC,KAAA,KAAU;AAEvD,IAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,MAAA,WAAA,GAAc,KAAA;AAAA,IAChB;AACA,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,EACpC,CAAC,CAAA;AAED,EAAA,MAAM,eAA6BC,4CAAA,CAA2B;AAAA,IAC5D,OAA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AAA,IAAI,GAAA,GAAM,GAAG,OAAO,MAAA;AACpB,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,KAAA,EAAO,MAAM,CAAC,CAAA;AAC3C,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,SAAS,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,MAAM,eAAgB,MAAA,CAAkD,OAAA;AACxE,EAAA,MAAM,cAAc,OAAO,YAAA,KAAiB,aAAa,YAAA,CAAa,IAAA,CAAK,MAAM,CAAA,GAAI,MAAA;AACrF,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAM,CAAA;AAC3C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"chunk-GD63JPGC.cjs","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n}\n\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new StreamObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n if (attempt === maxRetries) {\n throw new StreamObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
1
+ {"version":3,"sources":["../src/stream-object.ts"],"names":["setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage","disposeAndDeleteTransient"],"mappings":";;;;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AA6BA,gBAAuB,gBAAA,CACrB,SACA,IAAA,EACsE;AACtE,EAAA,MAAM,EAAE,UAAA,EAAY,UAAA,EAAY,YAAA,EAAa,GAAIA,uCAAA;AAAA,IAC/C,OAAA,CAAQ,MAAA;AAAA,IACR,OAAA,CAAQ;AAAA,GACV;AACA,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,SAAA,GAAY,YAAA;AAEhB,EAAA,MAAM,UAAA,GAAaC,gCAAA,CAAe,UAAA,EAAY,CAAC,KAAA,KAAU;AAEvD,IAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,MAAA,WAAA,GAAc,KAAA;AAAA,IAChB;AACA,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,EACp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IAAI,KAAA,KAAU,GAAG,GAAA,GAAM,CAAA;AAAA,IACzB;AAAA,EACF;AACA,EAAA,IAAI,GAAA,GAAM,GAAG,OAAO,MAAA;AACpB,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,KAAA,EAAO,MAAM,CAAC,CAAA;AAC3C,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,SAAS,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,MAAM,eAAgB,MAAA,CAAkD,OAAA;AACxE,EAAA,MAAM,cAAc,OAAO,YAAA,KAAiB,aAAa,YAAA,CAAa,IAAA,CAAK,MAAM,CAAA,GAAI,MAAA;AACrF,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAM,CAAA;AAC3C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"chunk-ROYPRJH4.cjs","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n}\n\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * REACHED BY DYNAMIC IMPORT — do not delete on a dead-code report (B-140).\n * `agent.ts` loads this module lazily to keep it off the eager path:\n *\n * streamObjectImport ??= import(\"./stream-object.js\");\n * const { streamObjectImpl } = await streamObjectImport;\n *\n * `knip` resolves imports statically and does not follow a destructure off a\n * dynamic-import promise, so it reports this export as unused on every run. It\n * is not: removing it breaks `Agent.streamObject`. That is why this file is\n * named in `knip.json`'s ignore list rather than cleaned up — the entry is a\n * tool limitation, not a suppression of a real finding, and the difference is\n * the whole reason this comment exists.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new StreamObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n if (attempt === maxRetries) {\n throw new StreamObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { atomicWriteText } from './chunk-6AZDM6LK.js';
2
- import { InvalidTaskIdError } from './chunk-U4UJHOSH.js';
3
- import { diag } from './chunk-5F5NWKPN.js';
1
+ import { atomicWriteText } from './chunk-VF7EWVDG.js';
2
+ import { InvalidTaskIdError } from './chunk-IDCKSLYH.js';
3
+ import { diag } from './chunk-T7O6K6PX.js';
4
4
  import { mkdirSync, readdirSync } from 'fs';
5
5
  import { readFile, unlink } from 'fs/promises';
6
6
  import { join } from 'path';
@@ -55,6 +55,14 @@ function matchesTime(h, filter) {
55
55
  function matchesFilter(h, filter) {
56
56
  return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);
57
57
  }
58
+ var TERMINAL_STATES = ["finished", "error", "cancelled"];
59
+ function insertionIndex(newestFirst, submittedAt) {
60
+ for (let i = 0; i < newestFirst.length; i++) {
61
+ const entry = newestFirst[i];
62
+ if (entry !== void 0 && entry.submittedAt < submittedAt) return i;
63
+ }
64
+ return newestFirst.length;
65
+ }
58
66
  function applyFilter(values, filter) {
59
67
  const limit = filter.limit ?? DEFAULT_LIST_LIMIT;
60
68
  const out = [];
@@ -142,7 +150,14 @@ var JsonFileTaskStore = class {
142
150
  return void 0;
143
151
  }
144
152
  }
145
- async list(filter) {
153
+ /**
154
+ * Task ids backed by a file in `dir`, in readdir order.
155
+ *
156
+ * EC-8: orphan `.tmp` files left by an interrupted atomic write are skipped, as is any name
157
+ * outside the id grammar. EC-6: a missing directory lists as empty; any other `readdir` failure
158
+ * (a permission error, say) throws rather than being reported as "no tasks".
159
+ */
160
+ candidateIds() {
146
161
  let entries;
147
162
  try {
148
163
  entries = readdirSync(this.dir);
@@ -150,16 +165,38 @@ var JsonFileTaskStore = class {
150
165
  if (err.code === "ENOENT") return [];
151
166
  throw err;
152
167
  }
153
- const candidates = entries.filter((name) => name.endsWith(".json") && !name.includes(".tmp")).slice(0, JSON_LOAD_CAP);
154
- const loaded = await Promise.all(
155
- candidates.map(async (name) => {
156
- const id = name.slice(0, -".json".length);
157
- if (!isValidTaskId(id, true)) return void 0;
158
- return this.get(id);
159
- })
160
- );
161
- const handles = loaded.filter((h) => h !== void 0);
162
- return applyFilter(handles, filter);
168
+ return entries.filter((name) => name.endsWith(".json") && !name.includes(".tmp")).map((name) => name.slice(0, -".json".length)).filter((id) => isValidTaskId(id, true));
169
+ }
170
+ /**
171
+ * Read every task in `ids`, handing each loaded handle to `visit`, at most `JSON_LOAD_CAP` file
172
+ * reads in flight.
173
+ *
174
+ * #362 — the cap used to be applied to the directory listing, which made it a bound on WHICH
175
+ * tasks were visible rather than on how much I/O ran at once. Every filter then ran on that
176
+ * arbitrary readdir-ordered prefix. As a concurrency bound it does the job it was named for
177
+ * without deciding what the caller gets to see; the caller's own bound on memory is whatever
178
+ * `visit` chooses to retain.
179
+ */
180
+ async forEachHandle(ids, visit) {
181
+ for (let start = 0; start < ids.length; start += JSON_LOAD_CAP) {
182
+ const batch = ids.slice(start, start + JSON_LOAD_CAP);
183
+ const loaded = await Promise.all(batch.map(async (id) => this.get(id)));
184
+ for (const handle of loaded) {
185
+ if (handle !== void 0) await visit(handle);
186
+ }
187
+ }
188
+ }
189
+ async list(filter) {
190
+ const limit = filter.limit ?? DEFAULT_LIST_LIMIT;
191
+ const newest = [];
192
+ await this.forEachHandle(this.candidateIds(), (handle) => {
193
+ if (!matchesFilter(handle, filter)) return;
194
+ const at = insertionIndex(newest, handle.submittedAt);
195
+ if (at >= limit) return;
196
+ newest.splice(at, 0, handle);
197
+ if (newest.length > limit) newest.pop();
198
+ });
199
+ return newest;
163
200
  }
164
201
  async delete(id) {
165
202
  assertValidIdForStore(id);
@@ -172,14 +209,13 @@ var JsonFileTaskStore = class {
172
209
  }
173
210
  }
174
211
  async evictTerminalOlderThan(epochMs) {
175
- const handles = await this.list({ state: ["finished", "error", "cancelled"], limit: 256 });
176
212
  let count = 0;
177
- for (const h of handles) {
178
- const ts = terminalTimestamp(h);
179
- if (ts !== void 0 && ts < epochMs) {
180
- if (await this.delete(h.id)) count++;
181
- }
182
- }
213
+ await this.forEachHandle(this.candidateIds(), async (handle) => {
214
+ if (!TERMINAL_STATES.includes(handle.state)) return;
215
+ const ts = terminalTimestamp(handle);
216
+ if (ts === void 0 || ts >= epochMs) return;
217
+ if (await this.delete(handle.id)) count++;
218
+ });
183
219
  return count;
184
220
  }
185
221
  };
@@ -189,5 +225,5 @@ function getTaskStoreFor(options) {
189
225
  }
190
226
 
191
227
  export { InMemoryTaskStore, JsonFileTaskStore, TASK_RESERVED_PREFIXES, getTaskStoreFor, isValidTaskId };
192
- //# sourceMappingURL=chunk-V26QVGUG.js.map
193
- //# sourceMappingURL=chunk-V26QVGUG.js.map
228
+ //# sourceMappingURL=chunk-RUDY2GTT.js.map
229
+ //# sourceMappingURL=chunk-RUDY2GTT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["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CAAO,KAAK,CAAA,EAAG;AAC7C,MAAA,MAAM,EAAA,GAAK,kBAAkB,MAAM,CAAA;AACnC,MAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,IAAM,OAAA,EAAS;AACvC,MAAA,IAAI,MAAM,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,EAAE,CAAA,EAAG,KAAA,EAAA;AAAA,IACpC,CAAC,CAAA;AACD,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,gBAAgB,OAAA,EAAsC;AACpE,EAAA,IAAI,OAAA,CAAQ,OAAA,KAAY,QAAA,EAAU,OAAO,IAAI,iBAAA,EAAkB;AAC/D,EAAA,OAAO,IAAI,iBAAA,CAAkB,OAAA,CAAQ,GAAG,CAAA;AAC1C","file":"chunk-RUDY2GTT.js","sourcesContent":["/**\n * Public type contract for the Task observability registry (ADRs D361-D374).\n *\n * Tasks are an opt-in observability layer over async work in the SDK\n * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have\n * a closed 5-state lifecycle (D362), discriminated events (D366), and a\n * pluggable store (D364). The `Task` facade in `task.ts` is the public\n * surface; consumers import these types from `@theokit/sdk`.\n *\n * @public\n */\n\n/**\n * Closed enum of the 5 lifecycle states (D362).\n *\n * Transitions are acyclic:\n * queued → running → (finished | error | cancelled)\n * queued → cancelled (direct, no run started)\n */\nexport type TaskState = \"queued\" | \"running\" | \"finished\" | \"error\" | \"cancelled\";\n\n/** Discriminator of the runtime that produced a task (D374). */\nexport type TaskKind = \"run\" | \"batch\" | \"workflow\" | \"cron\" | \"custom\";\n\n/** Discriminated union of task lifecycle events (D366). */\nexport type TaskEvent =\n | {\n readonly type: \"submitted\";\n readonly taskId: string;\n readonly kind: TaskKind;\n readonly submittedAt: number;\n readonly meta?: Record<string, unknown>;\n /** D372 — flag set on the first yielded event when the ring buffer was at cap. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"started\"; readonly taskId: string; readonly startedAt: number }\n | {\n readonly type: \"progress\";\n readonly taskId: string;\n readonly at: number;\n readonly payload: unknown;\n }\n | {\n readonly type: \"finished\";\n readonly taskId: string;\n readonly finishedAt: number;\n readonly result: unknown;\n }\n | {\n readonly type: \"errored\";\n readonly taskId: string;\n readonly erroredAt: number;\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly type: \"cancelled\";\n readonly taskId: string;\n readonly cancelledAt: number;\n readonly reason?: string;\n };\n\n/** Public read-only view of a task entry in the registry. */\nexport interface TaskHandle {\n readonly id: string;\n readonly kind: TaskKind;\n readonly state: TaskState;\n readonly submittedAt: number;\n readonly startedAt?: number;\n readonly finishedAt?: number;\n readonly cancelledAt?: number;\n readonly erroredAt?: number;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly meta?: Record<string, unknown>;\n /**\n * EC-7 — cross-process best-effort cancel flag. Set by CLI\n * `theokit tasks cancel` via JsonFileTaskStore. The owning process\n * polls at checkpoints and honors via AbortController. Always\n * `undefined` for in-process cancel paths (which go directly through\n * AbortController).\n */\n readonly cancelRequested?: boolean;\n /**\n * Why the task was cancelled, when whoever cancelled it said. Free text, written alongside\n * `cancelledAt` for a `queued` task and alongside `cancelRequested` for a `running` one.\n *\n * Absent when no reason was given — an empty string is not a reason, and a default like\n * \"cancelled\" would put words in the operator's mouth. `theokit tasks cancel --reason` is what\n * writes it (#351); nothing in the runtime reads it, because it exists for the human reading the\n * registry later.\n */\n readonly cancelReason?: string;\n}\n\n/** Query filter for `Task.list`. */\nexport interface TaskFilter {\n readonly state?: TaskState | readonly TaskState[];\n readonly kind?: TaskKind | readonly TaskKind[];\n readonly submittedAfter?: number;\n readonly submittedBefore?: number;\n /**\n * Defaults to 100. `JsonFileTaskStore` returns the newest matching tasks first and reads its\n * whole directory to find them (256 files at a time); page past this limit with\n * `submittedBefore` (#362).\n */\n readonly limit?: number;\n}\n\n/** Options for `Task.submit`. */\nexport interface TaskSubmitOptions {\n /**\n * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`\n * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`\n * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.\n */\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Optional caller-provided AbortSignal. If already aborted at submit\n * time, the registry short-circuits to `cancelled` without acquiring\n * a semaphore slot (EC-4).\n */\n readonly signal?: AbortSignal;\n /**\n * SE2 — an opt-in {@link import(\"./run-events.js\").RunEventSink}. The task's\n * lifecycle is forwarded to it as typed `task_started` / `task_updated` /\n * `task_completed` RunEvents, so a caller that spawned the task can observe it\n * through the same `onRunEvent` channel as the rest of the run. Best-effort (a\n * throwing sink never breaks the task). The dedicated `Task.subscribe(id)`\n * channel is unaffected.\n */\n readonly onRunEvent?: import(\"./run-events.js\").RunEventSink;\n}\n\n/** Options shape for `TaskStore` factory (D364). */\nexport type TaskStoreOptions =\n | { readonly backend: \"memory\" }\n | { readonly backend: \"json\"; readonly dir: string };\n\n/** Result of `Task.cancel` (D365 — idempotent). */\nexport interface TaskCancelResult {\n readonly cancelled: boolean;\n readonly alreadyTerminal: boolean;\n}\n\n/**\n * Grammar for user-supplied task IDs (D368).\n * `crypto.randomUUID()` outputs do NOT match this (UUIDs have dashes\n * AND uppercase letters in their canonical form on some Node versions),\n * but the registry normalizes auto-generated IDs to lowercase before\n * insertion, so they pass the same regex.\n */\nconst TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\n/** Reserved prefixes for adapter-generated IDs (D368, EC-5). */\nconst RESERVED_PREFIXES = [\"wf-\", \"b-\", \"cron-\"] as const;\n\n/**\n * Validates a task ID against the public grammar + reserved prefixes.\n * Throws `InvalidTaskIdError` from `../errors.js` on rejection.\n *\n * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`\n * to register their own IDs; user-facing surfaces (`Task.submit`,\n * `agent.send({ task: { id } })`) leave it false.\n */\nexport function isValidTaskId(id: string, allowReserved: boolean): boolean {\n if (!TASK_ID_GRAMMAR.test(id)) return false;\n if (allowReserved) return true;\n for (const prefix of RESERVED_PREFIXES) {\n if (id.startsWith(prefix)) return false;\n }\n return true;\n}\n\n/** Re-exported for adapter implementations + tests. */\nexport const TASK_RESERVED_PREFIXES: readonly string[] = RESERVED_PREFIXES;\n","/**\n * `TaskStore` interface + 2 implementations (ADR D364).\n *\n * - `InMemoryTaskStore` — default, transient, single-process.\n * - `JsonFileTaskStore` — opt-in, one JSON file per task under a\n * dedicated dir; single-process invariant (EC-15 documented).\n *\n * Edge cases absorbed:\n * - EC-1: constructor auto-creates dir (mkdirSync recursive idempotent).\n * - EC-2: every method validates the task id against the public\n * grammar (D368) BEFORE doing any path I/O — path-traversal defense.\n * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).\n * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted\n * atomic writes.\n * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap.\n * It no longer advertises `submittedBefore` as a way to page past it:\n * the cap is applied to the raw directory listing before any filter, so\n * paging beyond 256 files is not reachable through this interface.\n * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the\n * single-process invariant; v0.2 SQLite covers cross-process.\n *\n * @internal\n */\n\nimport { mkdirSync, readdirSync } from \"node:fs\";\nimport { readFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskFilter,\n type TaskHandle,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nconst JSON_LOAD_CAP = 256;\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Storage interface used by `TaskRegistry`. */\nexport interface TaskStore {\n insert(handle: TaskHandle): Promise<void>;\n update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;\n get(id: string): Promise<TaskHandle | undefined>;\n /**\n * Returns at most `filter.limit ?? 100` matching handles.\n *\n * `JsonFileTaskStore` returns them newest-first and considers every task in its\n * directory, reading at most 256 files concurrently (#362 — that number bounds\n * I/O, not which tasks are visible). Walk past `limit` by passing the oldest\n * `submittedAt` of a page as the next call's `submittedBefore`; the ordering is\n * what makes that a cursor rather than a re-roll of an arbitrary subset.\n * `InMemoryTaskStore` applies the same filters but does not order its result.\n */\n list(filter: TaskFilter): Promise<TaskHandle[]>;\n delete(id: string): Promise<boolean>;\n /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */\n evictTerminalOlderThan(epochMs: number): Promise<number>;\n}\n\nfunction assertValidIdForStore(id: string): void {\n if (!isValidTaskId(id, /* allowReserved */ true)) {\n throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);\n }\n}\n\nfunction terminalTimestamp(h: TaskHandle): number | undefined {\n if (h.state === \"finished\") return h.finishedAt;\n if (h.state === \"error\") return h.erroredAt;\n if (h.state === \"cancelled\") return h.cancelledAt;\n return undefined;\n}\n\nfunction isTerminal(state: TaskState): boolean {\n return state === \"finished\" || state === \"error\" || state === \"cancelled\";\n}\n\nfunction matchesState(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.state === undefined) return true;\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n return states.includes(h.state);\n}\nfunction matchesKind(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.kind === undefined) return true;\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n return kinds.includes(h.kind);\n}\nfunction matchesTime(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.submittedAfter !== undefined && h.submittedAt <= filter.submittedAfter) return false;\n if (filter.submittedBefore !== undefined && h.submittedAt >= filter.submittedBefore) return false;\n return true;\n}\nfunction matchesFilter(h: TaskHandle, filter: TaskFilter): boolean {\n return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);\n}\n\n/** The states `evictTerminalOlderThan` considers terminal. */\nconst TERMINAL_STATES: readonly TaskState[] = [\"finished\", \"error\", \"cancelled\"];\n\n/**\n * Where `submittedAt` belongs in a newest-first list — the first index whose entry is older.\n *\n * Linear rather than binary: the list is bounded by the caller's `limit` (100 by default) and the\n * scan runs once per MATCHING handle, so the comparison count is dwarfed by the file read that\n * produced the handle. A binary search here would trade a real cost for an imagined one.\n */\nfunction insertionIndex(newestFirst: readonly TaskHandle[], submittedAt: number): number {\n for (let i = 0; i < newestFirst.length; i++) {\n const entry = newestFirst[i];\n if (entry !== undefined && entry.submittedAt < submittedAt) return i;\n }\n return newestFirst.length;\n}\n\nfunction applyFilter(values: Iterable<TaskHandle>, filter: TaskFilter): TaskHandle[] {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n const out: TaskHandle[] = [];\n for (const h of values) {\n if (matchesFilter(h, filter)) {\n out.push(h);\n if (out.length >= limit) break;\n }\n }\n return out;\n}\n\n/* ─── InMemory ─── */\n\n/**\n * Default `TaskStore` — a plain `Map` living in the current process.\n *\n * Nothing reaches disk and nothing survives the process, so a task recorded here\n * is invisible to a reader in another process (`theokit tasks`). Select it with\n * `getTaskStoreFor({ backend: \"memory\" })`.\n *\n * How it fails: every id-taking method validates against the task-id grammar\n * (`^[a-z0-9][a-z0-9_-]*$`; reserved `wf-`/`b-`/`cron-` prefixes are permitted\n * here) and throws `InvalidTaskIdError` before touching the map. A missing id is\n * reported by returning `undefined` (`get`, `update`) or `false` (`delete`), never\n * by throwing.\n *\n * Traps:\n * - `insert()` is a `Map.set`: an existing id is overwritten silently, not\n * rejected.\n * - `list()` walks in INSERTION order and stops as soon as `filter.limit ?? 100`\n * matches are collected. It never sorts, so the limit truncates an\n * oldest-first scan rather than returning the most recent tasks.\n * - Nothing evicts on its own; terminal handles accumulate until a caller invokes\n * `evictTerminalOlderThan`.\n */\nexport class InMemoryTaskStore implements TaskStore {\n private readonly map = new Map<string, TaskHandle>();\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n this.map.set(handle.id, handle);\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = this.map.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n this.map.set(id, next);\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n return this.map.get(id);\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n return applyFilter(this.map.values(), filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n return this.map.delete(id);\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n let count = 0;\n for (const [id, h] of this.map.entries()) {\n if (!isTerminal(h.state)) continue;\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n this.map.delete(id);\n count++;\n }\n }\n return count;\n }\n}\n\n/* ─── JsonFile (opt-in) ───\n *\n * IMPORTANT (EC-15): `JsonFileTaskStore` is **single-process**.\n * Concurrent writers from multiple Node processes against the same\n * directory may corrupt entries (atomic-write protects per-file, but\n * the `list()` scan + `update()` read-modify-write cycle is not\n * serialised across processes). Use only when the `TaskRegistry`\n * runs in exactly one process. v0.2 will add a SQLite backend with\n * the same interface for cross-process scenarios (D364 + D61).\n */\n/**\n * Opt-in `TaskStore` that keeps one JSON file per task under `dir`, so another\n * process can read the registry off disk.\n *\n * const store = new JsonFileTaskStore(\"/var/lib/theokit/tasks\");\n *\n * Two calls are synchronous, and both are deliberate: the constructor creates `dir`\n * recursively (`mkdirSync`), and `list()` scans it with `readdirSync` before awaiting\n * anything. Every other operation is async — `get` uses `readFile`, `delete` uses\n * `unlink`, and every write goes through an atomic temp-file-plus-rename.\n *\n * SINGLE-PROCESS ONLY — see the note above. Per-file atomicity does not make\n * `update()` safe: it is a read-modify-write, so two writers that both `get`\n * before either writes lose one of the two mutations. That is true within one\n * process as well as across processes.\n *\n * How it fails:\n * - An invalid id throws `InvalidTaskIdError` BEFORE any path is constructed.\n * That ordering is the path-traversal defence, and it is why ids are validated\n * rather than escaped.\n * - A missing task is `undefined` from `get` and `false` from `delete`.\n * - A file that exists but does not parse is NOT surfaced as an error: `get`\n * writes to the diagnostics channel and returns `undefined`, so a corrupted\n * task also silently vanishes from `list()`.\n * - `list()` returns `[]` when `dir` does not exist; any other `readdir` failure\n * (for example a permission error) throws.\n *\n * Traps:\n * - `list()` reads every task file in the directory (256 at a time) to apply the\n * filter, because `state`, `kind` and `submittedAt` live inside the files. On a\n * large directory that is a lot of I/O for one call; the memory it holds is\n * bounded by `limit`, the time is not.\n * - `list()` is `async`, but its directory scan is not: `readdirSync` blocks the event\n * loop for the whole listing before the first `await`. Only the per-file reads that\n * follow it are concurrent.\n * - Files whose name contains `.tmp` are skipped as orphans of an interrupted\n * write, and nothing ever removes them.\n */\nexport class JsonFileTaskStore implements TaskStore {\n constructor(private readonly dir: string) {\n // EC-1: idempotent mkdir; ignore EEXIST.\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n }\n\n private filePath(id: string): string {\n return join(this.dir, `${id}.json`);\n }\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = await this.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n await atomicWriteText(this.filePath(id), JSON.stringify(next));\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n try {\n const raw = await readFile(this.filePath(id), \"utf8\");\n return JSON.parse(raw) as TaskHandle;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n // Corrupt JSON or other I/O error — log + degrade gracefully (D50/EC-7 cache pattern).\n diag(`[task-store] failed to read ${id}: ${(err as Error).message}\\n`);\n return undefined;\n }\n }\n\n /**\n * Task ids backed by a file in `dir`, in readdir order.\n *\n * EC-8: orphan `.tmp` files left by an interrupted atomic write are skipped, as is any name\n * outside the id grammar. EC-6: a missing directory lists as empty; any other `readdir` failure\n * (a permission error, say) throws rather than being reported as \"no tasks\".\n */\n private candidateIds(): string[] {\n let entries: string[];\n try {\n entries = readdirSync(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return []; // EC-6\n throw err;\n }\n return entries\n .filter((name) => name.endsWith(\".json\") && !name.includes(\".tmp\"))\n .map((name) => name.slice(0, -\".json\".length))\n .filter((id) => isValidTaskId(id, true));\n }\n\n /**\n * Read every task in `ids`, handing each loaded handle to `visit`, at most `JSON_LOAD_CAP` file\n * reads in flight.\n *\n * #362 — the cap used to be applied to the directory listing, which made it a bound on WHICH\n * tasks were visible rather than on how much I/O ran at once. Every filter then ran on that\n * arbitrary readdir-ordered prefix. As a concurrency bound it does the job it was named for\n * without deciding what the caller gets to see; the caller's own bound on memory is whatever\n * `visit` chooses to retain.\n */\n private async forEachHandle(\n ids: readonly string[],\n visit: (handle: TaskHandle) => void | Promise<void>,\n ): Promise<void> {\n for (let start = 0; start < ids.length; start += JSON_LOAD_CAP) {\n const batch = ids.slice(start, start + JSON_LOAD_CAP);\n const loaded = await Promise.all(batch.map(async (id) => this.get(id)));\n for (const handle of loaded) {\n if (handle !== undefined) await visit(handle);\n }\n }\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n // Newest-first, keeping at most `limit` handles in memory regardless of how many match. The\n // order is what makes `submittedBefore` a real cursor: with the previous readdir order, a page\n // was an arbitrary subset, so a caller walking the timeline skipped every task that happened\n // to fall outside its window and could never come back for them.\n const newest: TaskHandle[] = [];\n await this.forEachHandle(this.candidateIds(), (handle) => {\n if (!matchesFilter(handle, filter)) return;\n const at = insertionIndex(newest, handle.submittedAt);\n if (at >= limit) return; // older than everything already held, and the page is full\n newest.splice(at, 0, handle);\n if (newest.length > limit) newest.pop();\n });\n return newest;\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n try {\n await unlink(this.filePath(id));\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw err;\n }\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n // #362 — eviction scans the directory itself rather than borrowing `list()`. Sharing that path\n // made one call incomplete twice over: it saw only a 256-file window, and it wanted the OLDEST\n // handles while `list()` is ordered newest-first — so on a large directory it could delete\n // nothing while thousands of eligible handles sat just outside the page. Sweeping every\n // candidate is what lets one call mean \"everything eligible is gone\".\n let count = 0;\n await this.forEachHandle(this.candidateIds(), async (handle) => {\n if (!TERMINAL_STATES.includes(handle.state)) return;\n const ts = terminalTimestamp(handle);\n if (ts === undefined || ts >= epochMs) return;\n if (await this.delete(handle.id)) count++;\n });\n return count;\n }\n}\n\n/** Factory used by `TaskRegistry.configure` (D364). */\nexport function getTaskStoreFor(options: TaskStoreOptions): TaskStore {\n if (options.backend === \"memory\") return new InMemoryTaskStore();\n return new JsonFileTaskStore(options.dir);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
4
- var chunkBM6N4KHO_cjs = require('./chunk-BM6N4KHO.cjs');
3
+ var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
4
+ var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
5
5
  var promises = require('fs/promises');
6
6
  var path = require('path');
7
7
 
@@ -69,7 +69,7 @@ function applyWalWithFallback(db, label) {
69
69
  function logFallback(label, reason) {
70
70
  if (warnedLabels.has(label)) return;
71
71
  warnedLabels.add(label);
72
- chunkBM6N4KHO_cjs.diag(
72
+ chunkNUKRL3I6_cjs.diag(
73
73
  `[theokit-sdk] ${label}: WAL unavailable (${reason}); using DELETE journal mode. This is normal on NFS/SMB/FUSE; expect slightly slower concurrent access.
74
74
  `
75
75
  );
@@ -141,7 +141,7 @@ async function loadDriver(filePath) {
141
141
  } catch (nodeSqliteCause) {
142
142
  const b = betterSqliteCause instanceof Error ? betterSqliteCause.message : String(betterSqliteCause);
143
143
  const n = nodeSqliteCause instanceof Error ? nodeSqliteCause.message : String(nodeSqliteCause);
144
- throw new chunkLPVIRJVF_cjs.ConfigurationError(
144
+ throw new chunkK3FW2XZD_cjs.ConfigurationError(
145
145
  `Failed to load SQLite driver. Install \`better-sqlite3\` or run on Node 22.5+ for built-in \`node:sqlite\`. better-sqlite3: ${b}; node:sqlite: ${n}`,
146
146
  { code: "sqlite_driver_unavailable", cause: nodeSqliteCause }
147
147
  );
@@ -157,7 +157,7 @@ async function renameAside(filePath, label) {
157
157
  await promises.rename(filePath, asidePath).catch(() => void 0);
158
158
  await promises.rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => void 0);
159
159
  await promises.rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => void 0);
160
- chunkBM6N4KHO_cjs.diag(
160
+ chunkNUKRL3I6_cjs.diag(
161
161
  `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema
162
162
  `
163
163
  );
@@ -168,5 +168,5 @@ exports.containsCjk = containsCjk;
168
168
  exports.isCorruptionError = isCorruptionError;
169
169
  exports.openSqliteResilient = openSqliteResilient;
170
170
  exports.sanitizeFts5Query = sanitizeFts5Query;
171
- //# sourceMappingURL=chunk-JIQRXKTA.cjs.map
172
- //# sourceMappingURL=chunk-JIQRXKTA.cjs.map
171
+ //# sourceMappingURL=chunk-SKXBJ2NU.cjs.map
172
+ //# sourceMappingURL=chunk-SKXBJ2NU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/fts5-sanitize.ts","../src/internal/persistence/sqlite-wal.ts","../src/internal/persistence/sqlite-open.ts"],"names":["diag","mkdir","dirname","ConfigurationError","rename"],"mappings":";;;;;;;;AAs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AAI,QAAA,CAAS,gBAAgB,CAAA,IAC7B,GAAA,CAAI,QAAA,CAAS,WAAW,CAAA,IACxB,GAAA,CAAI,SAAS,yBAAyB,CAAA;AAE1C;AAEA,eAAe,WAAA,CAAY,UAAkB,KAAA,EAA8B;AACzE,EAAA,MAAM,YAAY,CAAA,EAAG,QAAQ,CAAA,SAAA,EAAY,IAAA,CAAK,KAAK,CAAA,CAAA;AACnD,EAAA,MAAMC,gBAAO,QAAA,EAAU,SAAS,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AACvD,EAAA,MAAMA,eAAA,CAAO,CAAA,EAAG,QAAQ,CAAA,IAAA,CAAA,EAAQ,CAAA,EAAG,SAAS,CAAA,IAAA,CAAM,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AACzE,EAAA,MAAMA,eAAA,CAAO,CAAA,EAAG,QAAQ,CAAA,IAAA,CAAA,EAAQ,CAAA,EAAG,SAAS,CAAA,IAAA,CAAM,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AACzE,EAAAJ,sBAAA;AAAA,IACE,CAAA,cAAA,EAAiB,KAAK,CAAA,oCAAA,EAAuC,SAAS,CAAA;AAAA;AAAA,GACxE;AACF","file":"chunk-SKXBJ2NU.cjs","sourcesContent":["/**\n * FTS5 query sanitization + CJK detection (ADR D64).\n *\n * Port of Hermes' 6-step sanitizer (`hermes_state.py:1797-1847`). Prevents\n * crashes on user inputs with hyphens, dots, underscores, and unmatched\n * specials. Auto-quotes identifier-shaped tokens so `error-code` finds\n * literal `error-code` instead of `error AND code`.\n *\n * CJK detection returns true for inputs containing characters in the main\n * CJK Unicode ranges (Chinese, Japanese, Korean). CJK trigram routing is\n * deferred to v1.4 — callers receiving `containsCjk === true` should\n * short-circuit to an empty result or LIKE fallback for v1.3.\n *\n * @internal\n */\n\n// Control-char sentinels for the phrase-preservation placeholder. U+0001\n// and U+0002 are essentially never present in real user queries, and\n// crucially do NOT form word boundaries / `\\w` characters, so Step 5's\n// auto-quote regex (`\\b\\w+[-._]\\w[\\w\\-._]*\\b`) cannot match them.\n// Choosing `__PHRASE_N__` instead would re-trigger Step 5 on the second\n// sanitize pass and break idempotence.\nconst PHRASE_OPEN = \"\u0001\";\nconst PHRASE_CLOSE = \"\u0002\";\n\n/**\n * Six-step FTS5 query sanitizer. Returns a query string safe for passing\n * to `WHERE <fts5_table> MATCH ?` as a parameter.\n *\n * Returns empty string when the input contains only specials (caller MUST\n * short-circuit to avoid runtime SQL error — EC-3).\n *\n */\nexport function sanitizeFts5Query(query: string): string {\n if (query.length === 0) return query;\n\n // Step 1: preserve \"quoted phrases\" via control-char placeholders.\n const phrases: string[] = [];\n let text = query.replace(/\"[^\"]+\"/g, (match) => {\n phrases.push(match);\n return `${PHRASE_OPEN}${phrases.length - 1}${PHRASE_CLOSE}`;\n });\n\n // Step 2: strip unmatched specials (brackets, braces, parens, double quotes, caret).\n text = text.replace(/[[\\]{}()\"^]/g, \" \");\n\n // Step 3: collapse repeated asterisks (FTS5 prefix operator is single `*`).\n text = text.replace(/\\*+/g, \"*\");\n\n // Step 4: strip dangling boolean operators (AND/OR/NOT) at start/end.\n text = text.replace(/^\\s*(AND|OR|NOT)\\s+/i, \"\");\n text = text.replace(/\\s+(AND|OR|NOT)\\s*$/i, \"\");\n\n // Step 5: auto-quote identifier-shaped tokens that contain `-`, `.`, or `_`.\n // FTS5 tokenizer would otherwise split them as boolean conjunctions.\n text = text.replace(/\\b\\w+[-._]\\w[\\w\\-._]*\\b/g, (match) => `\"${match}\"`);\n\n // Step 6: restore preserved phrases.\n for (let i = 0; i < phrases.length; i += 1) {\n text = text.replace(`${PHRASE_OPEN}${i}${PHRASE_CLOSE}`, phrases[i] ?? \"\");\n }\n\n return text.trim();\n}\n\n// CJK code-point ranges. Coverage matches Hermes' coarse detection for v1.3;\n// fine-grained trigram routing comes in v1.4.\nconst CJK_RANGES: ReadonlyArray<readonly [number, number]> = [\n [0x3000, 0x303f], // CJK Symbols and Punctuation\n [0x3040, 0x309f], // Hiragana\n [0x30a0, 0x30ff], // Katakana\n [0x3400, 0x4dbf], // CJK Unified Ideographs Extension A\n [0x4e00, 0x9fff], // CJK Unified Ideographs\n [0xac00, 0xd7af], // Hangul Syllables\n];\n\n/**\n * Report whether `text` holds at least one Chinese, Japanese or Korean character.\n *\n * Iterates by code point, so surrogate pairs are handled correctly, and returns on the first hit.\n * An empty string is `false`.\n *\n * Coverage is deliberately coarse: CJK Symbols and Punctuation, Hiragana, Katakana, Hangul\n * Syllables, and CJK Unified Ideographs including Extension A. Everything beyond that — the\n * higher ideograph extensions, Halfwidth and Fullwidth Forms, Hangul Jamo — reads as `false`, so\n * a `false` is not proof that the text is CJK-free.\n *\n * The reason to ask is FTS5: the default tokenizer splits on whitespace, which CJK text does not\n * use, so a matching query against it returns nothing rather than failing. A caller seeing `true`\n * should short-circuit to an empty result or a LIKE fallback instead of running the search and\n * reporting no matches.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function containsCjk(text: string): boolean {\n for (const char of text) {\n const cp = char.codePointAt(0);\n if (cp === undefined) continue;\n for (const [lo, hi] of CJK_RANGES) {\n if (cp >= lo && cp <= hi) return true;\n }\n }\n return false;\n}\n","/**\n * SQLite WAL mode helper with NFS/SMB/FUSE fallback to DELETE (ADR D63).\n *\n * WAL is faster (concurrent readers + one writer) but unsupported on some\n * network/FUSE filesystems. Try WAL; if the pragma returns something else\n * or throws, fall back to DELETE journal mode. Warn one time per label.\n *\n * This block is the MODULE header and must stay at offset 0. Sitting below the import it became a\n * leading comment of the first declaration instead, which is how its tag deleted `PragmaCapable`\n * from the emitted `.d.ts` while `applyWalWithFallback` — which names it — survived.\n */\n\nimport { diag } from \"../diagnostics.js\";\n\n/**\n * The narrow slice of a SQLite handle this module needs: anything with a `pragma()` method, which\n * `better-sqlite3` satisfies without being named here.\n *\n * Not exported, but it appears in the signature of `applyWalWithFallback`, so it is emitted into\n * the published declarations and a consumer can structurally satisfy it.\n */\ninterface PragmaCapable {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n}\n\n/**\n * What journal mode a connection ended up in after `applyWalWithFallback`.\n *\n * `mode` is the mode actually in effect, never the one that was requested. `fellBack` is `true`\n * only when WAL was attempted and refused — either the pragma threw or it reported a mode other\n * than `wal` — and the connection was put into DELETE instead.\n *\n * `fellBack: true` is normal on NFS, SMB and FUSE, where WAL needs shared memory the filesystem\n * does not provide. It is not an error and nothing further is required of the caller; the\n * consequence is slower concurrent access, since DELETE mode does not allow readers alongside a\n * writer. Treat it as a signal about the storage, not about the database.\n *\n * @public — re-exported from the semver-protected `@theokit/sdk/persistence` barrel, and (for\n * back-compat) from the semver-exempt `@theokit/sdk/internal/persistence` alias.\n */\nexport interface WalApplyResult {\n /** Final journal_mode actually in effect. */\n mode: \"wal\" | \"delete\";\n /** True if we wanted WAL but the filesystem refused. */\n fellBack: boolean;\n}\n\nconst warnedLabels = new Set<string>();\n\n/**\n * Apply WAL mode with DELETE fallback. Idempotent — safe to call multiple\n * times on the same connection.\n *\n * @param db any `pragma()`-capable SQLite handle (e.g., `better-sqlite3`)\n * @param label short identifier used in the warning (e.g., \"memory-index\")\n *\n */\nexport function applyWalWithFallback(db: PragmaCapable, label: string): WalApplyResult {\n try {\n const result = db.pragma(\"journal_mode = WAL\", { simple: true });\n if (typeof result === \"string\" && result.toLowerCase() === \"wal\") {\n return { mode: \"wal\", fellBack: false };\n }\n logFallback(label, `got \"${String(result)}\" instead of \"wal\"`);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n logFallback(label, msg);\n }\n\n db.pragma(\"journal_mode = DELETE\");\n return { mode: \"delete\", fellBack: true };\n}\n\nfunction logFallback(label: string, reason: string): void {\n if (warnedLabels.has(label)) return;\n warnedLabels.add(label);\n diag(\n `[theokit-sdk] ${label}: WAL unavailable (${reason}); using DELETE journal mode. ` +\n \"This is normal on NFS/SMB/FUSE; expect slightly slower concurrent access.\\n\",\n );\n}\n\n/**\n * Test helper — clears the warn-once registry.\n *\n * @internal\n */\nexport function _resetWalWarnings(): void {\n warnedLabels.clear();\n}\n","/**\n * Resilient SQLite open (plan m0-foundation-expose-primitives, M0-5).\n *\n * Generalizes the driver-load + WAL-apply + corruption-recovery logic that was\n * duplicated (byte-identical) across `sdk/internal/memory/index-db.ts` and\n * `sdk-memory/internal/index/index-db.ts`. Schema-agnostic: the caller applies\n * its own PRAGMA/SCHEMA via the `onOpen` callback.\n *\n * Corruption recovery (EC-7): when opening fails with a \"malformed\" / \"not a\n * database\" / \"encrypted\" error and `recoverCorrupt` is not false, the file is\n * renamed aside to `<path>.corrupt-<ts>` (plus its WAL/SHM siblings) and a fresh\n * DB is opened. The corrupt file is renamed, NOT backed up — the timestamped\n * `.corrupt-*` file is kept for manual recovery.\n *\n * @internal — public via `@theokit/sdk/internal/persistence` (semver-exempt)\n */\n\nimport { mkdir, rename } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { applyWalWithFallback } from \"./sqlite-wal.js\";\n\n/** Minimal SQLite handle surface every driver (`better-sqlite3`) exposes. */\nexport interface ResilientSqliteDb {\n /** SQLite `pragma()` access (used by `applyWalWithFallback`). */\n pragma(statement: string, options?: { simple?: boolean }): unknown;\n exec(sql: string): void;\n close(): void;\n}\n\n/**\n * Input to {@link openSqliteResilient}.\n *\n * The trap is `recoverCorrupt`, whose default is ON. When the driver reports a corrupt or encrypted\n * database, the file is renamed aside and a FRESH one is opened — so the call SUCCEEDS and hands\n * back an EMPTY database. The old bytes survive on disk under the renamed path, but a caller that\n * treats a resolved promise as \"my data is here\" is wrong exactly when it matters. Pass\n * `recoverCorrupt: false` to get the corruption error thrown instead.\n *\n * Semver-exempt: reachable via the '@theokit/sdk/internal/persistence' sub-path, which the package\n * declares in 'exports' but does NOT cover with its semver contract.\n *\n * @typeParam T - the concrete DB handle the driver returns; defaults to {@link ResilientSqliteDb}\n */\nexport interface OpenSqliteResilientOptions<T extends ResilientSqliteDb> {\n /** Absolute path to the SQLite file. Parent directories are created. */\n filePath: string;\n /**\n * Called after the driver is open and WAL is applied, before the handle is\n * returned. Apply PRAGMA/SCHEMA statements here. Errors propagate.\n */\n onOpen?: (db: T) => void | Promise<void>;\n /** Label used in the WAL-fallback warning and corruption-recovery log. Default \"sqlite\". */\n label?: string;\n /** When true (default) a corruption error renames the file aside and rebuilds. */\n recoverCorrupt?: boolean;\n}\n\n/**\n * Open a SQLite file with WAL (+ DELETE fallback) and corruption recovery.\n *\n * @typeParam T - the concrete DB handle type the driver returns (defaults to the\n * minimal {@link ResilientSqliteDb} surface)\n */\nexport async function openSqliteResilient<T extends ResilientSqliteDb = ResilientSqliteDb>(\n options: OpenSqliteResilientOptions<T>,\n): Promise<T> {\n await mkdir(dirname(options.filePath), { recursive: true });\n try {\n return await openConcrete(options);\n } catch (cause) {\n if (options.recoverCorrupt !== false && isCorruptionError(cause)) {\n await renameAside(options.filePath, options.label ?? \"sqlite\");\n return await openConcrete(options);\n }\n throw cause;\n }\n}\n\nasync function openConcrete<T extends ResilientSqliteDb>(\n options: OpenSqliteResilientOptions<T>,\n): Promise<T> {\n const db = await loadDriver<T>(options.filePath);\n // Apply WAL with NFS/SMB/FUSE fallback BEFORE schema so the journal mode is\n // set for the whole session.\n applyWalWithFallback(db, options.label ?? \"sqlite\");\n await options.onOpen?.(db);\n return db;\n}\n\n/** Injectable driver loaders (tests simulate a consumer env without better-sqlite3). */\ninterface DriverLoaders {\n betterSqlite3?: () => Promise<unknown>;\n nodeSqlite?: () => Promise<unknown>;\n}\nlet driverLoaderOverrides: DriverLoaders | undefined;\n\n/** Test-only. @internal */\nexport function _setDriverLoadersForTests(overrides: DriverLoaders | undefined): void {\n driverLoaderOverrides = overrides;\n}\n\n/**\n * Adapt `node:sqlite`'s `DatabaseSync` to the better-sqlite3 surface this module's callers use\n * (`prepare/get/all/run`, `exec`, `close`, `pragma`, `loadExtension`). The error message below has\n * ALWAYS promised this fallback (\"or run on Node 22.5+ for built-in node:sqlite\") — before the\n * flicker-bug fix the promise was fabricated: only better-sqlite3 was ever tried, so every consumer\n * without the optional native dep lost memory tools AND got a per-turn stderr WARN.\n */\nfunction adaptNodeSqlite(db: {\n prepare(sql: string): unknown;\n exec(sql: string): void;\n close(): void;\n loadExtension?: (path: string) => void;\n}): ResilientSqliteDb {\n const pragma = (statement: string, options?: { simple?: boolean }): unknown => {\n const stmt = db.prepare(`PRAGMA ${statement}`) as {\n get(): Record<string, unknown> | undefined;\n };\n const row = stmt.get();\n if (options?.simple === true) {\n return row === undefined ? undefined : Object.values(row)[0];\n }\n return row === undefined ? [] : [row];\n };\n return new Proxy(db as unknown as ResilientSqliteDb, {\n get(target, prop, receiver) {\n if (prop === \"pragma\") return pragma;\n if (prop === \"loadExtension\" && typeof db.loadExtension !== \"function\") {\n return () => {\n throw new Error(\n \"SQLite extension loading is unavailable on the node:sqlite fallback — install better-sqlite3 for sqlite-vec\",\n );\n };\n }\n const value = Reflect.get(target, prop, receiver) as unknown;\n return typeof value === \"function\"\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n });\n}\n\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nasync function loadDriver<T extends ResilientSqliteDb>(filePath: string): Promise<T> {\n let betterSqliteCause: unknown;\n try {\n const mod = (await (driverLoaderOverrides?.betterSqlite3?.() ?? import(\"better-sqlite3\"))) as {\n default?: unknown;\n };\n const Ctor = mod.default ?? mod;\n if (typeof Ctor !== \"function\") {\n throw new Error(`better-sqlite3 export is not a constructor (got ${typeof Ctor})`);\n }\n return new (Ctor as new (path: string) => unknown)(filePath) as T;\n } catch (cause) {\n betterSqliteCause = cause;\n }\n // Fallback: the Node 22.5+ built-in driver (the path the error message documents).\n // `process.getBuiltinModule` (Node 22.3+) instead of `import(\"node:sqlite\")` — bundlers that\n // predate the sqlite builtin rewrite the import specifier to a bare \"sqlite\" package (proven in\n // the published dist: \"Cannot find package 'sqlite'\"), while getBuiltinModule is opaque to them.\n try {\n const mod = (await (driverLoaderOverrides?.nodeSqlite?.() ??\n Promise.resolve(\n (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule?.(\n \"node:sqlite\",\n ) ??\n (() => {\n throw new Error(\"node:sqlite built-in unavailable (Node < 22.3)\");\n })(),\n ))) as {\n DatabaseSync: new (\n path: string,\n ) => {\n prepare(sql: string): unknown;\n exec(sql: string): void;\n close(): void;\n };\n };\n return adaptNodeSqlite(new mod.DatabaseSync(filePath)) as T;\n } catch (nodeSqliteCause) {\n const b =\n betterSqliteCause instanceof Error ? betterSqliteCause.message : String(betterSqliteCause);\n const n = nodeSqliteCause instanceof Error ? nodeSqliteCause.message : String(nodeSqliteCause);\n throw new ConfigurationError(\n `Failed to load SQLite driver. Install \\`better-sqlite3\\` or run on Node 22.5+ for built-in \\`node:sqlite\\`. better-sqlite3: ${b}; node:sqlite: ${n}`,\n { code: \"sqlite_driver_unavailable\", cause: nodeSqliteCause },\n );\n }\n}\n\n/** True when an open error indicates an unreadable / corrupt database file. */\nexport function isCorruptionError(cause: unknown): boolean {\n if (!(cause instanceof Error)) return false;\n const msg = cause.message.toLowerCase();\n return (\n msg.includes(\"malformed\") ||\n msg.includes(\"not a database\") ||\n msg.includes(\"encrypted\") ||\n msg.includes(\"disk image is malformed\")\n );\n}\n\nasync function renameAside(filePath: string, label: string): Promise<void> {\n const asidePath = `${filePath}.corrupt-${Date.now()}`;\n await rename(filePath, asidePath).catch(() => undefined);\n await rename(`${filePath}-wal`, `${asidePath}-wal`).catch(() => undefined);\n await rename(`${filePath}-shm`, `${asidePath}-shm`).catch(() => undefined);\n diag(\n `[theokit-sdk] ${label} database corrupt; renamed aside to ${asidePath} and rebuilt schema\\n`,\n );\n}\n"]}