@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
@@ -1,6 +1,6 @@
1
- import { sessions, transcriptKey, hydratedKeys } from './chunk-4QEC4CCS.js';
2
- import { persistTurn, readSessionMessages } from './chunk-BERBYXFH.js';
3
- import { diag } from './chunk-5F5NWKPN.js';
1
+ import { sessions, transcriptKey, hydratedKeys } from './chunk-WTMU7J4U.js';
2
+ import { persistTurn, readSessionMessages } from './chunk-BMAZLQQ4.js';
3
+ import { diag } from './chunk-T7O6K6PX.js';
4
4
 
5
5
  // src/internal/session/agent-session.ts
6
6
  var pendingWrites = /* @__PURE__ */ new Map();
@@ -46,7 +46,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
46
46
  const count = (recordCounts.get(key) ?? 0) + 1;
47
47
  recordCounts.set(key, count);
48
48
  if (turn.autoCompact !== void 0) {
49
- const { autoCompactIfNeeded } = await import('./compact-session-4MNKNMO2.js');
49
+ const { autoCompactIfNeeded } = await import('./compact-session-FUJDVF7B.js');
50
50
  const fired = await autoCompactIfNeeded({
51
51
  store,
52
52
  loc,
@@ -105,5 +105,5 @@ function enqueueSessionWrite(cwd, agentId, fn) {
105
105
  }
106
106
 
107
107
  export { appendSessionMessage, clearSession, discardSession, enqueueSessionWrite, flushSessionWrites, getSessionMessages, hydrateSession, persistTurnToTranscript };
108
- //# sourceMappingURL=chunk-GOVJO4YE.js.map
109
- //# sourceMappingURL=chunk-GOVJO4YE.js.map
108
+ //# sourceMappingURL=chunk-OHBIUXKM.js.map
109
+ //# sourceMappingURL=chunk-OHBIUXKM.js.map
@@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AsB,kBAAA,GAAoC;AACxD,EAAA,OAAO,aAAA,CAAc,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAkBO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-OHBIUXKM.js","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // risky. Tracked in usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkCZ2GKKYL_cjs = require('./chunk-CZ2GKKYL.cjs');
3
+ var chunkQDED6YO6_cjs = require('./chunk-QDED6YO6.cjs');
4
4
 
5
5
  // src/generate-object.ts
6
6
  var GenerateObjectError = class extends Error {
@@ -41,11 +41,11 @@ async function runReasoningPhase(options, deps) {
41
41
  const text = result.result;
42
42
  return typeof text === "string" ? text : options.prompt;
43
43
  } finally {
44
- await chunkCZ2GKKYL_cjs.disposeAndDeleteTransient(reasoningAgent, deps.delete);
44
+ await chunkQDED6YO6_cjs.disposeAndDeleteTransient(reasoningAgent, deps.delete);
45
45
  }
46
46
  }
47
47
  async function generateObjectImpl(options, deps) {
48
- const { jsonSchema, maxRetries, initialUsage } = chunkCZ2GKKYL_cjs.setupStructuredOutput(
48
+ const { jsonSchema, maxRetries, initialUsage } = chunkQDED6YO6_cjs.setupStructuredOutput(
49
49
  options.schema,
50
50
  options.maxRetries
51
51
  );
@@ -60,7 +60,7 @@ async function generateObjectImpl(options, deps) {
60
60
  captured;
61
61
  [sentinel] = true;
62
62
  }
63
- const outputTool = chunkCZ2GKKYL_cjs.makeOutputTool(jsonSchema, (input) => {
63
+ const outputTool = chunkQDED6YO6_cjs.makeOutputTool(jsonSchema, (input) => {
64
64
  if (capturedRaw === void 0) {
65
65
  capturedRaw = input;
66
66
  }
@@ -69,7 +69,7 @@ async function generateObjectImpl(options, deps) {
69
69
  const reasoningText = options.structuringModel !== void 0 ? await runReasoningPhase(options, deps) : void 0;
70
70
  const structuringModel = options.structuringModel ?? options.model;
71
71
  const structuringPrompt = reasoningText ?? options.prompt;
72
- const agentOptions = chunkCZ2GKKYL_cjs.buildTransientAgentOptions({
72
+ const agentOptions = chunkQDED6YO6_cjs.buildTransientAgentOptions({
73
73
  model: structuringModel,
74
74
  local: options.local,
75
75
  outputTool,
@@ -79,13 +79,13 @@ async function generateObjectImpl(options, deps) {
79
79
  });
80
80
  const agent = await deps.create(agentOptions);
81
81
  try {
82
- const userMessage = chunkCZ2GKKYL_cjs.buildToolPrompt(structuringPrompt);
82
+ const userMessage = chunkQDED6YO6_cjs.buildToolPrompt(structuringPrompt);
83
83
  let lastParseError;
84
84
  for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
85
85
  capturedRaw = void 0;
86
86
  const run = await agent.send(userMessage);
87
87
  const result = await run.wait();
88
- lastUsage = chunkCZ2GKKYL_cjs.extractUsage(result);
88
+ lastUsage = chunkQDED6YO6_cjs.extractUsage(result);
89
89
  if (capturedRaw === void 0) {
90
90
  if (result.status === "error" && result.error !== void 0) {
91
91
  throw new GenerateObjectError(
@@ -135,11 +135,11 @@ async function generateObjectImpl(options, deps) {
135
135
  lastParseError
136
136
  );
137
137
  } finally {
138
- await chunkCZ2GKKYL_cjs.disposeAndDeleteTransient(agent, deps.delete);
138
+ await chunkQDED6YO6_cjs.disposeAndDeleteTransient(agent, deps.delete);
139
139
  }
140
140
  }
141
141
 
142
142
  exports.GenerateObjectError = GenerateObjectError;
143
143
  exports.generateObjectImpl = generateObjectImpl;
144
- //# sourceMappingURL=chunk-FPYT5WZP.cjs.map
145
- //# sourceMappingURL=chunk-FPYT5WZP.cjs.map
144
+ //# sourceMappingURL=chunk-P6A3M6VD.cjs.map
145
+ //# sourceMappingURL=chunk-P6A3M6VD.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generate-object.ts"],"names":["disposeAndDeleteTransient","setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage"],"mappings":";;;;;AAyFO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC3B,IAAA,GAAO,qBAAA;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;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,WAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AACtD,IAAA,IAAI,OAAO,WAAA,EAAa,SAAA,KAAc,UAAA,EAAY;AAClD,IAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAA,CAAO,GAAG,CAAC,CAAA;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,GAAA,EAAK,WAAA;AAAA,UACL,KAAA,EAAO,SAAA;AAAA,UACP,YAAA,EAAc;AAAA,SAChB;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,MAAA,CAAO,KAAA;AAAA,IAC1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACA,wCAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAML,2CAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-FPYT5WZP.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.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\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 * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends Error {\n override readonly name = \"GenerateObjectError\";\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 GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n *\n * @internal\n */\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\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\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\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 GenerateObjectError(\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 // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\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 return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/generate-object.ts"],"names":["disposeAndDeleteTransient","setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage"],"mappings":";;;;;AAyFO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC3B,IAAA,GAAO,qBAAA;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;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,GAAA,EA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F;AACA,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,SAAA,CAAU,WAAW,CAAA;AACnD,MAAA,IAAI,OAAO,OAAA,EAAS;AAClB,QAAA,OAAO;AAAA,UACL,QAAQ,MAAA,CAAO,IAAA;AAAA,UACf,GAAA,EAAK,WAAA;AAAA,UACL,KAAA,EAAO,SAAA;AAAA,UACP,YAAA,EAAc;AAAA,SAChB;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,MAAA,CAAO,KAAA;AAAA,IAC1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACA,wCAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAML,2CAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-P6A3M6VD.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.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\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 * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends Error {\n override readonly name = \"GenerateObjectError\";\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 GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\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\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\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 GenerateObjectError(\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 // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\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 return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkL5YO6PWL_cjs = require('./chunk-L5YO6PWL.cjs');
3
+ var chunkZNW6V4Y6_cjs = require('./chunk-ZNW6V4Y6.cjs');
4
4
  var chunkVKJ7V7EB_cjs = require('./chunk-VKJ7V7EB.cjs');
5
5
  var os = require('os');
6
6
  var path = require('path');
@@ -236,8 +236,8 @@ function shouldActivate(fm, touchedFiles) {
236
236
 
237
237
  // src/internal/runtime/context/context-discovery-runner.ts
238
238
  async function runDiscovery(opts) {
239
- const gitRoot = chunkL5YO6PWL_cjs.findGitRoot(opts.cwd);
240
- const specs = opts.specs ?? chunkL5YO6PWL_cjs.DEFAULT_DISCOVERY_SPECS;
239
+ const gitRoot = chunkZNW6V4Y6_cjs.findGitRoot(opts.cwd);
240
+ const specs = opts.specs ?? chunkZNW6V4Y6_cjs.DEFAULT_DISCOVERY_SPECS;
241
241
  const out = [];
242
242
  const seenReal = /* @__PURE__ */ new Set();
243
243
  for (const spec of specs) {
@@ -254,12 +254,12 @@ async function runDiscovery(opts) {
254
254
  }
255
255
  async function resolvePathsForSpec(spec, cwd, gitRoot) {
256
256
  if (spec.scope === "cwd-only") {
257
- return chunkL5YO6PWL_cjs.walkUpForFile(cwd, spec.pattern, cwd);
257
+ return chunkZNW6V4Y6_cjs.walkUpForFile(cwd, spec.pattern, cwd);
258
258
  }
259
259
  if (spec.scope === "git-root-walk") {
260
- return chunkL5YO6PWL_cjs.walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);
260
+ return chunkZNW6V4Y6_cjs.walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);
261
261
  }
262
- return chunkL5YO6PWL_cjs.walkUpForGlob(cwd, spec.pattern);
262
+ return chunkZNW6V4Y6_cjs.walkUpForGlob(cwd, spec.pattern);
263
263
  }
264
264
  async function loadOneSource(spec, path$1, opts, gitRoot) {
265
265
  const relPath = path.relative(gitRoot ?? opts.cwd, path.dirname(path$1));
@@ -336,5 +336,5 @@ exports.resolveImports = resolveImports;
336
336
  exports.runDiscovery = runDiscovery;
337
337
  exports.shouldActivateRule = shouldActivateRule;
338
338
  exports.truncateWithMarker = truncateWithMarker;
339
- //# sourceMappingURL=chunk-OKLYRPKL.cjs.map
340
- //# sourceMappingURL=chunk-OKLYRPKL.cjs.map
339
+ //# sourceMappingURL=chunk-Q47R5E2X.cjs.map
340
+ //# sourceMappingURL=chunk-Q47R5E2X.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-discovery-runner.ts"],"names":["readFile","dirname","insideRoot","resolvePath","join","homedir","isAbsolute","z","findGitRoot","DEFAULT_DISCOVERY_SPECS","walkUpForFile","walkUpForGlob","path","relative"],"mappings":";;;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AA,EACA,EAAA,EACA,IAAA,EACuC;AACvC,EAAA,OAAO,gBAAA;AAAA,IAAiB,IAAA;AAAA,IAAM,IAAA;AAAA,IAAM,EAAA;AAAA,IAAI,UAAA;AAAA,IAAY,CAAC,EAAA,KACnD,kBAAA,CAAmB,IAAI,IAAA,CAAK,YAAA,IAAgB,EAAE;AAAA,GAChD;AACF;AAEA,eAAe,uBAAA,CACb,IAAA,EACA,IAAA,EACA,EAAA,EACA,MACA,OAAA,EACuC;AACvC,EAAA,MAAM,MAAA,GAAS,MAAM,iBAAA,CAAkB,IAAA,EAAM,EAAE,eAAA,EAAiB,IAAA,CAAK,iBAAiB,CAAA;AACtF,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AACjC,EAAA,IAAI,UAAU,MAAA,CAAO,OAAA;AACrB,EAAA,IAAI,KAAK,aAAA,EAAe;AACtB,IAAA,OAAA,GAAU,MAAM,cAAA,CAAe,OAAA,EAAS,IAAA,EAAM;AAAA,MAC5C,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,IAAI,CAAC,CAAA;AAAA,MACvB,KAAA,EAAO,CAAA;AAAA,MACP,iBAAiB,IAAA,CAAK,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAKtB,WAAA,EAAa,IAAA,CAAK,UAAA,IAAc,OAAA,IAAW,IAAA,CAAK;AAAA,KACjD,CAAA;AAAA,EACH;AACA,EAAA,OAAO;AAAA,IACL,EAAA;AAAA,IACA,MAAA,EAAQ,IAAA;AAAA,IACR,OAAA;AAAA,IACA,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"chunk-Q47R5E2X.cjs","sourcesContent":["/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { insideRoot } from \"./path-containment.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n /**\n * The directory an import may not escape. When set, a target resolving outside it is\n * refused and replaced with a placeholder.\n *\n * The file carrying the import is REPOSITORY-CONTROLLED — `CLAUDE.md` and `GEMINI.md`\n * are the two default specs with `followImports: true`, and both are found by\n * `git-root-walk` inside the tree the agent was pointed at. Without a root, a cloned\n * repository could name `@~/.ssh/id_rsa` or any absolute path and have its contents\n * inlined into the system prompt, and from there sent to the model provider. The\n * traversal guard that already existed (`isSafePattern`) guards the discovery PATTERN,\n * not the import TARGET, so it never saw this.\n *\n * OPTIONAL, so a caller outside the discovery path keeps the previous behaviour rather\n * than breaking on an upgrade. `runDiscovery` always supplies `gitRoot ?? cwd` — the\n * same value it already uses to keep absolute paths out of `<source name=\"\">`.\n */\n readonly projectRoot?: string;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n // Containment BEFORE the read. Reporting the refusal after loading the file would\n // already have put the bytes in memory, and the placeholder names the path the author\n // wrote rather than the resolved one — echoing `/home/<user>/.ssh/id_rsa` back into the\n // prompt would leak the layout of the machine to the same untrusted document.\n if (opts.projectRoot !== undefined && !insideRoot(absolute, opts.projectRoot)) {\n return `[@import outside the project root, refused: ${raw}]`;\n }\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth. `projectRoot` is FORWARDED: an\n // imported file is repository-controlled too, so a root that applied only at depth 0\n // would be escapable in one extra hop.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n ...(opts.projectRoot === undefined ? {} : { projectRoot: opts.projectRoot }),\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/**\n * YAML frontmatter schema for `.theokit/rules/*.md` files.\n *\n * Every field is optional, and unknown keys are dropped rather than rejected — `safeParse` failing\n * therefore means a declared key had the wrong TYPE (`paths` as a bare string, `enabled` as the\n * string `\"false\"`), never that an unexpected key was present.\n *\n * Exported because {@link RulesFrontmatter} is inferred from it and appears in the signature of\n * {@link shouldActivateRule}, which `@theokit/sdk/context` publishes: the constant has to reach the\n * emitted declarations for that inferred type to resolve in a consumer's project.\n */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Split a `.theokit/rules/*.md` document into its frontmatter and its body.\n *\n * A file with no `---` fence is not an error: the whole text becomes the body and the frontmatter\n * is synthesised as `{ alwaysApply: true }`, so a plain markdown rule with no metadata applies\n * unconditionally. That default is the one thing to know before adding a fence — adding one and\n * omitting both `alwaysApply` and a path pattern turns an always-on rule into a dormant one.\n *\n * `undefined` means the fence was there and its contents did not survive: YAML the lite parser\n * could not read, or a shape the schema rejected (`paths` as a bare string rather than a list,\n * `enabled` as `\"false\"` rather than `false`). It never throws, and it does not say WHICH of the\n * two happened — the caller drops the file and counts it.\n *\n * Unknown frontmatter keys are dropped rather than rejected, so a misspelled `alwaysAply` parses\n * fine and simply has no effect.\n *\n * Nothing here decides whether the rule applies; that is `shouldActivateRule`.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a parsed rule applies to this turn, given the files in scope.\n *\n * Checked in strict order, first match wins:\n *\n * 1. `enabled: false` — never applies, whatever else the frontmatter says. This overrides\n * `alwaysApply: true`, which is the point of having it.\n * 2. `alwaysApply: true` — applies, and `inScopePaths` is not consulted.\n * 3. otherwise — applies only if some pattern from `paths` or `globs` matches some path in\n * `inScopePaths`. The two lists are a union, not alternatives; `globs` exists for\n * Cursor compatibility and behaves identically.\n *\n * A scoped rule with an EMPTY `inScopePaths` never applies. That is the case worth planning for:\n * `contextPaths` is empty on a plain `agent.send()`, so a rule scoped by path stays dormant until\n * the caller declares which files the turn is about. It is quiet — a dormant rule looks exactly\n * like a rule that was never written.\n *\n * A rule with a fence but no patterns and no `alwaysApply` also never applies, since step 3 has\n * nothing to match.\n *\n * `description` is not consulted. It is a note for humans, not an activation condition.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\n/**\n * Input to the context-discovery run: where to walk, how much of each file to keep, and which\n * trust boundary an `@import` may not cross.\n *\n * `cwd` and `maxBytesPerFile` are required because neither has a safe default — an unset root walks\n * the wrong tree, and an unset cap lets one large file consume the context window.\n *\n * `importRoot` is the field to reach for when the caller's trust boundary is narrower than the\n * repository. Left unset, the repository IS the boundary (`gitRoot ?? cwd`), which is the honest\n * default for a document found by walking the repository — but it does mean an `@import` can pull\n * in any file the repo contains.\n *\n * @public — re-exported from '@theokit/sdk/context', and therefore under semver.\n */\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n /**\n * The root an `@import` may not escape. Defaults to `gitRoot ?? cwd` — the same value\n * this runner already uses to keep absolute paths out of `<source name=\"\">`.\n *\n * Present so an embedder with a trust boundary narrower than the repository can declare\n * it. Absent, the repository IS the boundary, which is the honest default for a document\n * discovered by walking the repository.\n */\n readonly importRoot?: string;\n}\n\n/**\n * Find, read and parse every context file the specs describe, and return them ready for the\n * aggregator.\n *\n * Specs are processed in the order given — `opts.specs` when supplied, otherwise\n * `DEFAULT_DISCOVERY_SPECS` — and within a spec, in the order its scope resolves paths. The\n * returned array carries `priority` on each source; it is NOT sorted here, so the aggregator is\n * what applies the ordering.\n *\n * A path already emitted is skipped, across specs as well as within one. Paths arrive resolved\n * through `realpath`, so two specs pointing at the same physical file through a symlink produce\n * one source rather than two.\n *\n * Missing and unreadable files are not errors: a file that does not exist is simply not matched,\n * and one that fails to read or parse is dropped and the run continues. A frontmatter file whose\n * activation conditions do not hold — `enabled: false`, or a scope that no touched file matches —\n * is dropped the same way. So a shorter result than expected means \"nothing qualified\", and this\n * function will not tell you which of those it was.\n *\n * Reads the filesystem and nothing else. No network, no writes, and no mutation of `opts`.\n *\n * Privacy: `<source name=\"\">` is built from the path RELATIVE to the git root (or `cwd` when\n * there is no git root), never an absolute path, so a home directory never reaches the prompt.\n * `@import` resolution is bounded by `opts.importRoot`, defaulting to that same root — a document\n * cannot pull in a file from outside the repository.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts, gitRoot);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n // The document carrying the import is repository-controlled, so the repository is the\n // boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs\n // with `followImports: true` — could name any absolute or `~/` path and have it\n // inlined into the system prompt.\n projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { resolveCredential } from './chunk-SSDD676S.js';
2
- import { readStoredOAuth } from './chunk-3V7UJLQT.js';
3
- import { diag } from './chunk-5F5NWKPN.js';
1
+ import { resolveCredential } from './chunk-44MBDIHG.js';
2
+ import { readStoredOAuth } from './chunk-UQGQFBRL.js';
3
+ import { diag } from './chunk-T7O6K6PX.js';
4
4
  import { readFileSync } from 'fs';
5
5
  import { dirname, join } from 'path';
6
6
  import { fileURLToPath } from 'url';
@@ -427,6 +427,13 @@ var OPENAI_CHATGPT = {
427
427
  // vendor's client is a false statement of identity. Third-party clients send their OWN name against
428
428
  // this same endpoint, which also shows the route is not restricted to the official client.
429
429
  extraHeaders: { originator: "theokit" },
430
+ // usetheokit/theokit-sdk#383 — carry the model's encrypted reasoning between the rounds of a turn.
431
+ // On for THIS profile and no other because this is the endpoint the issue measured: OpenAI Codex
432
+ // sends `include: ["reasoning.encrypted_content"]` with `reasoning.context: "all_turns"` to the
433
+ // same backend, same model, on the same account, so acceptance is observed rather than assumed.
434
+ // The issue's measurement — a third of our bytes, 2.8x our tokens — is what this closes together
435
+ // with `prompt_cache_key`.
436
+ encryptedReasoning: true,
430
437
  transform: {
431
438
  // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.
432
439
  fetch: () => codexFetch()
@@ -545,5 +552,5 @@ function registerBuiltins() {
545
552
  }
546
553
 
547
554
  export { catalogModelSchema, getCatalogCapabilities, getCatalogModelInfo, getProviderProfile, globalSingleton, inferModelDialect, inferRegionFromModelId, isPatchedModelKey, listProviders, loadProviderCatalog, patchModelInfo, registerBuiltins, registerProvider, resolveBedrockBaseUrl, resolveVertexBaseUrl, stripBedrockPrefix, stripVertexPrefix };
548
- //# sourceMappingURL=chunk-HSQ5Q3I5.js.map
549
- //# sourceMappingURL=chunk-HSQ5Q3I5.js.map
555
+ //# sourceMappingURL=chunk-Q4CMI2LP.js.map
556
+ //# sourceMappingURL=chunk-Q4CMI2LP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/global-singleton.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-schema.ts","../src/internal/providers/catalog-loader.ts","../src/internal/providers/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts"],"names":[],"mappings":";;;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC1B,EAAA,IAAI,EAAE,GAAG,CAAA,KAAM,QAAW,CAAA,CAAE,GAAG,IAAI,MAAA,EAAO;AAC1C,EAAA,OAAO,EAAE,GAAG,CAAA;AACd;;;ACIA,IAAM,QAAA,GAAW,eAAA;AAAA,EACf,gCAAA;AAAA,EACA,0BAAU,GAAA;AACZ,CAAA;AACA,IAAM,UAAU,eAAA,CAAgB,+BAAA,EAAiC,sBAAM,IAAI,KAAqB,CAAA;AAEzF,SAAS,iBAAiB,OAAA,EAAgC;AAC/D,EAAA,IAAI,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC9B,IAAA,IAAA,CAAK,CAAA,wBAAA,EAA2B,QAAQ,IAAI,CAAA;AAAA,CAAg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gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,GAAG,CAAA;AACpB,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AAEzB,EAAA,wBAAA,EAAyB;AAC3B","file":"chunk-Q4CMI2LP.js","sourcesContent":["/**\n * One singleton per realm, keyed by `Symbol.for`.\n *\n * It exists because a package can be loaded more than once in the same process (two copies in\n * `node_modules`, ESM and CJS side by side, a monorepo with distinct versions) — and then a module-level\n * `const x = new Map()` produces TWO caches that cannot see each other. `Symbol.for` uses the global\n * symbol registry, which belongs to the realm and not the module, so every copy converges on one instance.\n *\n * It was copied verbatim into `providers/discovery.ts` and `providers/catalog-loader.ts`. That is\n * duplicated KNOWLEDGE, not a coincidence of shape: the two copies have to agree on the\n * mechanism, and one fixed without the other produces exactly the bug the function exists to avoid.\n */\nexport function globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n","/**\n * Provider registry (T3.2, ADR D107).\n *\n * `registerProvider` is idempotent and surface-warning: re-registering\n * a `name` logs to stderr (D107 last-writer-wins with WARN). Alias\n * collisions also warn (EC-5).\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.aliases\", () => new Map<string, string>());\n\nexport function registerProvider(profile: ProviderProfile): void {\n if (REGISTRY.has(profile.name)) {\n diag(`[theokit-sdk] Provider \"${profile.name}\" overridden by user plugin.\\n`);\n }\n REGISTRY.set(profile.name, profile);\n for (const alias of profile.aliases ?? []) {\n // EC-5: surface alias collision so operators notice mis-routing.\n const previous = ALIASES.get(alias);\n if (previous !== undefined && previous !== profile.name) {\n diag(`[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\n`);\n }\n ALIASES.set(alias, profile.name);\n }\n}\n\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n const canonical = ALIASES.get(name) ?? name;\n return REGISTRY.get(canonical);\n}\n\nexport function listProviders(): ProviderProfile[] {\n return Array.from(REGISTRY.values());\n}\n\n/** Test-only reset. @internal */\nexport function _resetProvidersForTests(): void {\n REGISTRY.clear();\n ALIASES.clear();\n}\n","import { z } from \"zod\";\n\n/**\n * M44 — the per-model catalog sub-schema. Field names mirror models.dev VERBATIM (snake_case) so\n * `scripts/refresh-catalog.mjs` regenerates the vendored data mechanically from `api.json` with zero\n * renaming (ADR D1).\n * TOLERANT by design: every field optional, unknown keys ignored — models.dev adds fields over time and\n * additive drift must never break the loader (Blueprint §6.4).\n *\n * theokit extensions beyond models.dev: `structured_output` / `cache_control` (both already exist on the\n * SDK's `ModelCapabilities`; models.dev has no such flags).\n *\n * Semver-exempt: nothing here is declared in `package.json` `exports`. `MODALITIES` is nonetheless\n * reachable from published declarations through the type graph, so it must be EMITTED.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows; the tag that\n * used to sit here deleted the `MODALITIES` declaration below from the emitted `.d.ts`.\n */\n\nexport const MODALITIES = [\"text\", \"audio\", \"image\", \"video\", \"pdf\"] as const;\n\n/**\n * One input or output medium a model accepts or produces.\n *\n * The union is derived from `MODALITIES`, so it is closed: a models.dev entry whose\n * `modalities.input` or `modalities.output` array contains a string outside this set fails\n * `catalogModelSchema.safeParse`, and `patchIndexFromApiJson` drops that single model rather\n * than the whole payload. Widening the catalog to a new medium means adding it to `MODALITIES`\n * first — nothing else in the schema enumerates media.\n */\nexport type Modality = (typeof MODALITIES)[number];\n\nconst costSchema = z\n .object({\n /** USD per 1M tokens (models.dev convention). */\n input: z.number().nonnegative(),\n output: z.number().nonnegative(),\n cache_read: z.number().nonnegative().optional(),\n cache_write: z.number().nonnegative().optional(),\n })\n .loose();\n\nconst limitSchema = z\n .object({\n context: z.number().positive(),\n input: z.number().positive().optional(),\n output: z.number().positive().optional(),\n })\n .loose();\n\nconst modalitiesSchema = z\n .object({\n input: z.array(z.enum(MODALITIES)).optional(),\n output: z.array(z.enum(MODALITIES)).optional(),\n })\n .loose();\n\nexport const catalogModelSchema = z\n .object({\n name: z.string().optional(),\n release_date: z.string().optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n tool_call: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */\n structured_output: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsCacheControl. */\n cache_control: z.boolean().optional(),\n cost: costSchema.optional(),\n limit: limitSchema.optional(),\n modalities: modalitiesSchema.optional(),\n status: z.enum([\"alpha\", \"beta\", \"deprecated\"]).optional(),\n })\n .loose();\n\n/**\n * One model entry as it is stored in the vendored catalog and as models.dev publishes it.\n *\n * Every field is optional, so an entry that carries only `name` still parses. Reading a value\n * therefore means handling `undefined` at each level — `model.cost?.cache_read`, not\n * `model.cost.cache_read`. Field names are models.dev's own snake_case, kept verbatim so the\n * refresh script can copy `api.json` across without renaming.\n *\n * The schema is loose rather than strict: unknown keys survive parsing and stay on the returned\n * object instead of being rejected or dropped. That is what lets models.dev add a field without\n * breaking the loader — the cost is that a typo in a key name parses silently, so a caller\n * cannot use \"it parsed\" as evidence that a field it expected was present.\n *\n * `structured_output` and `cache_control` are theokit's own additions; models.dev publishes\n * neither.\n */\nexport type CatalogModel = z.infer<typeof catalogModelSchema>;\n\n/**\n * Per-token pricing for one model, in USD per 1M tokens (models.dev's unit — not per token, and\n * not per 1K).\n *\n * `input` and `output` are required and non-negative; the two cache buckets are optional and\n * absent for models that do not price caching separately. Absent is not zero: a missing\n * `cache_read` means the catalog says nothing about the cost of a cache hit, so a caller that\n * defaults it to 0 is asserting free cache reads on its own authority.\n *\n * Like `CatalogModel`, the shape is loose — unknown pricing keys published upstream are kept on\n * the parsed value.\n */\nexport type CatalogModelCost = z.infer<typeof costSchema>;\n","/**\n * Dynamic provider catalog loader (T10.1, ADR D447).\n *\n * Loads provider metadata from `provider-catalog.json` at runtime.\n * Malformed entries are skipped with WARN (EC-1) — never crash.\n *\n * @internal\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { type CatalogModel, catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile, registerProvider } from \"./registry.js\";\nimport type { ApiMode, AuthType, ProviderProfile } from \"./types.js\";\n\nconst __dirname_resolved = dirname(fileURLToPath(import.meta.url));\n\nexport interface ProviderCapabilities {\n supportsToolUse: boolean;\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsStreaming: boolean;\n supportsCacheControl: boolean;\n maxContextTokens?: number;\n maxOutputTokens?: number;\n}\n\nexport interface CatalogEntry {\n id: string;\n displayName: string;\n apiMode: ApiMode;\n authType: AuthType;\n baseUrl: string;\n envVars: string[];\n fallbackModels: string[];\n capabilities: ProviderCapabilities;\n aliases?: string[];\n modelsUrl?: string;\n hostname?: string;\n extraHeaders?: Record<string, string>;\n /**\n * M44 — OPTIONAL per-model data (models.dev shape, snake_case — see `catalog-schema.ts`), keyed by the\n * BARE model id. Additive: entries without it behave byte-identically to before. The loader indexes this\n * into the model-info index (`getCatalogModelInfo`) rather than onto `ProviderProfile` (ADR D2 — the\n * builtins-first registration skip means profile-attached data would never reach builtin providers).\n */\n models?: Record<string, CatalogModel>;\n}\n\n/**\n * M44 — the model-info index: `provider/model` → per-model catalog data (the EXACT-map key convention).\n * Populated by the vendored catalog load AND patched by the optional models-dev source (cache entries win\n * per model). The single lookup surface for capability / cost / limit enrichment.\n */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\n\n/**\n * Look up per-model catalog data by `provider/model` key.\n *\n * Semver-exempt: not declared in `package.json` `exports`, but re-exported by\n * `catalog-source-models-dev.ts`, whose declaration is reachable from published entries — so it\n * must be EMITTED.\n */\nexport function getCatalogModelInfo(key: string): CatalogModel | undefined {\n ensureModelIndexLoaded();\n return modelInfoIndex.get(key);\n}\n\n/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\n }\n}\n\n/**\n * Index an entry's `models` block. Runs for EVERY catalog entry — including those whose PROVIDER\n * registration is skipped builtins-first — so builtin providers still get their per-model data (ADR D2).\n * A malformed model sub-entry drops THAT MODEL with WARN and keeps the provider (EC-1 philosophy extended).\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\nfunction indexEntryModels(entry: CatalogEntry): void {\n if (entry.models === undefined || typeof entry.models !== \"object\") return;\n for (const [modelId, raw] of Object.entries(entry.models)) {\n const parsed = catalogModelSchema.safeParse(raw);\n if (!parsed.success) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog model \"${entry.id}/${modelId}\": ` +\n `${parsed.error.issues[0]?.message ?? \"invalid\"}\\n`,\n );\n continue;\n }\n // Index under the entry id AND every alias — capability lookups are VENDOR-keyed (e.g.\n // `google/gemini-2.5-pro` while the entry id is `google-gemini` with alias `google`), so alias keys are\n // what make the vendor-keyed convention resolve without a second mapping table.\n modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);\n for (const alias of entry.aliases ?? []) {\n const key = `${alias}/${modelId}`;\n if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);\n }\n }\n}\n\n/** Test-only reset for the model-info index. @internal */\nexport function _resetModelInfoIndexForTests(): void {\n modelInfoIndex.clear();\n patchedModelKeys.clear();\n indexState.loaded = false;\n}\n\ninterface LoadOptions {\n _testInjectMalformed?: boolean;\n}\n\nfunction validateEntry(raw: Record<string, unknown>): CatalogEntry | null {\n if (\n typeof raw.id !== \"string\" ||\n typeof raw.displayName !== \"string\" ||\n typeof raw.apiMode !== \"string\" ||\n typeof raw.authType !== \"string\" ||\n typeof raw.baseUrl !== \"string\" ||\n !Array.isArray(raw.envVars) ||\n !Array.isArray(raw.fallbackModels) ||\n raw.capabilities == null ||\n typeof raw.capabilities !== \"object\"\n ) {\n return null;\n }\n return raw as unknown as CatalogEntry;\n}\n\nexport function loadProviderCatalog(opts?: LoadOptions): Record<string, CatalogEntry> {\n const catalogPath = join(__dirname_resolved, \"provider-catalog.json\");\n const rawText = readFileSync(catalogPath, \"utf-8\");\n let entries: Record<string, unknown>[] = JSON.parse(rawText);\n\n if (opts?._testInjectMalformed) {\n entries = [\n ...entries,\n { id: \"malformed-provider\", displayName: \"Bad\" } as Record<string, unknown>,\n ];\n }\n\n const result: Record<string, CatalogEntry> = {};\n for (const raw of entries) {\n const validated = validateEntry(raw as Record<string, unknown>);\n if (validated === null) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}\\n`,\n );\n continue;\n }\n result[validated.id] = validated;\n }\n return result;\n}\n\nlet _capabilitiesCache: Record<string, ProviderCapabilities> | null = null;\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\nexport function getCatalogCapabilities(providerId: string): ProviderCapabilities | undefined {\n if (_capabilitiesCache === null) {\n const catalog = loadProviderCatalog();\n _capabilitiesCache = {};\n for (const entry of Object.values(catalog)) {\n _capabilitiesCache[entry.id] = entry.capabilities;\n // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\n }\n }\n return _capabilitiesCache[providerId];\n}\n\nexport function registerCatalogProviders(opts?: LoadOptions): void {\n const catalog = loadProviderCatalog(opts);\n for (const entry of Object.values(catalog)) {\n // Skip catalog entries that would overwrite first-party builtins.\n // Builtins have richer env-var handling and are registered first.\n // Also skip if any alias collides with an existing provider name.\n if (getProviderProfile(entry.id) !== undefined) continue;\n if (entry.aliases?.some((a) => getProviderProfile(a) !== undefined)) continue;\n\n const profile: ProviderProfile = {\n name: entry.id,\n apiMode: entry.apiMode,\n authType: entry.authType,\n baseUrl: entry.baseUrl,\n envVars: entry.envVars,\n fallbackModels: entry.fallbackModels,\n displayName: entry.displayName,\n aliases: entry.aliases,\n modelsUrl: entry.modelsUrl,\n hostname: entry.hostname,\n extraHeaders: entry.extraHeaders,\n };\n registerProvider(profile);\n }\n}\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant. The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. A profile-map pattern\n * flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. The integration header value is theokit's own: the header attributes TRAFFIC.\n * Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * The provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The SDK's ambient credential service.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split separates the integration id from the routed provider. Endpoints/clientId/scopes\n * are OpenAI's published OAuth values.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — missing-credential semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n // #165 — this shipped as `codex_cli_rs`, another vendor's client identifier. Claiming to be a different\n // vendor's client is a false statement of identity. Third-party clients send their OWN name against\n // this same endpoint, which also shows the route is not restricted to the official client.\n extraHeaders: { originator: \"theokit\" },\n // usetheokit/theokit-sdk#383 — carry the model's encrypted reasoning between the rounds of a turn.\n // On for THIS profile and no other because this is the endpoint the issue measured: OpenAI Codex\n // sends `include: [\"reasoning.encrypted_content\"]` with `reasoning.context: \"all_turns\"` to the\n // same backend, same model, on the same account, so acceptance is observed rather than assumed.\n // The issue's measurement — a third of our bytes, 2.8x our tokens — is what this closes together\n // with `prompt_cache_key`.\n encryptedReasoning: true,\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers. VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\n};\n"]}
@@ -14,5 +14,5 @@ function withCwdMutex(key, fn) {
14
14
  }
15
15
 
16
16
  export { withCwdMutex };
17
- //# sourceMappingURL=chunk-2XLKLVVR.js.map
18
- //# sourceMappingURL=chunk-2XLKLVVR.js.map
17
+ //# sourceMappingURL=chunk-Q5EWJPRY.js.map
18
+ //# sourceMappingURL=chunk-Q5EWJPRY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/cwd-mutex.ts"],"names":[],"mappings":";AAIA,IAAM,KAAA,uBAAY,GAAA,EAA8B;AAoCzC,SAAS,YAAA,CAAgB,KAAa,EAAA,EAAkC;AAC7E,EAAA,MAAM,OAAO,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AAC/C,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,EAAA,EAAI,EAAE,CAAA;AAG7B,EAAA,KAAA,CAAM,GAAA;AAAA,IACJ,GAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MACH,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-Q5EWJPRY.js","sourcesContent":["// Tail of the queue per key. Module-scoped on purpose — see `withCwdMutex` below, which is where\n// the contract is documented. Entries are never removed, so the Map holds one promise per distinct\n// key for the life of the process; keys are expected to come from a bounded set (a file path, a\n// subsystem name), not from unbounded user input.\nconst tails = new Map<string, Promise<unknown>>();\n\n/**\n * Run `fn` after every earlier `withCwdMutex` call for the same `key` has settled, and return\n * what `fn` returns.\n *\n * Calls with the same key run strictly in the order they were made — FIFO, never concurrent.\n * Calls with different keys never wait on each other. The key is an opaque string: two callers\n * serialize against each other exactly when they pass equal keys, so a shared key IS the\n * contract, and a mismatched one silently buys no protection at all.\n *\n * A rejection does not poison the queue. The next waiter runs whether the previous `fn` fulfilled\n * or rejected, and the rejection is delivered only to the caller whose `fn` threw. This function\n * neither retries nor swallows: the returned promise rejects with whatever `fn` rejected with.\n *\n * There is no timeout and no cancellation. An `fn` that never settles blocks that key for the\n * lifetime of the process.\n *\n * **Scope — this is an in-process lock only.** State is a module-scoped Map, so it serializes\n * callers that share one module instance and nothing else. Two processes, two worker threads, or\n * two copies of the SDK resolved into the same tree do not see each other's queue. When the\n * resource is a file that other processes can also write, use `withFileLock` from\n * `./file-lock.ts` instead — it takes an OS-level lock and layers this mutex underneath, so it\n * gives both guarantees. Reach for `withCwdMutex` directly when the shared state is in memory, or\n * when the file is one only this process touches.\n *\n * Extracted packages (`@theokit/sdk-budget`, `@theokit/sdk-memory`) import this from\n * `@theokit/sdk` rather than reimplementing it, precisely so the Map is the same one: a per-package\n * copy would give each package its own queue and let their writes race.\n *\n * The Map is module-scoped, so nothing survives a process restart or a fresh module instance, and\n * its entries are never removed — pass keys from a bounded set rather than from arbitrary input.\n * Signature and semantics will not change before sdk-core v3.0.\n *\n * @public\n */\nexport function withCwdMutex<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn); // run fn whether prev fulfilled or rejected\n // Save the new tail. Store the .then() chain that swallows the result so a\n // failure here doesn't poison subsequent waiters.\n tails.set(\n key,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n"]}