@theokit/sdk 4.53.0 → 4.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (719) hide show
  1. package/CHANGELOG.md +1096 -8
  2. package/LICENSE +2 -2
  3. package/README.md +14 -9
  4. package/bin/theokit-migrate-config.mjs +11 -2
  5. package/dist/a2a/agent-mailbox.d.cts +27 -0
  6. package/dist/a2a/agent-mailbox.d.ts +27 -0
  7. package/dist/a2a/index.cjs +9 -4
  8. package/dist/a2a/index.cjs.map +1 -1
  9. package/dist/a2a/index.js +7 -2
  10. package/dist/a2a/index.js.map +1 -1
  11. package/dist/a2a/message-bus.d.cts +39 -0
  12. package/dist/a2a/message-bus.d.ts +39 -0
  13. package/dist/a2a/subagent.d.cts +68 -7
  14. package/dist/a2a/subagent.d.ts +68 -7
  15. package/dist/a2a/types.d.cts +26 -0
  16. package/dist/a2a/types.d.ts +26 -0
  17. package/dist/{agent-BiCINq25.d.ts → agent-CIUgz7cN.d.cts} +211 -858
  18. package/dist/{agent-Zta1kvGH.d.cts → agent-DSec-E0c.d.ts} +211 -858
  19. package/dist/agent-NOEGF4GI.cjs +61 -0
  20. package/dist/{agent-JX5SBYDE.cjs.map → agent-NOEGF4GI.cjs.map} +1 -1
  21. package/dist/agent-VGD5WL4N.js +52 -0
  22. package/dist/{agent-ZAGG6ZBS.js.map → agent-VGD5WL4N.js.map} +1 -1
  23. package/dist/agent-builder.d.ts +19 -0
  24. package/dist/agent-session-store-P6V3FINW.js +7 -0
  25. package/dist/{agent-session-store-JMU7ASDB.js.map → agent-session-store-P6V3FINW.js.map} +1 -1
  26. package/dist/agent-session-store-ZJ3JSRS4.cjs +24 -0
  27. package/dist/{agent-session-store-EPX2WQI4.cjs.map → agent-session-store-ZJ3JSRS4.cjs.map} +1 -1
  28. package/dist/agent.d.ts +25 -7
  29. package/dist/auth/index.cjs +53 -36
  30. package/dist/auth/index.cjs.map +1 -1
  31. package/dist/auth/index.d.cts +1 -1
  32. package/dist/auth/index.d.ts +1 -1
  33. package/dist/auth/index.js +27 -10
  34. package/dist/auth/index.js.map +1 -1
  35. package/dist/{batch-NLIS4QTW.js → batch-2TGJMNCJ.js} +14 -13
  36. package/dist/batch-2TGJMNCJ.js.map +1 -0
  37. package/dist/{batch-WQ3AJCDV.cjs → batch-ND32UKZS.cjs} +31 -30
  38. package/dist/batch-ND32UKZS.cjs.map +1 -0
  39. package/dist/{chunk-TR4V2LHV.cjs → chunk-2ADR2GSO.cjs} +8 -8
  40. package/dist/chunk-2ADR2GSO.cjs.map +1 -0
  41. package/dist/{chunk-7HQVDLFI.cjs → chunk-2C72DXQF.cjs} +65 -27
  42. package/dist/chunk-2C72DXQF.cjs.map +1 -0
  43. package/dist/{chunk-DEZ75ET5.js → chunk-2D34UTDC.js} +21 -5
  44. package/dist/chunk-2D34UTDC.js.map +1 -0
  45. package/dist/{chunk-XGYI2KQH.js → chunk-2QKTVKH3.js} +4 -4
  46. package/dist/{chunk-XGYI2KQH.js.map → chunk-2QKTVKH3.js.map} +1 -1
  47. package/dist/{chunk-BBZYXVLZ.cjs → chunk-2ZPEDVLM.cjs} +2 -2
  48. package/dist/chunk-2ZPEDVLM.cjs.map +1 -0
  49. package/dist/{chunk-DHVNJYTO.js → chunk-3E77SX4H.js} +4 -4
  50. package/dist/{chunk-DHVNJYTO.js.map → chunk-3E77SX4H.js.map} +1 -1
  51. package/dist/{chunk-VYHJZVL5.cjs → chunk-3EE6LVWT.cjs} +2 -2
  52. package/dist/chunk-3EE6LVWT.cjs.map +1 -0
  53. package/dist/chunk-3KGLRRFC.cjs +18 -0
  54. package/dist/chunk-3KGLRRFC.cjs.map +1 -0
  55. package/dist/{chunk-5NBUH3NO.js → chunk-3OR54XG4.js} +2 -2
  56. package/dist/{chunk-C6Y6CWYD.cjs.map → chunk-3OR54XG4.js.map} +1 -1
  57. package/dist/{chunk-FUASIT3E.cjs → chunk-3YJNUKYN.cjs} +15 -15
  58. package/dist/{chunk-FUASIT3E.cjs.map → chunk-3YJNUKYN.cjs.map} +1 -1
  59. package/dist/{chunk-R7TKOQMJ.js → chunk-44JAAH4X.js} +3 -3
  60. package/dist/chunk-44JAAH4X.js.map +1 -0
  61. package/dist/{chunk-XRI6DXPZ.js → chunk-44MBDIHG.js} +4 -4
  62. package/dist/chunk-44MBDIHG.js.map +1 -0
  63. package/dist/{chunk-BXVSBYGW.js → chunk-4ERPXIVB.js} +5 -5
  64. package/dist/{chunk-BXVSBYGW.js.map → chunk-4ERPXIVB.js.map} +1 -1
  65. package/dist/{chunk-T6QUCG7L.cjs → chunk-4I55V454.cjs} +4 -4
  66. package/dist/chunk-4I55V454.cjs.map +1 -0
  67. package/dist/{chunk-B4YA6BRS.cjs → chunk-4O5TGQBW.cjs} +30 -7
  68. package/dist/chunk-4O5TGQBW.cjs.map +1 -0
  69. package/dist/{chunk-4JBHSLQO.cjs → chunk-4OTIXDMU.cjs} +2 -2
  70. package/dist/{chunk-4JBHSLQO.cjs.map → chunk-4OTIXDMU.cjs.map} +1 -1
  71. package/dist/{chunk-C6Y6CWYD.cjs → chunk-52NKC5HT.cjs} +2 -2
  72. package/dist/chunk-52NKC5HT.cjs.map +1 -0
  73. package/dist/{chunk-3YYDHUNH.cjs → chunk-53CBTBWO.cjs} +11 -11
  74. package/dist/{chunk-3YYDHUNH.cjs.map → chunk-53CBTBWO.cjs.map} +1 -1
  75. package/dist/{chunk-2QMK627M.cjs → chunk-5BJV5UPY.cjs} +27 -27
  76. package/dist/chunk-5BJV5UPY.cjs.map +1 -0
  77. package/dist/{chunk-OZXPA3ME.js → chunk-5JLFFPCH.js} +4 -4
  78. package/dist/{chunk-OZXPA3ME.js.map → chunk-5JLFFPCH.js.map} +1 -1
  79. package/dist/{chunk-34XOCZJO.js → chunk-5PHVENFV.js} +3 -3
  80. package/dist/chunk-5PHVENFV.js.map +1 -0
  81. package/dist/{chunk-EQMLJ52C.cjs → chunk-5UOVYM3P.cjs} +36 -31
  82. package/dist/chunk-5UOVYM3P.cjs.map +1 -0
  83. package/dist/{chunk-33L2NVTJ.cjs → chunk-5USCYPPI.cjs} +15 -15
  84. package/dist/chunk-5USCYPPI.cjs.map +1 -0
  85. package/dist/{chunk-I732VEDW.js → chunk-AEOZTXVW.js} +3 -3
  86. package/dist/{chunk-I732VEDW.js.map → chunk-AEOZTXVW.js.map} +1 -1
  87. package/dist/{chunk-5XXUYU3M.js → chunk-AG5JPQIY.js} +3 -3
  88. package/dist/{chunk-5XXUYU3M.js.map → chunk-AG5JPQIY.js.map} +1 -1
  89. package/dist/{chunk-3SHW7XKK.js → chunk-AGSBJD2L.js} +27 -29
  90. package/dist/chunk-AGSBJD2L.js.map +1 -0
  91. package/dist/{chunk-KZBB4YKU.js → chunk-AQLGBKNT.js} +3 -3
  92. package/dist/chunk-AQLGBKNT.js.map +1 -0
  93. package/dist/{chunk-7W7ZWMLQ.js → chunk-AWO27VRZ.js} +3 -3
  94. package/dist/chunk-AWO27VRZ.js.map +1 -0
  95. package/dist/{chunk-VYCKUKPA.cjs → chunk-B2J4ZMZL.cjs} +3 -2
  96. package/dist/chunk-B2J4ZMZL.cjs.map +1 -0
  97. package/dist/{chunk-UJ3SXRZZ.js → chunk-BMAZLQQ4.js} +3 -3
  98. package/dist/{chunk-UJ3SXRZZ.js.map → chunk-BMAZLQQ4.js.map} +1 -1
  99. package/dist/{chunk-NUEL6RCZ.cjs → chunk-BVZW2B5V.cjs} +4 -4
  100. package/dist/chunk-BVZW2B5V.cjs.map +1 -0
  101. package/dist/{chunk-W4FV7JBH.js → chunk-CQ2TQ32Y.js} +4 -4
  102. package/dist/chunk-CQ2TQ32Y.js.map +1 -0
  103. package/dist/{chunk-NFATC6ZF.cjs → chunk-CQGYNZ3K.cjs} +4 -4
  104. package/dist/{chunk-NFATC6ZF.cjs.map → chunk-CQGYNZ3K.cjs.map} +1 -1
  105. package/dist/{chunk-3R4ZCQAZ.cjs → chunk-CTCGWIUD.cjs} +5 -5
  106. package/dist/{chunk-3R4ZCQAZ.cjs.map → chunk-CTCGWIUD.cjs.map} +1 -1
  107. package/dist/{chunk-HTK54K2J.js → chunk-CV7XMBHP.js} +4 -4
  108. package/dist/chunk-CV7XMBHP.js.map +1 -0
  109. package/dist/{chunk-NOS7PTKP.js → chunk-DAPSQZT4.js} +15 -10
  110. package/dist/chunk-DAPSQZT4.js.map +1 -0
  111. package/dist/{chunk-E3OCRJU6.cjs → chunk-DQKERTND.cjs} +11 -11
  112. package/dist/{chunk-E3OCRJU6.cjs.map → chunk-DQKERTND.cjs.map} +1 -1
  113. package/dist/{chunk-I5OTK2RP.js → chunk-DUIF54UP.js} +6 -6
  114. package/dist/chunk-DUIF54UP.js.map +1 -0
  115. package/dist/{chunk-C4EU627W.js → chunk-DZBSJX6J.js} +4 -4
  116. package/dist/{chunk-C4EU627W.js.map → chunk-DZBSJX6J.js.map} +1 -1
  117. package/dist/{chunk-ADVZIC43.cjs → chunk-EI2Q7SJ5.cjs} +12 -12
  118. package/dist/chunk-EI2Q7SJ5.cjs.map +1 -0
  119. package/dist/{chunk-UCFONJBG.js → chunk-EPSICJLZ.js} +2 -2
  120. package/dist/{chunk-UCFONJBG.js.map → chunk-EPSICJLZ.js.map} +1 -1
  121. package/dist/{chunk-RAACTJ7C.cjs → chunk-F3YZMOAU.cjs} +8 -8
  122. package/dist/{chunk-RAACTJ7C.cjs.map → chunk-F3YZMOAU.cjs.map} +1 -1
  123. package/dist/{chunk-KIX45IKP.js → chunk-F7AQV62G.js} +5 -4
  124. package/dist/chunk-F7AQV62G.js.map +1 -0
  125. package/dist/{chunk-2YWWPCGX.js → chunk-FXEUP75G.js} +10 -12
  126. package/dist/chunk-FXEUP75G.js.map +1 -0
  127. package/dist/{chunk-2RW7K6FN.cjs → chunk-GHX4P3V2.cjs} +2 -2
  128. package/dist/chunk-GHX4P3V2.cjs.map +1 -0
  129. package/dist/{chunk-634YVZLU.js → chunk-GJ6RK75E.js} +5 -5
  130. package/dist/chunk-GJ6RK75E.js.map +1 -0
  131. package/dist/{chunk-Z5U2JGEK.cjs → chunk-GNT35C5U.cjs} +13 -13
  132. package/dist/chunk-GNT35C5U.cjs.map +1 -0
  133. package/dist/{chunk-4NAKHID5.js → chunk-GTKFV7O5.js} +2 -2
  134. package/dist/chunk-GTKFV7O5.js.map +1 -0
  135. package/dist/{chunk-BWGXYOBZ.cjs → chunk-GWC3HADL.cjs} +4 -4
  136. package/dist/{chunk-BWGXYOBZ.cjs.map → chunk-GWC3HADL.cjs.map} +1 -1
  137. package/dist/{chunk-OXNYIMZZ.js → chunk-H73MEMQB.js} +2 -2
  138. package/dist/chunk-H73MEMQB.js.map +1 -0
  139. package/dist/{chunk-RTLUZKDL.cjs → chunk-HJBMA5MB.cjs} +11 -11
  140. package/dist/{chunk-RTLUZKDL.cjs.map → chunk-HJBMA5MB.cjs.map} +1 -1
  141. package/dist/{chunk-AM2CNBKE.js → chunk-HKCKOAIO.js} +2 -2
  142. package/dist/chunk-HKCKOAIO.js.map +1 -0
  143. package/dist/{chunk-PVBANCWU.cjs → chunk-HY57ULY2.cjs} +5 -5
  144. package/dist/{chunk-PVBANCWU.cjs.map → chunk-HY57ULY2.cjs.map} +1 -1
  145. package/dist/{chunk-CAH3G4IS.js → chunk-HY66GLM6.js} +2 -2
  146. package/dist/chunk-HY66GLM6.js.map +1 -0
  147. package/dist/{chunk-2CFEET3Y.cjs → chunk-I6TGFUCO.cjs} +4 -4
  148. package/dist/chunk-I6TGFUCO.cjs.map +1 -0
  149. package/dist/{chunk-HI4ZW62S.js → chunk-IDCKSLYH.js} +4 -4
  150. package/dist/chunk-IDCKSLYH.js.map +1 -0
  151. package/dist/{chunk-KNZU4YO5.cjs → chunk-ILCGLTSA.cjs} +4 -4
  152. package/dist/{chunk-KNZU4YO5.cjs.map → chunk-ILCGLTSA.cjs.map} +1 -1
  153. package/dist/{chunk-44IISBRZ.cjs → chunk-IWBGCBR6.cjs} +4 -4
  154. package/dist/{chunk-44IISBRZ.cjs.map → chunk-IWBGCBR6.cjs.map} +1 -1
  155. package/dist/{chunk-R3CKCRK3.cjs → chunk-J24VJOH3.cjs} +22 -6
  156. package/dist/chunk-J24VJOH3.cjs.map +1 -0
  157. package/dist/{chunk-ECPL5RV6.cjs → chunk-JHPGF3FP.cjs} +8 -8
  158. package/dist/{chunk-ECPL5RV6.cjs.map → chunk-JHPGF3FP.cjs.map} +1 -1
  159. package/dist/{chunk-SXSPMRSV.cjs → chunk-JTB5Q42C.cjs} +21 -19
  160. package/dist/chunk-JTB5Q42C.cjs.map +1 -0
  161. package/dist/{chunk-2YGIBOUH.cjs → chunk-K3FW2XZD.cjs} +9 -9
  162. package/dist/chunk-K3FW2XZD.cjs.map +1 -0
  163. package/dist/{chunk-6DCTL32L.cjs → chunk-NGESVVJN.cjs} +17 -17
  164. package/dist/chunk-NGESVVJN.cjs.map +1 -0
  165. package/dist/{chunk-MV4TOCUK.js → chunk-NLTVXLGT.js} +3 -3
  166. package/dist/{chunk-MV4TOCUK.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-ZSJPRPN7.js → chunk-OC4NTGMN.js} +3 -3
  170. package/dist/{chunk-ZSJPRPN7.js.map → chunk-OC4NTGMN.js.map} +1 -1
  171. package/dist/{chunk-K42QGAKM.cjs → chunk-P6A3M6VD.cjs} +10 -10
  172. package/dist/{chunk-K42QGAKM.cjs.map → chunk-P6A3M6VD.cjs.map} +1 -1
  173. package/dist/{chunk-OKLYRPKL.cjs → chunk-Q47R5E2X.cjs} +8 -8
  174. package/dist/chunk-Q47R5E2X.cjs.map +1 -0
  175. package/dist/{chunk-2XLKLVVR.js → chunk-Q5EWJPRY.js} +2 -2
  176. package/dist/chunk-Q5EWJPRY.js.map +1 -0
  177. package/dist/{chunk-XWCTBGYK.js → chunk-QARJGQSA.js} +16 -7
  178. package/dist/chunk-QARJGQSA.js.map +1 -0
  179. package/dist/{chunk-EUBGGYPH.cjs → chunk-QDED6YO6.cjs} +5 -5
  180. package/dist/{chunk-EUBGGYPH.cjs.map → chunk-QDED6YO6.cjs.map} +1 -1
  181. package/dist/{chunk-VK7MAV65.cjs → chunk-QKLOP4VC.cjs} +2 -2
  182. package/dist/{chunk-VK7MAV65.cjs.map → chunk-QKLOP4VC.cjs.map} +1 -1
  183. package/dist/{chunk-PLUCC4N5.js → chunk-QRSUA2CV.js} +3 -3
  184. package/dist/{chunk-PLUCC4N5.js.map → chunk-QRSUA2CV.js.map} +1 -1
  185. package/dist/{chunk-YTO5BRBD.cjs → chunk-R3UPQFKK.cjs} +21 -12
  186. package/dist/chunk-R3UPQFKK.cjs.map +1 -0
  187. package/dist/{chunk-X2FR4OIT.js → chunk-R7WIIPUR.js} +2 -2
  188. package/dist/chunk-R7WIIPUR.js.map +1 -0
  189. package/dist/{chunk-BC5EUG7R.cjs → chunk-RM7Y65IG.cjs} +18 -20
  190. package/dist/chunk-RM7Y65IG.cjs.map +1 -0
  191. package/dist/{chunk-RP5HQVLD.js → chunk-RNB4APBZ.js} +30 -7
  192. package/dist/chunk-RNB4APBZ.js.map +1 -0
  193. package/dist/{chunk-V45L2OYP.cjs → chunk-ROYPRJH4.cjs} +9 -9
  194. package/dist/{chunk-V45L2OYP.cjs.map → chunk-ROYPRJH4.cjs.map} +1 -1
  195. package/dist/{chunk-JJZ4NIAG.js → chunk-RUDY2GTT.js} +61 -24
  196. package/dist/chunk-RUDY2GTT.js.map +1 -0
  197. package/dist/{chunk-QLAWEGTZ.cjs → chunk-SKXBJ2NU.cjs} +7 -7
  198. package/dist/chunk-SKXBJ2NU.cjs.map +1 -0
  199. package/dist/chunk-SSQZA3DZ.js +15 -0
  200. package/dist/chunk-SSQZA3DZ.js.map +1 -0
  201. package/dist/{chunk-7TB5U7RK.js → chunk-SUKXXLWD.js} +6 -6
  202. package/dist/chunk-SUKXXLWD.js.map +1 -0
  203. package/dist/{chunk-N43XLTHZ.js → chunk-T73NA43R.js} +3 -3
  204. package/dist/{chunk-N43XLTHZ.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-4X3SBHPK.js → chunk-T7XEKOVW.js} +18 -17
  208. package/dist/chunk-T7XEKOVW.js.map +1 -0
  209. package/dist/{chunk-NZOR3N4E.js → chunk-TPTZA6NI.js} +293 -126
  210. package/dist/chunk-TPTZA6NI.js.map +1 -0
  211. package/dist/{chunk-QN5N3ZVT.cjs → chunk-TTHBHAJI.cjs} +44 -46
  212. package/dist/chunk-TTHBHAJI.cjs.map +1 -0
  213. package/dist/{chunk-CZHPR2G7.cjs → chunk-U2AC6JUP.cjs} +8 -8
  214. package/dist/chunk-U2AC6JUP.cjs.map +1 -0
  215. package/dist/{chunk-ITQ4NO4P.js → chunk-UC3HT2S4.js} +3 -3
  216. package/dist/{chunk-ITQ4NO4P.js.map → chunk-UC3HT2S4.js.map} +1 -1
  217. package/dist/{chunk-2VFZQEDW.cjs → chunk-UFAO4T7Z.cjs} +565 -399
  218. package/dist/chunk-UFAO4T7Z.cjs.map +1 -0
  219. package/dist/{chunk-DM6Y5B2G.cjs → chunk-UNDROG5N.cjs} +201 -154
  220. package/dist/chunk-UNDROG5N.cjs.map +1 -0
  221. package/dist/{chunk-L7EGRCKJ.js → chunk-UPRJR6IP.js} +4 -4
  222. package/dist/chunk-UPRJR6IP.js.map +1 -0
  223. package/dist/{chunk-23VZBRDQ.js → chunk-UQGQFBRL.js} +3 -3
  224. package/dist/chunk-UQGQFBRL.js.map +1 -0
  225. package/dist/{chunk-2Y5NO2SY.js → chunk-VDEWG5TV.js} +88 -43
  226. package/dist/chunk-VDEWG5TV.js.map +1 -0
  227. package/dist/{chunk-CHVSMEKM.js → chunk-VF7EWVDG.js} +3 -3
  228. package/dist/chunk-VF7EWVDG.js.map +1 -0
  229. package/dist/{chunk-PNVDQL5Y.cjs → chunk-VTYY7XL5.cjs} +2 -2
  230. package/dist/chunk-VTYY7XL5.cjs.map +1 -0
  231. package/dist/{chunk-E6T264NS.js → chunk-WKRSH2VR.js} +3 -3
  232. package/dist/{chunk-E6T264NS.js.map → chunk-WKRSH2VR.js.map} +1 -1
  233. package/dist/{chunk-4QEC4CCS.js → chunk-WTMU7J4U.js} +2 -2
  234. package/dist/{chunk-4QEC4CCS.js.map → chunk-WTMU7J4U.js.map} +1 -1
  235. package/dist/{chunk-EFXJ5C7X.js → chunk-XN7NOENA.js} +6 -6
  236. package/dist/chunk-XN7NOENA.js.map +1 -0
  237. package/dist/{chunk-AMYY3JHQ.cjs → chunk-XSX2UU6Y.cjs} +10 -9
  238. package/dist/chunk-XSX2UU6Y.cjs.map +1 -0
  239. package/dist/{chunk-6PTCKXD3.js → chunk-XV4IZNV4.js} +9 -9
  240. package/dist/chunk-XV4IZNV4.js.map +1 -0
  241. package/dist/{chunk-FBZMSLDC.cjs → chunk-XWL6O3SW.cjs} +4 -4
  242. package/dist/chunk-XWL6O3SW.cjs.map +1 -0
  243. package/dist/{chunk-OIBHY6JQ.js → chunk-YMA4S2WO.js} +4 -4
  244. package/dist/{chunk-OIBHY6JQ.js.map → chunk-YMA4S2WO.js.map} +1 -1
  245. package/dist/{chunk-T5ZWI3MC.cjs → chunk-YPJ5NH5N.cjs} +11 -11
  246. package/dist/chunk-YPJ5NH5N.cjs.map +1 -0
  247. package/dist/{chunk-YLQQX5W2.cjs → chunk-ZF2LDKQQ.cjs} +2 -2
  248. package/dist/chunk-ZF2LDKQQ.cjs.map +1 -0
  249. package/dist/{chunk-L5YO6PWL.cjs → chunk-ZNW6V4Y6.cjs} +2 -2
  250. package/dist/chunk-ZNW6V4Y6.cjs.map +1 -0
  251. package/dist/client/index.cjs.map +1 -1
  252. package/dist/client/index.js.map +1 -1
  253. package/dist/client/theokit-client.d.cts +36 -0
  254. package/dist/client/theokit-client.d.ts +36 -0
  255. package/dist/client/types.d.cts +30 -0
  256. package/dist/client/types.d.ts +30 -0
  257. package/dist/compact-session-K5LXTBPJ.js +22 -0
  258. package/dist/{compact-session-EJ36VH5I.js.map → compact-session-K5LXTBPJ.js.map} +1 -1
  259. package/dist/compact-session-YCT6JMBX.cjs +59 -0
  260. package/dist/{compact-session-6GKIS4SD.cjs.map → compact-session-YCT6JMBX.cjs.map} +1 -1
  261. package/dist/compaction.cjs +17 -16
  262. package/dist/compaction.d.cts +13 -13
  263. package/dist/compaction.d.ts +13 -13
  264. package/dist/compaction.js +4 -3
  265. package/dist/concurrency.cjs +7 -6
  266. package/dist/concurrency.cjs.map +1 -1
  267. package/dist/concurrency.js +5 -4
  268. package/dist/concurrency.js.map +1 -1
  269. package/dist/context/index.cjs +7 -7
  270. package/dist/context/index.js +3 -3
  271. package/dist/context-FDOON2DB.js +6 -0
  272. package/dist/{context-DCECDKWN.js.map → context-FDOON2DB.js.map} +1 -1
  273. package/dist/context-VMIE4BMD.cjs +23 -0
  274. package/dist/{context-4HGPCOH6.cjs.map → context-VMIE4BMD.cjs.map} +1 -1
  275. package/dist/cron-CRwy2JBF.d.ts +240 -0
  276. package/dist/cron-DxxeQ-sK.d.cts +240 -0
  277. package/dist/cron.cjs +44 -42
  278. package/dist/cron.d.cts +5 -3
  279. package/dist/cron.d.ts +5 -3
  280. package/dist/cron.js +43 -41
  281. package/dist/define-tool.d.ts +14 -6
  282. package/dist/{errors-CHllybaU.d.ts → errors-BgJH9PHi.d.cts} +39 -24
  283. package/dist/{errors-BSoXcl3F.d.cts → errors-C5fJUqLk.d.ts} +39 -24
  284. package/dist/errors.cjs +22 -21
  285. package/dist/errors.d.cts +2 -2
  286. package/dist/errors.d.ts +2 -2
  287. package/dist/errors.js +3 -2
  288. package/dist/eval.cjs +62 -59
  289. package/dist/eval.cjs.map +1 -1
  290. package/dist/eval.d.cts +38 -0
  291. package/dist/eval.d.ts +38 -0
  292. package/dist/eval.js +52 -49
  293. package/dist/eval.js.map +1 -1
  294. package/dist/event-bus.d.ts +16 -0
  295. package/dist/{executor-3CGPLVJL.js → executor-BMEHFOXZ.js} +8 -7
  296. package/dist/executor-BMEHFOXZ.js.map +1 -0
  297. package/dist/{executor-4SW7QGZ4.cjs → executor-ZERJ3DGN.cjs} +25 -24
  298. package/dist/executor-ZERJ3DGN.cjs.map +1 -0
  299. package/dist/filesystem/index.cjs +8 -7
  300. package/dist/filesystem/index.cjs.map +1 -1
  301. package/dist/filesystem/index.js +4 -3
  302. package/dist/filesystem/index.js.map +1 -1
  303. package/dist/filesystem/local-filesystem.d.cts +18 -0
  304. package/dist/filesystem/local-filesystem.d.ts +18 -0
  305. package/dist/filesystem/types.d.cts +12 -0
  306. package/dist/filesystem/types.d.ts +12 -0
  307. package/dist/fs-session-store-3MOJQGP2.cjs +20 -0
  308. package/dist/{fs-session-store-VXXDIBGM.cjs.map → fs-session-store-3MOJQGP2.cjs.map} +1 -1
  309. package/dist/fs-session-store-IN7JTTXD.js +11 -0
  310. package/dist/{fs-session-store-LIKYT24K.js.map → fs-session-store-IN7JTTXD.js.map} +1 -1
  311. package/dist/generate-object-N5MDZUJI.js +8 -0
  312. package/dist/{generate-object-TVQCW2IZ.js.map → generate-object-N5MDZUJI.js.map} +1 -1
  313. package/dist/generate-object-PGSP5U7N.cjs +21 -0
  314. package/dist/{generate-object-E465DX5I.cjs.map → generate-object-PGSP5U7N.cjs.map} +1 -1
  315. package/dist/generate-object.d.ts +20 -0
  316. package/dist/index-manager-NG5YENWO.cjs +22 -0
  317. package/dist/{index-manager-HGGL4DD5.cjs.map → index-manager-NG5YENWO.cjs.map} +1 -1
  318. package/dist/index-manager-ZMRJ6ZII.js +13 -0
  319. package/dist/{index-manager-EA6FGIQG.js.map → index-manager-ZMRJ6ZII.js.map} +1 -1
  320. package/dist/index.cjs +176 -154
  321. package/dist/index.cjs.map +1 -1
  322. package/dist/index.d.cts +761 -57
  323. package/dist/index.d.ts +761 -57
  324. package/dist/index.js +62 -59
  325. package/dist/index.js.map +1 -1
  326. package/dist/{inject-session-HO7FYVCX.js → inject-session-DDR6X6PC.js} +9 -8
  327. package/dist/inject-session-DDR6X6PC.js.map +1 -0
  328. package/dist/inject-session-XLO3KTBM.cjs +29 -0
  329. package/dist/inject-session-XLO3KTBM.cjs.map +1 -0
  330. package/dist/internal/auth/auth-types.d.ts +84 -2
  331. package/dist/internal/auth/credential-store.d.ts +34 -6
  332. package/dist/internal/auth/oauth-device.d.ts +2 -3
  333. package/dist/internal/auth/resolve-credential.d.ts +40 -0
  334. package/dist/internal/budget/tracker/budget.d.ts +12 -14
  335. package/dist/internal/budget/usage-accumulator.d.ts +15 -0
  336. package/dist/internal/llm/anthropic-shared.d.ts +8 -4
  337. package/dist/internal/llm/model-identifier.d.ts +26 -0
  338. package/dist/internal/llm/openai.d.ts +8 -0
  339. package/dist/internal/llm/router.d.ts +8 -0
  340. package/dist/internal/llm/types.d.ts +12 -1
  341. package/dist/internal/local-agent/mcp-pool.d.ts +2 -4
  342. package/dist/internal/local-agent/real-local-run-provider.d.ts +8 -3
  343. package/dist/internal/local-agent/real-local-run-tools.d.ts +8 -0
  344. package/dist/internal/mcp/oauth.d.ts +19 -1
  345. package/dist/internal/mcp/token-storage.d.ts +52 -1
  346. package/dist/internal/memory/adapters/index.cjs +12 -11
  347. package/dist/internal/memory/adapters/index.d.cts +3 -1
  348. package/dist/internal/memory/adapters/index.d.ts +3 -1
  349. package/dist/internal/memory/adapters/index.js +9 -8
  350. package/dist/internal/memory/adapters/openai-compatible.d.cts +45 -0
  351. package/dist/internal/memory/adapters/openai-compatible.d.ts +45 -0
  352. package/dist/internal/memory/embedding-cache.d.ts +42 -1
  353. package/dist/internal/memory/escape-like-pattern.d.ts +22 -0
  354. package/dist/internal/memory/sqlite-vec-loader.d.ts +1 -3
  355. package/dist/internal/memory/storage/markdown-store.d.ts +0 -5
  356. package/dist/internal/persistence/atomic-write.d.cts +93 -0
  357. package/dist/internal/persistence/atomic-write.d.ts +93 -0
  358. package/dist/internal/persistence/cwd-mutex.d.cts +34 -0
  359. package/dist/internal/persistence/cwd-mutex.d.ts +34 -0
  360. package/dist/internal/persistence/exclusive-create.d.cts +31 -0
  361. package/dist/internal/persistence/exclusive-create.d.ts +31 -0
  362. package/dist/internal/persistence/file-lock.d.cts +41 -1
  363. package/dist/internal/persistence/file-lock.d.ts +41 -1
  364. package/dist/internal/persistence/fs-session-store.d.cts +3 -0
  365. package/dist/internal/persistence/fs-session-store.d.ts +3 -0
  366. package/dist/internal/persistence/fts5-sanitize.d.cts +29 -1
  367. package/dist/internal/persistence/fts5-sanitize.d.ts +29 -1
  368. package/dist/internal/persistence/index.cjs +40 -39
  369. package/dist/internal/persistence/index.cjs.map +1 -1
  370. package/dist/internal/persistence/index.d.cts +6 -1
  371. package/dist/internal/persistence/index.d.ts +6 -1
  372. package/dist/internal/persistence/index.js +9 -8
  373. package/dist/internal/persistence/index.js.map +1 -1
  374. package/dist/internal/persistence/paths.d.cts +54 -1
  375. package/dist/internal/persistence/paths.d.ts +54 -1
  376. package/dist/internal/persistence/persistence-schema.d.cts +9 -1
  377. package/dist/internal/persistence/persistence-schema.d.ts +9 -1
  378. package/dist/internal/persistence/schema-version.d.cts +215 -1
  379. package/dist/internal/persistence/schema-version.d.ts +215 -1
  380. package/dist/internal/persistence/session-dir.d.cts +1 -0
  381. package/dist/internal/persistence/session-dir.d.ts +1 -0
  382. package/dist/internal/persistence/session-writer.d.cts +20 -7
  383. package/dist/internal/persistence/session-writer.d.ts +20 -7
  384. package/dist/internal/persistence/sqlite-cas.d.cts +37 -1
  385. package/dist/internal/persistence/sqlite-cas.d.ts +37 -1
  386. package/dist/internal/persistence/sqlite-open.d.cts +14 -0
  387. package/dist/internal/persistence/sqlite-open.d.ts +14 -0
  388. package/dist/internal/persistence/sqlite-wal.d.cts +53 -0
  389. package/dist/internal/persistence/sqlite-wal.d.ts +53 -0
  390. package/dist/internal/persistence/transcript-ops.d.cts +7 -1
  391. package/dist/internal/persistence/transcript-ops.d.ts +7 -1
  392. package/dist/internal/plugins/types.d.cts +1 -1
  393. package/dist/internal/plugins/types.d.ts +1 -1
  394. package/dist/internal/providers/builtin/cerebras.d.ts +2 -2
  395. package/dist/internal/providers/builtin/deepinfra.d.ts +1 -1
  396. package/dist/internal/providers/builtin/openai-chatgpt.d.ts +12 -0
  397. package/dist/internal/providers/catalog-loader.d.ts +8 -0
  398. package/dist/internal/providers/catalog-schema.d.ts +55 -0
  399. package/dist/internal/providers/catalog-source-models-dev.d.ts +37 -1
  400. package/dist/internal/runtime/concurrency/delegation-depth.d.ts +27 -0
  401. package/dist/internal/runtime/concurrency/subagent-credentials.d.ts +33 -1
  402. package/dist/internal/runtime/context/context-discovery-runner.d.ts +44 -0
  403. package/dist/internal/runtime/context/context-discovery.d.ts +58 -0
  404. package/dist/internal/runtime/context/context-rules-frontmatter.d.ts +70 -1
  405. package/dist/internal/runtime/fixtures/fixture-mode.d.ts +15 -1
  406. package/dist/internal/runtime/lifecycle/env-policy.d.ts +1 -3
  407. package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +15 -0
  408. package/dist/internal/runtime/registry/agent-registry-store.d.ts +12 -0
  409. package/dist/internal/runtime/registry/live-agent-registry.d.ts +37 -0
  410. package/dist/internal/scorers/llm-judge.d.ts +6 -1
  411. package/dist/internal/security/index.cjs +14 -13
  412. package/dist/internal/security/index.d.cts +4 -1
  413. package/dist/internal/security/index.d.ts +4 -1
  414. package/dist/internal/security/index.js +4 -3
  415. package/dist/internal/security/path-guard.d.cts +107 -0
  416. package/dist/internal/security/path-guard.d.ts +107 -0
  417. package/dist/internal/security/redact.d.cts +71 -0
  418. package/dist/internal/security/redact.d.ts +71 -0
  419. package/dist/internal/session/agent-session.d.ts +15 -4
  420. package/dist/internal/session/compact-session.d.ts +2 -2
  421. package/dist/internal/session/session-cache.d.ts +5 -0
  422. package/dist/internal/task/store.d.ts +91 -5
  423. package/dist/internal/telemetry/span-names.d.ts +0 -1
  424. package/dist/internal/telemetry/tracer.d.ts +38 -0
  425. package/dist/job-queue.d.ts +18 -0
  426. package/dist/judge-call-DWHAJATE.js +6 -0
  427. package/dist/{judge-call-QMKGC2ZK.js.map → judge-call-DWHAJATE.js.map} +1 -1
  428. package/dist/judge-call-EGYRC2RE.cjs +23 -0
  429. package/dist/{judge-call-GVIJWQVE.cjs.map → judge-call-EGYRC2RE.cjs.map} +1 -1
  430. package/dist/mcp-auth.cjs +41 -25
  431. package/dist/mcp-auth.cjs.map +1 -1
  432. package/dist/mcp-auth.js +34 -18
  433. package/dist/mcp-auth.js.map +1 -1
  434. package/dist/models.cjs +43 -28
  435. package/dist/models.cjs.map +1 -1
  436. package/dist/models.js +26 -11
  437. package/dist/models.js.map +1 -1
  438. package/dist/oauth-transaction-store-BT4GLTLK.cjs +36 -0
  439. package/dist/{oauth-transaction-store-7CKHPQRN.cjs.map → oauth-transaction-store-BT4GLTLK.cjs.map} +1 -1
  440. package/dist/oauth-transaction-store-W52KVHQ4.js +3 -0
  441. package/dist/{oauth-transaction-store-W74I6EFD.js.map → oauth-transaction-store-W52KVHQ4.js.map} +1 -1
  442. package/dist/path-safety.cjs +11 -10
  443. package/dist/path-safety.js +4 -3
  444. package/dist/permission-engine.d.ts +55 -0
  445. package/dist/persistence.cjs +43 -42
  446. package/dist/persistence.cjs.map +1 -1
  447. package/dist/persistence.js +13 -12
  448. package/dist/persistence.js.map +1 -1
  449. package/dist/project.cjs +9 -8
  450. package/dist/project.cjs.map +1 -1
  451. package/dist/project.js +5 -4
  452. package/dist/project.js.map +1 -1
  453. package/dist/providers.cjs +23 -0
  454. package/dist/providers.cjs.map +1 -0
  455. package/dist/providers.d.cts +29 -0
  456. package/dist/providers.d.ts +29 -0
  457. package/dist/providers.js +10 -0
  458. package/dist/providers.js.map +1 -0
  459. package/dist/registry-VFKX7WOP.cjs +47 -0
  460. package/dist/{registry-UBY26R4I.cjs.map → registry-VFKX7WOP.cjs.map} +1 -1
  461. package/dist/registry-VFP3WWQP.js +10 -0
  462. package/dist/{registry-GC7BQMSV.js.map → registry-VFP3WWQP.js.map} +1 -1
  463. package/dist/retry.cjs +5 -4
  464. package/dist/retry.js +4 -3
  465. package/dist/{run-C8FBAC8o.d.ts → run-BYSHf58D.d.cts} +185 -33
  466. package/dist/{run-C8FBAC8o.d.cts → run-BYSHf58D.d.ts} +185 -33
  467. package/dist/{run-to-completion-JDPIUKSH.js → run-to-completion-DRO77625.js} +3 -3
  468. package/dist/{run-to-completion-JDPIUKSH.js.map → run-to-completion-DRO77625.js.map} +1 -1
  469. package/dist/{run-to-completion-J73I6IY4.cjs → run-to-completion-X4OWM673.cjs} +13 -13
  470. package/dist/{run-to-completion-J73I6IY4.cjs.map → run-to-completion-X4OWM673.cjs.map} +1 -1
  471. package/dist/sandbox/bwrap.d.cts +27 -14
  472. package/dist/sandbox/bwrap.d.ts +27 -14
  473. package/dist/sandbox/index.cjs +21 -20
  474. package/dist/sandbox/index.cjs.map +1 -1
  475. package/dist/sandbox/index.js +6 -5
  476. package/dist/sandbox/index.js.map +1 -1
  477. package/dist/sandbox/linux-sandbox.d.cts +72 -0
  478. package/dist/sandbox/linux-sandbox.d.ts +72 -0
  479. package/dist/sandbox/local-sandbox.d.cts +41 -0
  480. package/dist/sandbox/local-sandbox.d.ts +41 -0
  481. package/dist/sandbox/seccomp.d.cts +6 -0
  482. package/dist/sandbox/seccomp.d.ts +6 -0
  483. package/dist/sandbox/types.d.cts +64 -0
  484. package/dist/sandbox/types.d.ts +64 -0
  485. package/dist/scorers.d.ts +38 -7
  486. package/dist/sdk-agent-D8qJVkuV.d.ts +860 -0
  487. package/dist/sdk-agent-DEoKhA8a.d.cts +860 -0
  488. package/dist/server/auth/errors.d.cts +1 -1
  489. package/dist/server/auth/errors.d.ts +1 -1
  490. package/dist/server/auth/index.cjs +29 -21
  491. package/dist/server/auth/index.cjs.map +1 -1
  492. package/dist/server/auth/index.d.cts +25 -15
  493. package/dist/server/auth/index.d.ts +25 -15
  494. package/dist/server/auth/index.js +15 -7
  495. package/dist/server/auth/index.js.map +1 -1
  496. package/dist/server/auth/oauth-transaction-store.d.cts +13 -1
  497. package/dist/server/auth/oauth-transaction-store.d.ts +13 -1
  498. package/dist/server/auth/orchestrator.d.cts +1 -1
  499. package/dist/server/auth/orchestrator.d.ts +1 -1
  500. package/dist/server/auth/types.d.cts +1 -1
  501. package/dist/server/auth/types.d.ts +1 -1
  502. package/dist/server/auth/validate-return-to.d.cts +21 -11
  503. package/dist/server/auth/validate-return-to.d.ts +21 -11
  504. package/dist/server/errors-envelope.cjs +15 -14
  505. package/dist/server/errors-envelope.cjs.map +1 -1
  506. package/dist/server/errors-envelope.d.cts +4 -4
  507. package/dist/server/errors-envelope.d.ts +4 -4
  508. package/dist/server/errors-envelope.js +4 -3
  509. package/dist/server/errors-envelope.js.map +1 -1
  510. package/dist/session-transcript-AKDYYGXQ.js +6 -0
  511. package/dist/{session-transcript-SKIRBEJE.js.map → session-transcript-AKDYYGXQ.js.map} +1 -1
  512. package/dist/session-transcript-JXHFTB7G.cjs +51 -0
  513. package/dist/{session-transcript-TNAJ4O3M.cjs.map → session-transcript-JXHFTB7G.cjs.map} +1 -1
  514. package/dist/skills.cjs +8 -7
  515. package/dist/skills.js +6 -5
  516. package/dist/stream-object-BUCF5PHO.cjs +21 -0
  517. package/dist/{stream-object-T4DAMNVB.cjs.map → stream-object-BUCF5PHO.cjs.map} +1 -1
  518. package/dist/stream-object-L57K4OFS.js +8 -0
  519. package/dist/{stream-object-QMNR3YFF.js.map → stream-object-L57K4OFS.js.map} +1 -1
  520. package/dist/{stream-to-completion-DFJ5T3BK.js → stream-to-completion-QV5HCL3J.js} +3 -3
  521. package/dist/{stream-to-completion-DFJ5T3BK.js.map → stream-to-completion-QV5HCL3J.js.map} +1 -1
  522. package/dist/{stream-to-completion-H2MHISSK.cjs → stream-to-completion-SRISU5AB.cjs} +10 -10
  523. package/dist/{stream-to-completion-H2MHISSK.cjs.map → stream-to-completion-SRISU5AB.cjs.map} +1 -1
  524. package/dist/subagents-loader-AZIXJ7D3.cjs +16 -0
  525. package/dist/{subagents-loader-3CXBQWWY.cjs.map → subagents-loader-AZIXJ7D3.cjs.map} +1 -1
  526. package/dist/subagents-loader-J54ESLDV.js +7 -0
  527. package/dist/{subagents-loader-WN2SB6PV.js.map → subagents-loader-J54ESLDV.js.map} +1 -1
  528. package/dist/subagents-loader.cjs +7 -6
  529. package/dist/subagents-loader.cjs.map +1 -1
  530. package/dist/subagents-loader.d.cts +3 -2
  531. package/dist/subagents-loader.d.ts +3 -2
  532. package/dist/subagents-loader.js +5 -4
  533. package/dist/subagents-loader.js.map +1 -1
  534. package/dist/subscription/define-subscription.d.cts +1 -1
  535. package/dist/subscription/define-subscription.d.ts +1 -1
  536. package/dist/subscription/index.cjs +22 -9
  537. package/dist/subscription/index.cjs.map +1 -1
  538. package/dist/subscription/index.d.cts +1 -1
  539. package/dist/subscription/index.d.ts +1 -1
  540. package/dist/subscription/index.js +21 -8
  541. package/dist/subscription/index.js.map +1 -1
  542. package/dist/subscription/internal/adapter-types.d.cts +1 -1
  543. package/dist/subscription/internal/adapter-types.d.ts +1 -1
  544. package/dist/subscription/internal/server-integration.d.cts +1 -1
  545. package/dist/subscription/internal/server-integration.d.ts +1 -1
  546. package/dist/subscription/internal/sse-encoder.d.cts +1 -1
  547. package/dist/subscription/internal/sse-encoder.d.ts +1 -1
  548. package/dist/subscription/internal/sse-parser.d.cts +1 -1
  549. package/dist/subscription/internal/sse-parser.d.ts +1 -1
  550. package/dist/subscription/internal/subscription-runtime.d.cts +1 -1
  551. package/dist/subscription/internal/subscription-runtime.d.ts +1 -1
  552. package/dist/subscription/internal/ws-adapter-node.d.cts +1 -1
  553. package/dist/subscription/internal/ws-adapter-node.d.ts +1 -1
  554. package/dist/subscription/theokit-subscribe.d.cts +14 -1
  555. package/dist/subscription/theokit-subscribe.d.ts +14 -1
  556. package/dist/subscription/types.d.cts +19 -1
  557. package/dist/subscription/types.d.ts +19 -1
  558. package/dist/task-store.cjs +8 -7
  559. package/dist/task-store.js +5 -4
  560. package/dist/types/agent-prims.d.ts +14 -0
  561. package/dist/types/agent.d.ts +69 -17
  562. package/dist/types/batch.d.ts +7 -1
  563. package/dist/types/conversation.d.ts +18 -5
  564. package/dist/types/goal-events.d.ts +4 -8
  565. package/dist/types/memory-adapter.d.ts +12 -1
  566. package/dist/types/plugin.d.ts +101 -0
  567. package/dist/types/provider-profile.d.ts +21 -2
  568. package/dist/types/run-events.d.ts +28 -1
  569. package/dist/types/run.d.ts +35 -23
  570. package/dist/types/sdk-agent.d.ts +14 -0
  571. package/dist/types/session-record.d.ts +18 -1
  572. package/dist/types/task.d.ts +15 -1
  573. package/dist/types/theokit.d.ts +10 -1
  574. package/dist/types/updates.d.ts +35 -4
  575. package/dist/types/workflow.d.ts +155 -0
  576. package/dist/workflow.cjs +29 -28
  577. package/dist/workflow.d.cts +666 -17
  578. package/dist/workflow.d.ts +666 -17
  579. package/dist/workflow.js +8 -7
  580. package/docs/error-codes.md +208 -172
  581. package/docs/harness-capability-map.md +1357 -304
  582. package/package.json +21 -8
  583. package/bin/init-claude.mjs +0 -68
  584. package/claude-template/AGENTS.md +0 -157
  585. package/claude-template/CLAUDE.md +0 -66
  586. package/claude-template/dot-claude/rules/theokit-conventions.md +0 -32
  587. package/claude-template/dot-claude/settings.json +0 -16
  588. package/claude-template/dot-claude/skills/theokit-agent-core/SKILL.md +0 -209
  589. package/claude-template/dot-claude/skills/theokit-auth/SKILL.md +0 -102
  590. package/claude-template/dot-claude/skills/theokit-budget/SKILL.md +0 -176
  591. package/claude-template/dot-claude/skills/theokit-client/SKILL.md +0 -58
  592. package/claude-template/dot-claude/skills/theokit-compaction/SKILL.md +0 -102
  593. package/claude-template/dot-claude/skills/theokit-concurrency/SKILL.md +0 -68
  594. package/claude-template/dot-claude/skills/theokit-config/SKILL.md +0 -139
  595. package/claude-template/dot-claude/skills/theokit-cron/SKILL.md +0 -148
  596. package/claude-template/dot-claude/skills/theokit-di/SKILL.md +0 -233
  597. package/claude-template/dot-claude/skills/theokit-di-agent/SKILL.md +0 -294
  598. package/claude-template/dot-claude/skills/theokit-errors/SKILL.md +0 -172
  599. package/claude-template/dot-claude/skills/theokit-eval/SKILL.md +0 -179
  600. package/claude-template/dot-claude/skills/theokit-filesystem/SKILL.md +0 -74
  601. package/claude-template/dot-claude/skills/theokit-gateways/SKILL.md +0 -209
  602. package/claude-template/dot-claude/skills/theokit-memory/SKILL.md +0 -176
  603. package/claude-template/dot-claude/skills/theokit-messages/SKILL.md +0 -58
  604. package/claude-template/dot-claude/skills/theokit-models/SKILL.md +0 -79
  605. package/claude-template/dot-claude/skills/theokit-path-safety/SKILL.md +0 -60
  606. package/claude-template/dot-claude/skills/theokit-persistence/SKILL.md +0 -85
  607. package/claude-template/dot-claude/skills/theokit-project/SKILL.md +0 -55
  608. package/claude-template/dot-claude/skills/theokit-retry/SKILL.md +0 -50
  609. package/claude-template/dot-claude/skills/theokit-sandbox/SKILL.md +0 -93
  610. package/claude-template/dot-claude/skills/theokit-sanitize/SKILL.md +0 -66
  611. package/claude-template/dot-claude/skills/theokit-skills/SKILL.md +0 -68
  612. package/claude-template/dot-claude/skills/theokit-streaming/SKILL.md +0 -156
  613. package/claude-template/dot-claude/skills/theokit-subagents/SKILL.md +0 -109
  614. package/claude-template/dot-claude/skills/theokit-subscriptions/SKILL.md +0 -148
  615. package/claude-template/dot-claude/skills/theokit-task-store/SKILL.md +0 -75
  616. package/claude-template/dot-claude/skills/theokit-tools/SKILL.md +0 -170
  617. package/claude-template/dot-claude/skills/theokit-workflows/SKILL.md +0 -218
  618. package/dist/agent-JX5SBYDE.cjs +0 -59
  619. package/dist/agent-ZAGG6ZBS.js +0 -50
  620. package/dist/agent-session-store-EPX2WQI4.cjs +0 -23
  621. package/dist/agent-session-store-JMU7ASDB.js +0 -6
  622. package/dist/batch-NLIS4QTW.js.map +0 -1
  623. package/dist/batch-WQ3AJCDV.cjs.map +0 -1
  624. package/dist/chunk-23VZBRDQ.js.map +0 -1
  625. package/dist/chunk-2CFEET3Y.cjs.map +0 -1
  626. package/dist/chunk-2QMK627M.cjs.map +0 -1
  627. package/dist/chunk-2RW7K6FN.cjs.map +0 -1
  628. package/dist/chunk-2VFZQEDW.cjs.map +0 -1
  629. package/dist/chunk-2XLKLVVR.js.map +0 -1
  630. package/dist/chunk-2Y5NO2SY.js.map +0 -1
  631. package/dist/chunk-2YGIBOUH.cjs.map +0 -1
  632. package/dist/chunk-2YWWPCGX.js.map +0 -1
  633. package/dist/chunk-33L2NVTJ.cjs.map +0 -1
  634. package/dist/chunk-34XOCZJO.js.map +0 -1
  635. package/dist/chunk-3SHW7XKK.js.map +0 -1
  636. package/dist/chunk-4NAKHID5.js.map +0 -1
  637. package/dist/chunk-4X3SBHPK.js.map +0 -1
  638. package/dist/chunk-5NBUH3NO.js.map +0 -1
  639. package/dist/chunk-634YVZLU.js.map +0 -1
  640. package/dist/chunk-6DCTL32L.cjs.map +0 -1
  641. package/dist/chunk-6PTCKXD3.js.map +0 -1
  642. package/dist/chunk-7HQVDLFI.cjs.map +0 -1
  643. package/dist/chunk-7TB5U7RK.js.map +0 -1
  644. package/dist/chunk-7W7ZWMLQ.js.map +0 -1
  645. package/dist/chunk-ADVZIC43.cjs.map +0 -1
  646. package/dist/chunk-AM2CNBKE.js.map +0 -1
  647. package/dist/chunk-AMYY3JHQ.cjs.map +0 -1
  648. package/dist/chunk-B4YA6BRS.cjs.map +0 -1
  649. package/dist/chunk-BBZYXVLZ.cjs.map +0 -1
  650. package/dist/chunk-BC5EUG7R.cjs.map +0 -1
  651. package/dist/chunk-CAH3G4IS.js.map +0 -1
  652. package/dist/chunk-CHVSMEKM.js.map +0 -1
  653. package/dist/chunk-CZHPR2G7.cjs.map +0 -1
  654. package/dist/chunk-DEZ75ET5.js.map +0 -1
  655. package/dist/chunk-DM6Y5B2G.cjs.map +0 -1
  656. package/dist/chunk-EFXJ5C7X.js.map +0 -1
  657. package/dist/chunk-EQMLJ52C.cjs.map +0 -1
  658. package/dist/chunk-FBZMSLDC.cjs.map +0 -1
  659. package/dist/chunk-HI4ZW62S.js.map +0 -1
  660. package/dist/chunk-HTK54K2J.js.map +0 -1
  661. package/dist/chunk-I5OTK2RP.js.map +0 -1
  662. package/dist/chunk-JJZ4NIAG.js.map +0 -1
  663. package/dist/chunk-KIX45IKP.js.map +0 -1
  664. package/dist/chunk-KZBB4YKU.js.map +0 -1
  665. package/dist/chunk-L5YO6PWL.cjs.map +0 -1
  666. package/dist/chunk-L7EGRCKJ.js.map +0 -1
  667. package/dist/chunk-NOS7PTKP.js.map +0 -1
  668. package/dist/chunk-NUEL6RCZ.cjs.map +0 -1
  669. package/dist/chunk-NZOR3N4E.js.map +0 -1
  670. package/dist/chunk-OKLYRPKL.cjs.map +0 -1
  671. package/dist/chunk-OXNYIMZZ.js.map +0 -1
  672. package/dist/chunk-PNVDQL5Y.cjs.map +0 -1
  673. package/dist/chunk-QLAWEGTZ.cjs.map +0 -1
  674. package/dist/chunk-QN5N3ZVT.cjs.map +0 -1
  675. package/dist/chunk-R3CKCRK3.cjs.map +0 -1
  676. package/dist/chunk-R7TKOQMJ.js.map +0 -1
  677. package/dist/chunk-RP5HQVLD.js.map +0 -1
  678. package/dist/chunk-SXSPMRSV.cjs.map +0 -1
  679. package/dist/chunk-T5ZWI3MC.cjs.map +0 -1
  680. package/dist/chunk-T6QUCG7L.cjs.map +0 -1
  681. package/dist/chunk-TR4V2LHV.cjs.map +0 -1
  682. package/dist/chunk-VYCKUKPA.cjs.map +0 -1
  683. package/dist/chunk-VYHJZVL5.cjs.map +0 -1
  684. package/dist/chunk-W4FV7JBH.js.map +0 -1
  685. package/dist/chunk-X2FR4OIT.js.map +0 -1
  686. package/dist/chunk-XRI6DXPZ.js.map +0 -1
  687. package/dist/chunk-XWCTBGYK.js.map +0 -1
  688. package/dist/chunk-YLQQX5W2.cjs.map +0 -1
  689. package/dist/chunk-YTO5BRBD.cjs.map +0 -1
  690. package/dist/chunk-Z5U2JGEK.cjs.map +0 -1
  691. package/dist/compact-session-6GKIS4SD.cjs +0 -58
  692. package/dist/compact-session-EJ36VH5I.js +0 -21
  693. package/dist/context-4HGPCOH6.cjs +0 -22
  694. package/dist/context-DCECDKWN.js +0 -5
  695. package/dist/cron-DgHJnMAK.d.cts +0 -631
  696. package/dist/cron-DyWQsEG6.d.ts +0 -631
  697. package/dist/executor-3CGPLVJL.js.map +0 -1
  698. package/dist/executor-4SW7QGZ4.cjs.map +0 -1
  699. package/dist/fs-session-store-LIKYT24K.js +0 -10
  700. package/dist/fs-session-store-VXXDIBGM.cjs +0 -19
  701. package/dist/generate-object-E465DX5I.cjs +0 -20
  702. package/dist/generate-object-TVQCW2IZ.js +0 -7
  703. package/dist/index-manager-EA6FGIQG.js +0 -12
  704. package/dist/index-manager-HGGL4DD5.cjs +0 -21
  705. package/dist/inject-session-67SF65FC.cjs +0 -28
  706. package/dist/inject-session-67SF65FC.cjs.map +0 -1
  707. package/dist/inject-session-HO7FYVCX.js.map +0 -1
  708. package/dist/judge-call-GVIJWQVE.cjs +0 -22
  709. package/dist/judge-call-QMKGC2ZK.js +0 -5
  710. package/dist/oauth-transaction-store-7CKHPQRN.cjs +0 -32
  711. package/dist/oauth-transaction-store-W74I6EFD.js +0 -3
  712. package/dist/registry-GC7BQMSV.js +0 -9
  713. package/dist/registry-UBY26R4I.cjs +0 -46
  714. package/dist/session-transcript-SKIRBEJE.js +0 -5
  715. package/dist/session-transcript-TNAJ4O3M.cjs +0 -50
  716. package/dist/stream-object-QMNR3YFF.js +0 -7
  717. package/dist/stream-object-T4DAMNVB.cjs +0 -20
  718. package/dist/subagents-loader-3CXBQWWY.cjs +0 -15
  719. package/dist/subagents-loader-WN2SB6PV.js +0 -6
@@ -17,4 +17,9 @@ export declare const sessions: Map<string, SessionMessage[]>;
17
17
  export declare const hydratedKeys: Set<string>;
18
18
  /** The per-(cwd, agentId) transcript key for cache/hydration bookkeeping. */
19
19
  export declare function transcriptKey(cwd: string, agentId: string): string;
20
+ /**
21
+ * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates
22
+ * from disk. Without this, a compaction only helps after a process restart: the live process keeps
23
+ * sending the full pre-compact history (the cache is read synchronously by every send).
24
+ */
20
25
  export declare function invalidateSessionCache(cwd: string, agentId: string): void;
@@ -12,8 +12,10 @@
12
12
  * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).
13
13
  * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted
14
14
  * atomic writes.
15
- * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap
16
- * and the `submittedBefore` paging idiom.
15
+ * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap.
16
+ * It no longer advertises `submittedBefore` as a way to page past it:
17
+ * the cap is applied to the raw directory listing before any filter, so
18
+ * paging beyond 256 files is not reachable through this interface.
17
19
  * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the
18
20
  * single-process invariant; v0.2 SQLite covers cross-process.
19
21
  *
@@ -26,15 +28,42 @@ export interface TaskStore {
26
28
  update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;
27
29
  get(id: string): Promise<TaskHandle | undefined>;
28
30
  /**
29
- * Returns at most `filter.limit ?? 100` matching handles. JsonFile
30
- * backend hard-caps loaded entries at 256 — callers needing larger
31
- * pages must use `submittedBefore` to walk the timeline.
31
+ * Returns at most `filter.limit ?? 100` matching handles.
32
+ *
33
+ * `JsonFileTaskStore` returns them newest-first and considers every task in its
34
+ * directory, reading at most 256 files concurrently (#362 — that number bounds
35
+ * I/O, not which tasks are visible). Walk past `limit` by passing the oldest
36
+ * `submittedAt` of a page as the next call's `submittedBefore`; the ordering is
37
+ * what makes that a cursor rather than a re-roll of an arbitrary subset.
38
+ * `InMemoryTaskStore` applies the same filters but does not order its result.
32
39
  */
33
40
  list(filter: TaskFilter): Promise<TaskHandle[]>;
34
41
  delete(id: string): Promise<boolean>;
35
42
  /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */
36
43
  evictTerminalOlderThan(epochMs: number): Promise<number>;
37
44
  }
45
+ /**
46
+ * Default `TaskStore` — a plain `Map` living in the current process.
47
+ *
48
+ * Nothing reaches disk and nothing survives the process, so a task recorded here
49
+ * is invisible to a reader in another process (`theokit tasks`). Select it with
50
+ * `getTaskStoreFor({ backend: "memory" })`.
51
+ *
52
+ * How it fails: every id-taking method validates against the task-id grammar
53
+ * (`^[a-z0-9][a-z0-9_-]*$`; reserved `wf-`/`b-`/`cron-` prefixes are permitted
54
+ * here) and throws `InvalidTaskIdError` before touching the map. A missing id is
55
+ * reported by returning `undefined` (`get`, `update`) or `false` (`delete`), never
56
+ * by throwing.
57
+ *
58
+ * Traps:
59
+ * - `insert()` is a `Map.set`: an existing id is overwritten silently, not
60
+ * rejected.
61
+ * - `list()` walks in INSERTION order and stops as soon as `filter.limit ?? 100`
62
+ * matches are collected. It never sorts, so the limit truncates an
63
+ * oldest-first scan rather than returning the most recent tasks.
64
+ * - Nothing evicts on its own; terminal handles accumulate until a caller invokes
65
+ * `evictTerminalOlderThan`.
66
+ */
38
67
  export declare class InMemoryTaskStore implements TaskStore {
39
68
  private readonly map;
40
69
  insert(handle: TaskHandle): Promise<void>;
@@ -44,6 +73,44 @@ export declare class InMemoryTaskStore implements TaskStore {
44
73
  delete(id: string): Promise<boolean>;
45
74
  evictTerminalOlderThan(epochMs: number): Promise<number>;
46
75
  }
76
+ /**
77
+ * Opt-in `TaskStore` that keeps one JSON file per task under `dir`, so another
78
+ * process can read the registry off disk.
79
+ *
80
+ * const store = new JsonFileTaskStore("/var/lib/theokit/tasks");
81
+ *
82
+ * Two calls are synchronous, and both are deliberate: the constructor creates `dir`
83
+ * recursively (`mkdirSync`), and `list()` scans it with `readdirSync` before awaiting
84
+ * anything. Every other operation is async — `get` uses `readFile`, `delete` uses
85
+ * `unlink`, and every write goes through an atomic temp-file-plus-rename.
86
+ *
87
+ * SINGLE-PROCESS ONLY — see the note above. Per-file atomicity does not make
88
+ * `update()` safe: it is a read-modify-write, so two writers that both `get`
89
+ * before either writes lose one of the two mutations. That is true within one
90
+ * process as well as across processes.
91
+ *
92
+ * How it fails:
93
+ * - An invalid id throws `InvalidTaskIdError` BEFORE any path is constructed.
94
+ * That ordering is the path-traversal defence, and it is why ids are validated
95
+ * rather than escaped.
96
+ * - A missing task is `undefined` from `get` and `false` from `delete`.
97
+ * - A file that exists but does not parse is NOT surfaced as an error: `get`
98
+ * writes to the diagnostics channel and returns `undefined`, so a corrupted
99
+ * task also silently vanishes from `list()`.
100
+ * - `list()` returns `[]` when `dir` does not exist; any other `readdir` failure
101
+ * (for example a permission error) throws.
102
+ *
103
+ * Traps:
104
+ * - `list()` reads every task file in the directory (256 at a time) to apply the
105
+ * filter, because `state`, `kind` and `submittedAt` live inside the files. On a
106
+ * large directory that is a lot of I/O for one call; the memory it holds is
107
+ * bounded by `limit`, the time is not.
108
+ * - `list()` is `async`, but its directory scan is not: `readdirSync` blocks the event
109
+ * loop for the whole listing before the first `await`. Only the per-file reads that
110
+ * follow it are concurrent.
111
+ * - Files whose name contains `.tmp` are skipped as orphans of an interrupted
112
+ * write, and nothing ever removes them.
113
+ */
47
114
  export declare class JsonFileTaskStore implements TaskStore {
48
115
  private readonly dir;
49
116
  constructor(dir: string);
@@ -51,6 +118,25 @@ export declare class JsonFileTaskStore implements TaskStore {
51
118
  insert(handle: TaskHandle): Promise<void>;
52
119
  update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;
53
120
  get(id: string): Promise<TaskHandle | undefined>;
121
+ /**
122
+ * Task ids backed by a file in `dir`, in readdir order.
123
+ *
124
+ * EC-8: orphan `.tmp` files left by an interrupted atomic write are skipped, as is any name
125
+ * outside the id grammar. EC-6: a missing directory lists as empty; any other `readdir` failure
126
+ * (a permission error, say) throws rather than being reported as "no tasks".
127
+ */
128
+ private candidateIds;
129
+ /**
130
+ * Read every task in `ids`, handing each loaded handle to `visit`, at most `JSON_LOAD_CAP` file
131
+ * reads in flight.
132
+ *
133
+ * #362 — the cap used to be applied to the directory listing, which made it a bound on WHICH
134
+ * tasks were visible rather than on how much I/O ran at once. Every filter then ran on that
135
+ * arbitrary readdir-ordered prefix. As a concurrency bound it does the job it was named for
136
+ * without deciding what the caller gets to see; the caller's own bound on memory is whatever
137
+ * `visit` chooses to retain.
138
+ */
139
+ private forEachHandle;
54
140
  list(filter: TaskFilter): Promise<TaskHandle[]>;
55
141
  delete(id: string): Promise<boolean>;
56
142
  evictTerminalOlderThan(epochMs: number): Promise<number>;
@@ -1,4 +1,3 @@
1
- export type SpanName = (typeof SPAN_NAMES)[keyof typeof SPAN_NAMES];
2
1
  /** Histogram names emitted by the SDK. M3 #64 closes the wiring-triad pillar-c
3
2
  * gap: tool/LLM durations + LLM token throughput were measured but never emitted. */
4
3
  export declare const HISTOGRAM_NAMES: {
@@ -1,3 +1,17 @@
1
+ /**
2
+ * The subset of the OpenTelemetry `Span` API this SDK calls.
3
+ *
4
+ * Structural, not nominal: a real `@opentelemetry/api` span satisfies it, and so does a test double
5
+ * or a no-op. That is why it is exported — `@theokit/sdk-memory` previously kept a hand-written
6
+ * mirror of this shape, and the two had already drifted (the mirror rejected `undefined` attribute
7
+ * values this one accepts, and declared `end()` without its `endTime` parameter). Import this
8
+ * instead of re-declaring it.
9
+ *
10
+ * Erased at build time, so importing it adds nothing to a bundle and does not require
11
+ * `@opentelemetry/api` to be installed.
12
+ *
13
+ * @public
14
+ */
1
15
  export interface OTelSpan {
2
16
  setAttribute(key: string, value: string | number | boolean): void;
3
17
  setAttributes(attrs: Record<string, string | number | boolean | undefined>): void;
@@ -14,6 +28,30 @@ export interface OTelSpan {
14
28
  };
15
29
  isRecording(): boolean;
16
30
  }
31
+ /**
32
+ * Telemetry handle returned by {@link createTelemetry}. Callers use this to
33
+ * start spans, add events, etc. When telemetry is disabled OR OTel is not
34
+ * installed, every method is a safe no-op.
35
+ *
36
+ */
37
+ export interface TelemetryHandle {
38
+ readonly enabled: boolean;
39
+ readonly includeContent: boolean;
40
+ /** Start a span. Returns a no-op span if telemetry is disabled. */
41
+ startSpan(name: string, attrs?: Record<string, string | number | boolean>): OTelSpan;
42
+ /** Start a child span nested under `parent` (M3 #64). `undefined` parent →
43
+ * a root span (parentless callers, or telemetry with no run span). */
44
+ startChildSpan(parent: OTelSpan | undefined, name: string, attrs?: Record<string, string | number | boolean>): OTelSpan;
45
+ /**
46
+ * Record a histogram observation. T0.1 ships
47
+ * `theokit_memory_recall_duration_ms`; downstream tasks add more.
48
+ * No-op when telemetry is disabled or when `@opentelemetry/api`'s metrics
49
+ * namespace is unavailable. ADR D34 — exporter errors are swallowed by `safe()`.
50
+ */
51
+ recordHistogram(name: string, valueMs: number, attrs?: Record<string, string | number | boolean>): void;
52
+ /** End all open spans on this handle (best-effort, used by Agent.dispose). */
53
+ endAll(): void;
54
+ }
17
55
  export declare const NOOP_SPAN: OTelSpan;
18
56
  /** Exported for tests — resets the OTel cache and the warning-once latch. */
19
57
  export declare function _resetTelemetryCacheForTests(): void;
@@ -24,6 +24,24 @@ export interface JobQueueOptions {
24
24
  */
25
25
  maxConcurrency?: number;
26
26
  }
27
+ /**
28
+ * An in-process queue of background jobs with status tracking, cancellation, and an optional
29
+ * concurrency bound.
30
+ *
31
+ * `enqueue` returns a job id immediately and never throws for the job's own failure: a synchronous
32
+ * throw inside the function becomes a rejection, and a rejection becomes `status: "failed"` with
33
+ * the message on `job.error`. Poll `getJob(id)` or `list()` for outcomes — there is no completion
34
+ * event and no promise to await.
35
+ *
36
+ * Cancellation is COOPERATIVE. `cancel` aborts the `AbortSignal` handed to the job function and
37
+ * flips the status, but a function that ignores the signal keeps running to completion; its result
38
+ * is then discarded, because a cancelled job never leaves the cancelled state. The concurrency slot
39
+ * of a running job is freed at cancel time rather than when it eventually settles, so a job that
40
+ * never settles cannot deadlock a bounded queue.
41
+ *
42
+ * State lives entirely in memory and grows without bound — nothing evicts finished jobs. This is a
43
+ * queue for one process, not a durable one.
44
+ */
27
45
  export declare class JobQueue {
28
46
  #private;
29
47
  private jobs;
@@ -0,0 +1,6 @@
1
+ export { JudgeCredentialError, composeJudgePrompt, judgeCallImpl } from './chunk-T73NA43R.js';
2
+ import './chunk-IDCKSLYH.js';
3
+ import './chunk-T7XEKOVW.js';
4
+ import './chunk-T7O6K6PX.js';
5
+ //# sourceMappingURL=judge-call-DWHAJATE.js.map
6
+ //# sourceMappingURL=judge-call-DWHAJATE.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"judge-call-QMKGC2ZK.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"judge-call-DWHAJATE.js"}
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ var chunkGWC3HADL_cjs = require('./chunk-GWC3HADL.cjs');
4
+ require('./chunk-K3FW2XZD.cjs');
5
+ require('./chunk-JTB5Q42C.cjs');
6
+ require('./chunk-NUKRL3I6.cjs');
7
+
8
+
9
+
10
+ Object.defineProperty(exports, "JudgeCredentialError", {
11
+ enumerable: true,
12
+ get: function () { return chunkGWC3HADL_cjs.JudgeCredentialError; }
13
+ });
14
+ Object.defineProperty(exports, "composeJudgePrompt", {
15
+ enumerable: true,
16
+ get: function () { return chunkGWC3HADL_cjs.composeJudgePrompt; }
17
+ });
18
+ Object.defineProperty(exports, "judgeCallImpl", {
19
+ enumerable: true,
20
+ get: function () { return chunkGWC3HADL_cjs.judgeCallImpl; }
21
+ });
22
+ //# sourceMappingURL=judge-call-EGYRC2RE.cjs.map
23
+ //# sourceMappingURL=judge-call-EGYRC2RE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"judge-call-GVIJWQVE.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"judge-call-EGYRC2RE.cjs"}
package/dist/mcp-auth.cjs CHANGED
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunk2CFEET3Y_cjs = require('./chunk-2CFEET3Y.cjs');
4
- var chunkNUEL6RCZ_cjs = require('./chunk-NUEL6RCZ.cjs');
5
- var chunk2YGIBOUH_cjs = require('./chunk-2YGIBOUH.cjs');
6
- var chunkSXSPMRSV_cjs = require('./chunk-SXSPMRSV.cjs');
3
+ var chunkI6TGFUCO_cjs = require('./chunk-I6TGFUCO.cjs');
4
+ var chunkBVZW2B5V_cjs = require('./chunk-BVZW2B5V.cjs');
5
+ var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
6
+ require('./chunk-JTB5Q42C.cjs');
7
+ var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
7
8
  var crypto = require('crypto');
8
9
  var http = require('http');
9
10
  var promises = require('readline/promises');
@@ -14,12 +15,23 @@ var path = require('path');
14
15
 
15
16
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
17
  var KEYTAR_SERVICE = "theokit-mcp";
17
- var FILE_PATH = path.join(os.homedir(), ".theokit", "mcp-tokens.json");
18
- function ensurePrivateStoreDir() {
19
- const dir = path.dirname(FILE_PATH);
18
+ function storeFilePath() {
19
+ return storeLocation().file;
20
+ }
21
+ function storeLocation() {
22
+ const override = process.env.THEOKIT_HOME?.trim();
23
+ if (override !== void 0 && override.length > 0) {
24
+ return { dir: override, file: path.join(override, "mcp-tokens.json"), ours: false };
25
+ }
26
+ const fromEnv = process.platform === "win32" ? process.env.USERPROFILE?.trim() : process.env.HOME?.trim();
27
+ const home = fromEnv !== void 0 && fromEnv.length > 0 ? fromEnv : os.homedir();
28
+ const dir = path.join(home, ".theokit");
29
+ return { dir, file: path.join(dir, "mcp-tokens.json"), ours: true };
30
+ }
31
+ function ensurePrivateStoreDir({ dir, ours }) {
20
32
  try {
21
33
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
22
- fs.chmodSync(dir, 448);
34
+ if (ours) fs.chmodSync(dir, 448);
23
35
  } catch {
24
36
  }
25
37
  }
@@ -32,8 +44,9 @@ function tryRequireKeytar() {
32
44
  cachedKeytar = r("keytar");
33
45
  } catch {
34
46
  if (!keytarWarned) {
35
- chunkSXSPMRSV_cjs.diag(
36
- "[theokit-sdk] keytar not installed; MCP OAuth tokens will be stored in ~/.theokit/mcp-tokens.json (chmod 600 where POSIX). Install `keytar` for OS keychain storage.\n"
47
+ chunkNUKRL3I6_cjs.diag(
48
+ `[theokit-sdk] keytar not installed; MCP OAuth tokens will be stored in ${storeFilePath()} (chmod 600 where POSIX). Install \`keytar\` for OS keychain storage.
49
+ `
37
50
  );
38
51
  keytarWarned = true;
39
52
  }
@@ -49,19 +62,21 @@ async function setTokens(serverName, tokens) {
49
62
  await kt.setPassword(KEYTAR_SERVICE, serverName, payload);
50
63
  return;
51
64
  }
52
- ensurePrivateStoreDir();
65
+ const location = storeLocation();
66
+ const filePath = location.file;
67
+ ensurePrivateStoreDir(location);
53
68
  let allTokens = {};
54
- if (fs.existsSync(FILE_PATH)) {
69
+ if (fs.existsSync(filePath)) {
55
70
  try {
56
- allTokens = JSON.parse(fs.readFileSync(FILE_PATH, "utf8"));
71
+ allTokens = JSON.parse(fs.readFileSync(filePath, "utf8"));
57
72
  } catch {
58
73
  allTokens = {};
59
74
  }
60
75
  }
61
76
  allTokens[serverName] = tokens;
62
- await chunk2CFEET3Y_cjs.atomicWriteJson(FILE_PATH, allTokens);
77
+ await chunkI6TGFUCO_cjs.atomicWriteJson(filePath, allTokens);
63
78
  try {
64
- fs.chmodSync(FILE_PATH, 384);
79
+ fs.chmodSync(filePath, 384);
65
80
  } catch {
66
81
  }
67
82
  }
@@ -76,10 +91,11 @@ async function getTokens(serverName) {
76
91
  return void 0;
77
92
  }
78
93
  }
79
- if (!fs.existsSync(FILE_PATH)) return void 0;
80
- chunkNUEL6RCZ_cjs.assertSecureModes(path.dirname(FILE_PATH), FILE_PATH);
94
+ const filePath = storeFilePath();
95
+ if (!fs.existsSync(filePath)) return void 0;
96
+ chunkBVZW2B5V_cjs.assertSecureModes(path.dirname(filePath), filePath);
81
97
  try {
82
- const all = JSON.parse(fs.readFileSync(FILE_PATH, "utf8"));
98
+ const all = JSON.parse(fs.readFileSync(filePath, "utf8"));
83
99
  return all[serverName];
84
100
  } catch {
85
101
  return void 0;
@@ -118,7 +134,7 @@ async function refreshAccessToken(serverName, clientId, refreshToken, oauth) {
118
134
  body: body.toString()
119
135
  });
120
136
  if (!response.ok) {
121
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`OAuth refresh failed: HTTP ${response.status}`, {
137
+ throw new chunkK3FW2XZD_cjs.ConfigurationError(`OAuth refresh failed: HTTP ${response.status}`, {
122
138
  code: "oauth_refresh_failed"
123
139
  });
124
140
  }
@@ -164,7 +180,7 @@ async function runPkceFlow(serverName, clientId, scopes, oauth) {
164
180
  authUrl.searchParams.set("code_challenge", challenge);
165
181
  authUrl.searchParams.set("code_challenge_method", "S256");
166
182
  authUrl.searchParams.set("state", state);
167
- chunkSXSPMRSV_cjs.diag(
183
+ chunkNUKRL3I6_cjs.diag(
168
184
  `
169
185
  [theokit-sdk] OAuth required for MCP server "${serverName}".
170
186
  Open this URL to authenticate:
@@ -174,7 +190,7 @@ Open this URL to authenticate:
174
190
  );
175
191
  const { code, state: returnedState } = await codeWaiter;
176
192
  if (returnedState !== state) {
177
- throw new chunk2YGIBOUH_cjs.ConfigurationError(
193
+ throw new chunkK3FW2XZD_cjs.ConfigurationError(
178
194
  "OAuth state mismatch \u2014 possible CSRF attempt; aborting token exchange.",
179
195
  { code: "oauth_state_mismatch" }
180
196
  );
@@ -193,7 +209,7 @@ Open this URL to authenticate:
193
209
  });
194
210
  if (!response.ok) {
195
211
  const errText = await response.text();
196
- throw new chunk2YGIBOUH_cjs.ConfigurationError(
212
+ throw new chunkK3FW2XZD_cjs.ConfigurationError(
197
213
  `OAuth token exchange failed: HTTP ${response.status}: ${errText.slice(0, 200)}`,
198
214
  { code: "oauth_token_exchange_failed" }
199
215
  );
@@ -239,7 +255,7 @@ async function openLocalhostCallback(expectedState, timeoutMs) {
239
255
  });
240
256
  server.listen(0, "127.0.0.1");
241
257
  const timeoutHandle = setTimeout(() => {
242
- rejectCode?.(new chunk2YGIBOUH_cjs.ConfigurationError("OAuth flow timed out", { code: "oauth_timeout" }));
258
+ rejectCode?.(new chunkK3FW2XZD_cjs.ConfigurationError("OAuth flow timed out", { code: "oauth_timeout" }));
243
259
  }, timeoutMs);
244
260
  await new Promise((r) => {
245
261
  if (server.listening) r();
@@ -248,7 +264,7 @@ async function openLocalhostCallback(expectedState, timeoutMs) {
248
264
  const address = server.address();
249
265
  if (typeof address !== "object" || address === null) {
250
266
  server.close();
251
- throw new chunk2YGIBOUH_cjs.ConfigurationError("OAuth localhost callback failed to bind", {
267
+ throw new chunkK3FW2XZD_cjs.ConfigurationError("OAuth localhost callback failed to bind", {
252
268
  code: "oauth_bind_failed"
253
269
  });
254
270
  }
@@ -284,7 +300,7 @@ async function readCodeFromStdin(expectedState, timeoutMs) {
284
300
  }).catch(reject);
285
301
  setTimeout(() => {
286
302
  rl.close();
287
- reject(new chunk2YGIBOUH_cjs.ConfigurationError("OAuth manual input timed out", { code: "oauth_timeout" }));
303
+ reject(new chunkK3FW2XZD_cjs.ConfigurationError("OAuth manual input timed out", { code: "oauth_timeout" }));
288
304
  }, timeoutMs);
289
305
  });
290
306
  return promise;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/mcp/token-storage.ts","../src/internal/mcp/oauth.ts"],"names":["join","homedir","dirname","mkdirSync","chmodSync","createRequire","diag","existsSync","readFileSync","atomicWriteJson","assertSecureModes","randomBytes","createHash","ConfigurationError","createServer","createInterface"],"mappings":";;;;;;;;;;;;;;;AAqBA,IAAM,cAAA,GAAiB,aAAA;AACvB,IAAM,SAAA,GAAYA,SAAA,CAAKC,UAAA,EAAQ,EAAG,YAAY,iBAAiB,CAAA;AAgB/D,SAAS,qBAAA,GAA8B;AACrC,EAAA,MAAM,GAAA,GAAMC,aAAQ,SAAS,CAAA;AAC7B,EAAA,IAAI;AACF,IAAAC,YAAA,CAAU,KAAK,EAAE,SAA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AAa,GAAA,CAAI,OAAO,CAAA,IAAK,EAAA;AAClD,UAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,YAAA,OAAA,CAAQ,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AACvB,YAAA;AAAA,UACF;AAAA,QACF,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAIA,MAAA,OAAA,CAAQ,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAO,eAAe,CAAA;AAAA,IACjD,CAAC,CAAA,CACA,KAAA,CAAM,MAAM,CAAA;AACf,IAAA,UAAA,CAAW,MAAM;AACf,MAAA,EAAA,CAAG,KAAA,EAAM;AACT,MAAA,MAAA,CAAO,IAAIF,oCAAA,CAAmB,8BAAA,EAAgC,EAAE,IAAA,EAAM,eAAA,EAAiB,CAAC,CAAA;AAAA,IAC1F,GAAG,SAAS,CAAA;AAAA,EACd,CAAC,CAAA;AACD,EAAA,OAAO,OAAA;AACT","file":"mcp-auth.cjs","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { assertSecureModes } from \"../auth/credential-store.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"../persistence/atomic-write.js\";\n\n/**\n * OAuth token bundle persisted per MCP server. See ADR D41.\n *\n * @internal\n */\nexport interface OAuthTokens {\n accessToken: string;\n refreshToken?: string;\n expiresAt: number; // ms epoch\n scope?: string;\n obtainedAt: number; // ms epoch\n}\n\nconst KEYTAR_SERVICE = \"theokit-mcp\";\nconst FILE_PATH = join(homedir(), \".theokit\", \"mcp-tokens.json\");\n\n/**\n * Make the directory private BEFORE anything is written into it.\n *\n * `atomicWriteJson` auto-creates the parent with a bare recursive `mkdir`, so under the common umask\n * 002 `~/.theokit` was born 0775 — and the `chmod 600` applied to the file afterwards protects the\n * wrong thing. Write permission on a DIRECTORY is permission to unlink and recreate its contents, so\n * a 0600 file inside a group-writable directory can be replaced wholesale by another local user. The\n * secret here is a REFRESH TOKEN: replacing it swaps which account the agent authenticates as.\n *\n * The `chmod` is unconditional and not a fallback for the `mkdir` mode: `mkdir`'s mode applies only\n * at CREATION, so every machine that already ran an older build has the loose directory sitting\n * there, and a fix that only covers fresh installs does not reach the population that has the\n * problem.\n */\nfunction ensurePrivateStoreDir(): void {\n const dir = dirname(FILE_PATH);\n try {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n } catch {\n // Windows: chmod is a no-op and the mode argument is meaningless. Same posture as the file\n // chmod below — documented in ADR D41 / EC-14.\n }\n}\n\ninterface KeytarLike {\n setPassword: (service: string, account: string, password: string) => Promise<void>;\n getPassword: (service: string, account: string) => Promise<string | null>;\n deletePassword: (service: string, account: string) => Promise<boolean>;\n}\n\nlet keytarWarned = false;\nlet cachedKeytar: KeytarLike | undefined | null;\nfunction tryRequireKeytar(): KeytarLike | null {\n if (cachedKeytar !== undefined) return cachedKeytar;\n try {\n const r = createRequire(import.meta.url);\n cachedKeytar = r(\"keytar\") as KeytarLike;\n } catch {\n if (!keytarWarned) {\n diag(\n \"[theokit-sdk] keytar not installed; MCP OAuth tokens will be stored in ~/.theokit/mcp-tokens.json (chmod 600 where POSIX). Install `keytar` for OS keychain storage.\\n\",\n );\n keytarWarned = true;\n }\n cachedKeytar = null;\n }\n return cachedKeytar;\n}\n\n// EC-9 (race): serialize concurrent refreshes per server. Each key maps to\n// the in-flight refresh Promise; subsequent callers await the same promise.\nconst inflightRefresh = new Map<string, Promise<OAuthTokens>>();\n\n/**\n * Persist tokens for `serverName`. Tries keychain first, falls back to file\n * with chmod 600 (POSIX). Idempotent.\n *\n * @internal\n */\nexport async function setTokens(serverName: string, tokens: OAuthTokens): Promise<void> {\n const kt = tryRequireKeytar();\n const payload = JSON.stringify(tokens);\n if (kt !== null && kt !== undefined) {\n await kt.setPassword(KEYTAR_SERVICE, serverName, payload);\n return;\n }\n // File fallback. The directory is locked down first — see `ensurePrivateStoreDir`.\n ensurePrivateStoreDir();\n let allTokens: Record<string, OAuthTokens> = {};\n if (existsSync(FILE_PATH)) {\n try {\n allTokens = JSON.parse(readFileSync(FILE_PATH, \"utf8\")) as Record<string, OAuthTokens>;\n } catch {\n // corrupt file — start fresh\n allTokens = {};\n }\n }\n allTokens[serverName] = tokens;\n await atomicWriteJson(FILE_PATH, allTokens);\n try {\n chmodSync(FILE_PATH, 0o600);\n } catch {\n // Windows: chmod is a no-op. Documented in ADR D41 / EC-14.\n }\n}\n\n/**\n * Retrieve tokens for `serverName`. Returns undefined if absent.\n *\n * @internal\n */\nexport async function getTokens(serverName: string): Promise<OAuthTokens | undefined> {\n const kt = tryRequireKeytar();\n if (kt !== null && kt !== undefined) {\n const value = await kt.getPassword(KEYTAR_SERVICE, serverName);\n if (typeof value !== \"string\") return undefined;\n try {\n return JSON.parse(value) as OAuthTokens;\n } catch {\n return undefined;\n }\n }\n if (!existsSync(FILE_PATH)) return undefined;\n // The same gate the credential file gets, and deliberately the same implementation rather than a\n // second one: a refresh token is a credential, and `assertSecureModes` already carries the attack\n // it defends against in its docstring. It is called OUTSIDE the try/catch on purpose — the catch\n // below exists to treat a corrupt file as absent, and letting it swallow this would turn \"someone\n // else can replace your token\" into a silent `undefined`, which reads as \"not logged in\".\n assertSecureModes(dirname(FILE_PATH), FILE_PATH);\n try {\n const all = JSON.parse(readFileSync(FILE_PATH, \"utf8\")) as Record<string, OAuthTokens>;\n return all[serverName];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serialize concurrent refresh attempts per server (EC-9). If a refresh is\n * already in flight for the same `serverName`, the second caller awaits\n * the same Promise.\n *\n * @internal\n */\nexport function lockedRefresh(\n serverName: string,\n refreshFn: () => Promise<OAuthTokens>,\n): Promise<OAuthTokens> {\n const existing = inflightRefresh.get(serverName);\n if (existing !== undefined) return existing;\n const promise = (async () => {\n try {\n return await refreshFn();\n } finally {\n inflightRefresh.delete(serverName);\n }\n })();\n inflightRefresh.set(serverName, promise);\n return promise;\n}\n\n/**\n * Reset all cached state. Test-only helper.\n *\n * @internal\n */\nexport function _resetForTests(): void {\n inflightRefresh.clear();\n cachedKeytar = undefined;\n keytarWarned = false;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { createInterface } from \"node:readline/promises\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { McpOAuthConfig } from \"../../types/mcp.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type OAuthTokens, setTokens } from \"./token-storage.js\";\n\n/**\n * OAuth 2.1 PKCE flow runner for MCP HTTP servers. See ADR D41.\n *\n * @internal\n */\n\n/**\n * Generate a random base64url-encoded string. Used for both code_verifier\n * (43-128 chars) and state (CSRF protection).\n */\nfunction base64url(n: number): string {\n return randomBytes(n).toString(\"base64url\");\n}\n\n/**\n * Compute PKCE code_challenge = base64url(SHA256(code_verifier)).\n */\nfunction challengeFor(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/**\n * Refresh an access token using `refresh_token`. Throws on failure.\n *\n * @internal\n */\nexport async function refreshAccessToken(\n serverName: string,\n clientId: string,\n refreshToken: string,\n oauth: McpOAuthConfig,\n): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: clientId,\n });\n const response = await fetch(oauth.tokenEndpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n });\n if (!response.ok) {\n throw new ConfigurationError(`OAuth refresh failed: HTTP ${response.status}`, {\n code: \"oauth_refresh_failed\",\n });\n }\n const data = (await response.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n const obtainedAt = Date.now();\n const tokens: OAuthTokens = {\n accessToken: data.access_token,\n refreshToken: data.refresh_token ?? refreshToken,\n // EC-10: default conservative 3600s if expires_in missing.\n expiresAt: obtainedAt + (data.expires_in ?? 3600) * 1000,\n obtainedAt,\n ...(data.scope !== undefined ? { scope: data.scope } : {}),\n };\n await setTokens(serverName, tokens);\n return tokens;\n}\n\n/**\n * Run the full PKCE flow. Generates verifier+challenge+state, opens the\n * authorization URL (browser or manual print), waits for the callback\n * (localhost or stdin), exchanges code for tokens.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: PKCE flow is a linear protocol step (verifier → challenge → state → URL → wait → exchange); refactoring fragments the RFC 7636 narrative.\nexport async function runPkceFlow(\n serverName: string,\n clientId: string,\n scopes: string[] | undefined,\n oauth: McpOAuthConfig,\n): Promise<OAuthTokens> {\n const verifier = base64url(48);\n const challenge = challengeFor(verifier);\n const state = base64url(16);\n const timeoutMs = oauth.timeoutMs ?? 300_000;\n\n let redirectUri: string;\n let codeWaiter: Promise<{ code: string; state: string }>;\n let cleanup: () => void = () => {};\n\n if (oauth.redirectMode === \"localhost\") {\n const result = await openLocalhostCallback(state, timeoutMs);\n redirectUri = result.redirectUri;\n codeWaiter = result.waitFor;\n cleanup = result.close;\n } else {\n redirectUri = \"urn:ietf:wg:oauth:2.0:oob\";\n codeWaiter = readCodeFromStdin(state, timeoutMs);\n }\n\n try {\n const authUrl = new URL(oauth.authorizationEndpoint);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"client_id\", clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUri);\n if (scopes !== undefined && scopes.length > 0) {\n authUrl.searchParams.set(\"scope\", scopes.join(\" \"));\n }\n authUrl.searchParams.set(\"code_challenge\", challenge);\n authUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n authUrl.searchParams.set(\"state\", state);\n\n diag(\n `\\n[theokit-sdk] OAuth required for MCP server \"${serverName}\".\\n` +\n `Open this URL to authenticate:\\n ${authUrl.toString()}\\n\\n`,\n );\n\n const { code, state: returnedState } = await codeWaiter;\n // EC-2 MUST FIX: validate state.\n if (returnedState !== state) {\n throw new ConfigurationError(\n \"OAuth state mismatch — possible CSRF attempt; aborting token exchange.\",\n { code: \"oauth_state_mismatch\" },\n );\n }\n\n // Exchange code for tokens.\n const tokenBody = new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n client_id: clientId,\n code_verifier: verifier,\n redirect_uri: redirectUri,\n });\n const response = await fetch(oauth.tokenEndpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: tokenBody.toString(),\n });\n if (!response.ok) {\n const errText = await response.text();\n throw new ConfigurationError(\n `OAuth token exchange failed: HTTP ${response.status}: ${errText.slice(0, 200)}`,\n { code: \"oauth_token_exchange_failed\" },\n );\n }\n const data = (await response.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n const obtainedAt = Date.now();\n return {\n accessToken: data.access_token,\n ...(data.refresh_token !== undefined ? { refreshToken: data.refresh_token } : {}),\n // EC-10: default 3600s when expires_in absent.\n expiresAt: obtainedAt + (data.expires_in ?? 3600) * 1000,\n obtainedAt,\n ...(data.scope !== undefined ? { scope: data.scope } : {}),\n };\n } finally {\n cleanup();\n }\n}\n\n/**\n * Start a localhost HTTP server on a free port; return the redirect URI,\n * a promise that resolves with the code+state from the first valid request,\n * and a close handle.\n *\n * @internal\n */\nasync function openLocalhostCallback(\n expectedState: string,\n timeoutMs: number,\n): Promise<{\n redirectUri: string;\n waitFor: Promise<{ code: string; state: string }>;\n close: () => void;\n}> {\n let resolveCode: ((value: { code: string; state: string }) => void) | undefined;\n let rejectCode: ((reason: unknown) => void) | undefined;\n const waitFor = new Promise<{ code: string; state: string }>((res, rej) => {\n resolveCode = res;\n rejectCode = rej;\n });\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n if (typeof code !== \"string\" || typeof state !== \"string\") {\n res.statusCode = 400;\n res.end(\"Missing code or state\");\n return;\n }\n // EC-2: state must match the one we generated. We DO NOT trust any\n // localhost GET — only the one carrying our exact state.\n if (state !== expectedState) {\n res.statusCode = 400;\n res.end(\"State mismatch — request rejected.\");\n return;\n }\n res.statusCode = 200;\n res.end(\"Authentication successful. You can close this tab and return to the terminal.\");\n resolveCode?.({ code, state });\n });\n server.listen(0, \"127.0.0.1\");\n const timeoutHandle = setTimeout(() => {\n rejectCode?.(new ConfigurationError(\"OAuth flow timed out\", { code: \"oauth_timeout\" }));\n }, timeoutMs);\n // Wait for server.listen to bind so we can read the port.\n await new Promise<void>((r) => {\n if (server.listening) r();\n else server.once(\"listening\", () => r());\n });\n const address = server.address();\n if (typeof address !== \"object\" || address === null) {\n server.close();\n throw new ConfigurationError(\"OAuth localhost callback failed to bind\", {\n code: \"oauth_bind_failed\",\n });\n }\n const port = address.port;\n return {\n redirectUri: `http://127.0.0.1:${port}/callback`,\n waitFor,\n close: () => {\n clearTimeout(timeoutHandle);\n server.close();\n },\n };\n}\n\n/**\n * Read `code` (and `state`) from stdin (manual mode). User pastes the\n * full callback URL or just the code value.\n *\n * @internal\n */\nasync function readCodeFromStdin(\n expectedState: string,\n timeoutMs: number,\n): Promise<{ code: string; state: string }> {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const promise = new Promise<{ code: string; state: string }>((resolve, reject) => {\n rl.question(\"Paste the full callback URL (or just the code): \")\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stdin reader handles 2 input formats (full URL vs raw code) inline; splitting fragments the manual-mode UX.\n .then((answer) => {\n rl.close();\n const trimmed = answer.trim();\n // Try to parse as URL first.\n if (trimmed.includes(\"?\")) {\n try {\n const parsed = new URL(trimmed);\n const code = parsed.searchParams.get(\"code\");\n const state = parsed.searchParams.get(\"state\") ?? \"\";\n if (typeof code === \"string\") {\n resolve({ code, state });\n return;\n }\n } catch {\n // not a URL — fall through\n }\n }\n // Treat the entire input as the code. State validation will fail\n // unless the user also provided state — but in manual mode they\n // typically paste the URL with state baked in.\n resolve({ code: trimmed, state: expectedState });\n })\n .catch(reject);\n setTimeout(() => {\n rl.close();\n reject(new ConfigurationError(\"OAuth manual input timed out\", { code: \"oauth_timeout\" }));\n }, timeoutMs);\n });\n return promise;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/mcp/token-storage.ts","../src/internal/mcp/oauth.ts"],"names":["join","homedir","mkdirSync","chmodSync","createRequire","diag","existsSync","readFileSync","atomicWriteJson","assertSecureModes","dirname","randomBytes","createHash","ConfigurationError","createServer","createInterface"],"mappings":";;;;;;;;;;;;;;;;AA2CA,IAAM,cAAA,GAAiB,aAAA;AAgGvB,SAAS,aAAA,GAAwB;AAC/B,EAAA,OAAO,eAAc,CAAE,IAAA;AACzB;AAwBA,SAAS,aAAA,GAA+B;AACtC,EAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,YAAA,EAAc,IAAA,EAAK;AAChD,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,EAAG;AACjD,IAAA,OAAO,EAAE,KAAK,QAAA,EAAU,IAAA,EAAMA,UAAK,QAAA,EAAU,iBAAiB,CAAA,EAAG,IAAA,EAAM,KAAA,EAAM;AAAA,EAC/E;AAEA,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,QAAA,KAAa,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,WAAA,EAAa,IAAA,EAAK,GAAI,OAAA,CAAQ,GAAA,CAAI,IAAA,EAAM,IAAA,EAAK;AAC1F,EAAA,MAAM,OAAO,OAAA,KAAY,MAAA,IAAa,QAAQ,MAAA,GAAS,CAAA,GAAI,UAAUC,UAAA,EAAQ;AAC7E,EAAA,MAAM,GAAA,GAAMD,SAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AACjC,EAAA,OAAO,EAAE,KAAK,IAAA,EAAMA,SAAA,CAAK,KAAK,iBAAiB,CAAA,EAAG,MAAM,IAAA,EAAK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AG,KAAA,EAAM;AACT,MAAA,MAAM,OAAA,GAAU,OAAO,IAAA,EAAK;AAE5B,MAAA,IAAI,OAAA,CAAQ,QAAA,CAAS,GAAG,CAAA,EAAG;AACzB,QAAA,IAAI;AACF,UAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAO,CAAA;AAC9B,UAAA,MAAM,IAAA,GAAO,MAAA,CAAO,YAAA,CAAa,GAAA,CAAI,MAAM,CAAA;AAC3C,UAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,YAAA,CAAa,GAAA,CAAI,OAAO,CAAA,IAAK,EAAA;AAClD,UAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,YAAA,OAAA,CAAQ,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AACvB,YAAA;AAAA,UACF;AAAA,QACF,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAIA,MAAA,OAAA,CAAQ,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAO,eAAe,CAAA;AAAA,IACjD,CAAC,CAAA,CACA,KAAA,CAAM,MAAM,CAAA;AACf,IAAA,UAAA,CAAW,MAAM;AACf,MAAA,EAAA,CAAG,KAAA,EAAM;AACT,MAAA,MAAA,CAAO,IAAIF,oCAAA,CAAmB,8BAAA,EAAgC,EAAE,IAAA,EAAM,eAAA,EAAiB,CAAC,CAAA;AAAA,IAC1F,GAAG,SAAS,CAAA;AAAA,EACd,CAAC,CAAA;AACD,EAAA,OAAO,OAAA;AACT","file":"mcp-auth.cjs","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { assertSecureModes } from \"../auth/credential-store.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"../persistence/atomic-write.js\";\n\n/**\n * The OAuth tokens held for one MCP server. See ADR D41.\n *\n * Persisted per server name by `setTokens` and returned unchanged by `getTokens`. Where it lands\n * depends on what is installed: `keytar` puts the serialized bundle in the OS keychain, and\n * without it the bundle is written to a JSON file at mode 0600 inside a 0700 directory — in\n * PLAINTEXT, keyed by server name alongside every other server's tokens. Nothing here encrypts it.\n *\n * `refreshToken` is the field that matters most and the field that is optional. When present it\n * outlives `accessToken` and can mint new ones, so a leaked store is a persistent compromise of\n * the account rather than a temporary one. When absent, an expired access token means re-running\n * the authorization flow.\n *\n * `expiresAt` and `obtainedAt` are both epoch milliseconds and both describe the ACCESS token —\n * when it stops working, and when this bundle was issued. Nothing records when the refresh token\n * expires, so a refresh rejected because the grant itself lapsed is only discovered at the token\n * endpoint.\n *\n * The value is not validated on read: whatever JSON was stored is cast to this shape, so a\n * hand-edited or truncated store yields an object whose fields may be missing rather than an\n * error.\n *\n * `scope` records what the token was granted, as the server returned it. It is stored for\n * inspection; nothing in this module enforces it.\n *\n * @public — re-exported from `@theokit/sdk/mcp-auth`, and therefore under semver.\n */\nexport interface OAuthTokens {\n accessToken: string;\n refreshToken?: string;\n expiresAt: number; // ms epoch\n scope?: string;\n obtainedAt: number; // ms epoch\n}\n\nconst KEYTAR_SERVICE = \"theokit-mcp\";\n/**\n * Resolve the store path on every call instead of binding it once at module load.\n *\n * This used to be `const FILE_PATH = join(homedir(), ...)`. A module-level constant captures\n * ambient global state at IMPORT, so the store kept writing to whichever HOME was set when the\n * module first loaded and never noticed a later change. In production that is invisible, because\n * HOME does not move mid-process — but it made the module's correctness a property of *when* it was\n * imported, which is not a property a credential store should have.\n *\n * The environment variable is read FIRST and `homedir()` is the fallback, and the variable READ IS\n * PER PLATFORM because `os.homedir()` itself is: on POSIX it prefers `$HOME`, on Windows it reads\n * `USERPROFILE` and never consults `HOME`. Mirroring that split is what keeps this a pure\n * binding-time fix instead of a behaviour change.\n *\n * A previous revision read `process.env.HOME` on every platform. Review caught it: under Git Bash,\n * MSYS2 or Cygwin `HOME` IS set, to a POSIX-shaped path, and `path.win32.join(\"/c/Users/N\", ...)`\n * yields `\\c\\Users\\N\\.theokit\\...` where `USERPROFILE` would have given\n * `C:\\Users\\N\\.theokit\\...`. That would have hidden every existing token on those setups and\n * written a new credential file to a drive-relative path. It was published as \"on Windows HOME is\n * typically unset\" — an untested platform claim, and the same defect class it was written to fix.\n *\n * Why read the env at all: inside a worker thread `process.env` is a JS-level copy while\n * `os.homedir()` is a native call reading the real process environment, so code that moves the home\n * inside a worker is invisible to `homedir()`. Reading the env first makes this module independent\n * of the execution model, not just of the import moment.\n *\n * The empty/whitespace guard falls through to `homedir()`, and it buys LESS than two earlier\n * revisions of this comment claimed. Measured on POSIX: `homedir()` with `HOME=\"\"` returns `\"\"` and\n * with `HOME=\" \"` returns `\" \"` untrimmed, so the fallback hands back the same value the guard\n * rejected — close to a no-op. `path.join(\"\", \".theokit\", ...)` yields a CWD-RELATIVE\n * `.theokit/mcp-tokens.json`, never `/.theokit`; an earlier revision named that as the hazard and it\n * does not exist.\n *\n * On Windows it is UNKNOWN rather than load-bearing: the fallback reads the same `USERPROFILE`, so\n * whether the guard changes anything depends on whether an empty variable is reported as absent\n * there, which is untested and not asserted here. The one case where the guard is genuinely\n * load-bearing is a worker thread whose environment copy was blanked.\n *\n * The OS is UNTESTED here: every POSIX-mode test in `mcp-token-store-modes.test.ts` is\n * `it.skipIf(!POSIX)` and CI runs ubuntu only, so nothing exercises real Windows chmod semantics or\n * libuv's `USERPROFILE` lookup. The BRANCH SELECTION is tested — `process.platform` is spy-able, and\n * `test_the_store_reads_USERPROFILE_and_not_HOME_on_win32` pins all three legs.\n *\n * The split is reasoned from `os.homedir()`'s documented per-platform source. A previous revision\n * also cited `internal/runtime/fixtures/fixture-mode.ts:119` as support; that citation was WRONG and\n * is removed rather than quietly dropped. That line reads `process.env.HOME ?? process.env.USERPROFILE`\n * — HOME-first on every platform, which is the exact shape this split exists to avoid. It supports\n * the rejected alternative, not this one. (That the two modules now resolve different homes under\n * Git Bash is real and is filed separately; `fixture-mode` only probes for `~/.aws/credentials`.)\n *\n * Measured cost, not asserted: `homedir()` is 151 ns/op against 13 382 for the read this path\n * performs and 97 079 for the write (89x and 645x). The resolution is free relative to the I/O it\n * precedes.\n *\n * B-089. `packages/sdk/tests/mcp-token-store-modes.test.ts` pins it: import once, move HOME, write,\n * assert the write followed — and it must hold under `--pool=threads`, not only under the repo's\n * configured `forks`.\n *\n * B-090 — `THEOKIT_HOME` now WINS over the home-anchored default, and the reason is not tidiness.\n * `vitest.setup.ts` isolates every test in this package by pointing `THEOKIT_HOME` at a fresh\n * tmpdir; it backs `HOME` up and never sets it. A home-anchored module that ignored the variable\n * therefore resolved to the developer's REAL `~` while the suite believed it was isolated — and it\n * did: a default-config run deposited four refresh-token entries (`test-srv`, `srv-2`, `srv-race`,\n * `srv-roundtrip`) into `~/.theokit/mcp-tokens.json` from `tests/golden/mcp/oauth.golden.test.ts`.\n * A suite that is wrong about its own isolation is a false green about the one property the rest of\n * its greens rest on.\n *\n * **This is the code catching up to a contract the SDK already published**, not a new policy.\n * `src/project-env.ts:47-49` documents `THEOKIT_HOME` as \"Locates the SDK home — sessions, AND THE\n * CREDENTIAL STORE BENEATH IT\", and it is listed there as a sovereign key precisely because it\n * governs where credentials live. The public contract already said the store sits under the\n * variable; this module was the half that disagreed.\n *\n * The resolver adopted is `transcriptRoot()`'s (`internal/persistence/session-transcript.ts`), NOT\n * `paths.ts`'s `getTheokitHome(cwd)`. The transcript is the sibling with the right SHAPE: home-anchored\n * default, `THEOKIT_HOME` override, trimmed, empty-guarded — and its docstring records that before M94\n * it ignored the variable, so \"whoever set it had their state split in two silently\", which is this\n * defect verbatim. M94 ADR-2 already accepted that migration for identically-shaped state.\n * `getTheokitHome(cwd)` falls back to `<cwd>/.theokit`, so adopting IT would move the token file of\n * everyone who does not set the variable — and to a DIFFERENT place per working directory, making\n * whether you are logged in a property of which folder you launched from.\n *\n * **The migration this does carry**, stated rather than buried: a user who already holds\n * `~/.theokit/mcp-tokens.json` AND sets `THEOKIT_HOME` stops seeing those tokens. `getTokens` returns\n * `undefined`, which the caller surfaces as \"not logged in\", and the OAuth flow re-runs. Nothing is\n * deleted and nothing is overwritten — the old file stays where it is and is picked up again the\n * moment the variable is unset. No migration step is performed on the user's behalf, because\n * silently moving a credential file is a worse failure than a re-auth. Users who do NOT set\n * `THEOKIT_HOME` — the default — see no change at all.\n *\n * **Two further consequences for those who DO set it**, both on the directory-mode path rather than\n * on the path resolution, and both spelled out at {@link ensurePrivateStoreDir}: the store no longer\n * re-permissions a `$THEOKIT_HOME` it did not create, and `getTokens` REFUSES — typed, loud — to read\n * out of a group- or world-writable one instead of returning `undefined`.\n */\nfunction storeFilePath(): string {\n return storeLocation().file;\n}\n\n/**\n * Where the store lives, and whether that directory is OURS.\n *\n * `ours` is not bookkeeping — it decides whether this module is entitled to change the directory's\n * permissions. `<home>/.theokit` is a directory the SDK creates and owns; a `THEOKIT_HOME` root is\n * one the operator chose and may share with other state. See {@link ensurePrivateStoreDir}.\n */\ninterface StoreLocation {\n readonly dir: string;\n readonly file: string;\n readonly ours: boolean;\n}\n\n/**\n * The directory the token file lives in: `THEOKIT_HOME` when usable, `<home>/.theokit` otherwise.\n *\n * The empty/whitespace guard on the override is load-bearing in a way the HOME guard below is not:\n * `THEOKIT_HOME=\"\"` with no guard resolves the store to a CWD-RELATIVE `mcp-tokens.json`, and\n * `THEOKIT_HOME=\" \"` to a directory literally named three spaces. Neither falls back to anything;\n * both are new locations invented from an unusable value. `transcriptRoot()` guards it for the same\n * reason.\n */\nfunction storeLocation(): StoreLocation {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) {\n return { dir: override, file: join(override, \"mcp-tokens.json\"), ours: false };\n }\n // Mirrors `os.homedir()`'s own per-platform source: USERPROFILE on Windows, HOME elsewhere.\n const fromEnv =\n process.platform === \"win32\" ? process.env.USERPROFILE?.trim() : process.env.HOME?.trim();\n const home = fromEnv !== undefined && fromEnv.length > 0 ? fromEnv : homedir();\n const dir = join(home, \".theokit\");\n return { dir, file: join(dir, \"mcp-tokens.json\"), ours: true };\n}\n\n/**\n * Make the directory private BEFORE anything is written into it.\n *\n * `atomicWriteJson` auto-creates the parent with a bare recursive `mkdir`, so under the common umask\n * 002 `~/.theokit` was born 0775 — and the `chmod 600` applied to the file afterwards protects the\n * wrong thing. Write permission on a DIRECTORY is permission to unlink and recreate its contents, so\n * a 0600 file inside a group-writable directory can be replaced wholesale by another local user. The\n * secret here is a REFRESH TOKEN: replacing it swaps which account the agent authenticates as.\n *\n * **The retro-fix `chmod` is scoped to directories we own, and B-090 is why.** It was written\n * unconditional for a specific reason: `mkdir`'s mode applies only at CREATION, so every machine\n * that already ran an older build has a loose `~/.theokit` sitting there, and a fix that only covers\n * fresh installs does not reach the population that has the problem. That reasoning names its own\n * population — directories THIS MODULE created in an older build. Once `THEOKIT_HOME` is honoured,\n * an unconditional `chmod` also reaches a root the operator chose, which we never created and which\n * `paths.ts` documents as a multi-tenant deployment knob. Measured: it silently demoted a 0775\n * `$THEOKIT_HOME` to 0700, taking the sessions, transcripts, personality and credential-pool state\n * that share that root with it. No other consumer of the variable imposes a mode on it.\n *\n * So: always `mkdir` at 0700 (a directory WE create is born private wherever it is), and `chmod` an\n * existing one only when it is `<home>/.theokit`.\n *\n * The `chmod` deliberately does NOT also cover \"we just created it\". A first draft guarded it with\n * `ours || created !== undefined`; mutating that to plain `ours` killed no test, and the reason is\n * that the disjunct cannot make a difference: a umask only CLEARS bits, and 0700 carries none in the\n * group/other range, so `mkdir(0700)` is private for every possible umask. The redundant clause was\n * removed rather than pinned with a test written to justify it.\n *\n * **What that leaves, stated rather than left to be discovered.** A pre-existing group-writable\n * `$THEOKIT_HOME` is no longer repaired, so the next {@link getTokens} throws `CredentialError` from\n * `assertSecureModes` naming the directory and the `chmod 700` that fixes it. That is the intended\n * end state: a refresh token under a directory any local user can replace files in is not safe to\n * return, and the two available alternatives are worse. Silently tightening the operator's root\n * breaks their deployment to protect them from a choice they may have made deliberately; silently\n * returning the token hands the caller a credential that may already have been swapped. A loud,\n * actionable refusal is the only option that neither mutates someone else's directory nor lies about\n * what it read.\n *\n * The asymmetry that remains is real and is NOT fixed here: the write path has no such gate, so\n * `setTokens` will happily write into that directory and the following `getTokens` refuses it.\n * Adding a write-side gate is a separate behaviour change on a path that currently always succeeds.\n */\nfunction ensurePrivateStoreDir({ dir, ours }: StoreLocation): void {\n try {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n if (ours) chmodSync(dir, 0o700);\n } catch {\n // Windows: chmod is a no-op and the mode argument is meaningless. Same posture as the file\n // chmod below — documented in ADR D41 / EC-14.\n }\n}\n\ninterface KeytarLike {\n setPassword: (service: string, account: string, password: string) => Promise<void>;\n getPassword: (service: string, account: string) => Promise<string | null>;\n deletePassword: (service: string, account: string) => Promise<boolean>;\n}\n\nlet keytarWarned = false;\nlet cachedKeytar: KeytarLike | undefined | null;\nfunction tryRequireKeytar(): KeytarLike | null {\n if (cachedKeytar !== undefined) return cachedKeytar;\n try {\n const r = createRequire(import.meta.url);\n cachedKeytar = r(\"keytar\") as KeytarLike;\n } catch {\n if (!keytarWarned) {\n // The path is RESOLVED rather than spelled `~/.theokit/mcp-tokens.json`. That literal was\n // correct until B-090 made `THEOKIT_HOME` win, at which point a message naming a fixed\n // location would send anyone who sets the variable to look at a file the store no longer\n // writes — a diagnostic that lies costs more than one that is absent.\n diag(\n `[theokit-sdk] keytar not installed; MCP OAuth tokens will be stored in ${storeFilePath()} (chmod 600 where POSIX). Install \\`keytar\\` for OS keychain storage.\\n`,\n );\n keytarWarned = true;\n }\n cachedKeytar = null;\n }\n return cachedKeytar;\n}\n\n// EC-9 (race): serialize concurrent refreshes per server. Each key maps to\n// the in-flight refresh Promise; subsequent callers await the same promise.\nconst inflightRefresh = new Map<string, Promise<OAuthTokens>>();\n\n/**\n * Persist tokens for `serverName`. Tries keychain first, falls back to file\n * with chmod 600 (POSIX). Idempotent.\n *\n */\nexport async function setTokens(serverName: string, tokens: OAuthTokens): Promise<void> {\n const kt = tryRequireKeytar();\n const payload = JSON.stringify(tokens);\n if (kt !== null && kt !== undefined) {\n await kt.setPassword(KEYTAR_SERVICE, serverName, payload);\n return;\n }\n // File fallback. The directory is locked down first — see `ensurePrivateStoreDir`.\n // Resolved once for the whole operation and PASSED DOWN. Resolving per use would let a read and\n // the write that follows it disagree if HOME moved in between — and `ensurePrivateStoreDir`\n // resolving its own copy would let the directory be locked down under one home while the token\n // lands under another. Today those two statements are adjacent and synchronous so they cannot\n // diverge, but that is incidental; passing the path makes the invariant structural.\n const location = storeLocation();\n const filePath = location.file;\n ensurePrivateStoreDir(location);\n let allTokens: Record<string, OAuthTokens> = {};\n if (existsSync(filePath)) {\n try {\n allTokens = JSON.parse(readFileSync(filePath, \"utf8\")) as Record<string, OAuthTokens>;\n } catch {\n // corrupt file — start fresh\n allTokens = {};\n }\n }\n allTokens[serverName] = tokens;\n await atomicWriteJson(filePath, allTokens);\n try {\n chmodSync(filePath, 0o600);\n } catch {\n // Windows: chmod is a no-op. Documented in ADR D41 / EC-14.\n }\n}\n\n/**\n * Retrieve tokens for `serverName`. Returns undefined if absent.\n *\n */\nexport async function getTokens(serverName: string): Promise<OAuthTokens | undefined> {\n const kt = tryRequireKeytar();\n if (kt !== null && kt !== undefined) {\n const value = await kt.getPassword(KEYTAR_SERVICE, serverName);\n if (typeof value !== \"string\") return undefined;\n try {\n return JSON.parse(value) as OAuthTokens;\n } catch {\n return undefined;\n }\n }\n const filePath = storeFilePath();\n if (!existsSync(filePath)) return undefined;\n // The same gate the credential file gets, and deliberately the same implementation rather than a\n // second one: a refresh token is a credential, and `assertSecureModes` already carries the attack\n // it defends against in its docstring. It is called OUTSIDE the try/catch on purpose — the catch\n // below exists to treat a corrupt file as absent, and letting it swallow this would turn \"someone\n // else can replace your token\" into a silent `undefined`, which reads as \"not logged in\".\n assertSecureModes(dirname(filePath), filePath);\n try {\n const all = JSON.parse(readFileSync(filePath, \"utf8\")) as Record<string, OAuthTokens>;\n return all[serverName];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serialize concurrent refresh attempts per server (EC-9). If a refresh is\n * already in flight for the same `serverName`, the second caller awaits\n * the same Promise.\n *\n */\nexport function lockedRefresh(\n serverName: string,\n refreshFn: () => Promise<OAuthTokens>,\n): Promise<OAuthTokens> {\n const existing = inflightRefresh.get(serverName);\n if (existing !== undefined) return existing;\n const promise = (async () => {\n try {\n return await refreshFn();\n } finally {\n inflightRefresh.delete(serverName);\n }\n })();\n inflightRefresh.set(serverName, promise);\n return promise;\n}\n\n/**\n * Reset all cached state. Test-only helper.\n *\n * @internal\n */\nexport function _resetForTests(): void {\n inflightRefresh.clear();\n cachedKeytar = undefined;\n keytarWarned = false;\n}\n","/**\n * OAuth 2.1 PKCE flow runner for MCP HTTP servers. See ADR D41.\n *\n * @internal\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { createInterface } from \"node:readline/promises\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { McpOAuthConfig } from \"../../types/mcp.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type OAuthTokens, setTokens } from \"./token-storage.js\";\n\n/**\n * Generate a random base64url-encoded string. Used for both code_verifier\n * (43-128 chars) and state (CSRF protection).\n */\nfunction base64url(n: number): string {\n return randomBytes(n).toString(\"base64url\");\n}\n\n/**\n * Compute PKCE code_challenge = base64url(SHA256(code_verifier)).\n */\nfunction challengeFor(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\n/**\n * Refresh an access token using `refresh_token`. Throws on failure.\n *\n */\nexport async function refreshAccessToken(\n serverName: string,\n clientId: string,\n refreshToken: string,\n oauth: McpOAuthConfig,\n): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: clientId,\n });\n const response = await fetch(oauth.tokenEndpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n });\n if (!response.ok) {\n throw new ConfigurationError(`OAuth refresh failed: HTTP ${response.status}`, {\n code: \"oauth_refresh_failed\",\n });\n }\n const data = (await response.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n const obtainedAt = Date.now();\n const tokens: OAuthTokens = {\n accessToken: data.access_token,\n refreshToken: data.refresh_token ?? refreshToken,\n // EC-10: default conservative 3600s if expires_in missing.\n expiresAt: obtainedAt + (data.expires_in ?? 3600) * 1000,\n obtainedAt,\n ...(data.scope !== undefined ? { scope: data.scope } : {}),\n };\n await setTokens(serverName, tokens);\n return tokens;\n}\n\n/**\n * Run the full PKCE flow. Generates verifier+challenge+state, opens the\n * authorization URL (browser or manual print), waits for the callback\n * (localhost or stdin), exchanges code for tokens.\n *\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: PKCE flow is a linear protocol step (verifier → challenge → state → URL → wait → exchange); refactoring fragments the RFC 7636 narrative.\nexport async function runPkceFlow(\n serverName: string,\n clientId: string,\n scopes: string[] | undefined,\n oauth: McpOAuthConfig,\n): Promise<OAuthTokens> {\n const verifier = base64url(48);\n const challenge = challengeFor(verifier);\n const state = base64url(16);\n const timeoutMs = oauth.timeoutMs ?? 300_000;\n\n let redirectUri: string;\n let codeWaiter: Promise<{ code: string; state: string }>;\n let cleanup: () => void = () => {};\n\n if (oauth.redirectMode === \"localhost\") {\n const result = await openLocalhostCallback(state, timeoutMs);\n redirectUri = result.redirectUri;\n codeWaiter = result.waitFor;\n cleanup = result.close;\n } else {\n redirectUri = \"urn:ietf:wg:oauth:2.0:oob\";\n codeWaiter = readCodeFromStdin(state, timeoutMs);\n }\n\n try {\n const authUrl = new URL(oauth.authorizationEndpoint);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"client_id\", clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUri);\n if (scopes !== undefined && scopes.length > 0) {\n authUrl.searchParams.set(\"scope\", scopes.join(\" \"));\n }\n authUrl.searchParams.set(\"code_challenge\", challenge);\n authUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n authUrl.searchParams.set(\"state\", state);\n\n diag(\n `\\n[theokit-sdk] OAuth required for MCP server \"${serverName}\".\\n` +\n `Open this URL to authenticate:\\n ${authUrl.toString()}\\n\\n`,\n );\n\n const { code, state: returnedState } = await codeWaiter;\n // EC-2 MUST FIX: validate state.\n if (returnedState !== state) {\n throw new ConfigurationError(\n \"OAuth state mismatch — possible CSRF attempt; aborting token exchange.\",\n { code: \"oauth_state_mismatch\" },\n );\n }\n\n // Exchange code for tokens.\n const tokenBody = new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n client_id: clientId,\n code_verifier: verifier,\n redirect_uri: redirectUri,\n });\n const response = await fetch(oauth.tokenEndpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: tokenBody.toString(),\n });\n if (!response.ok) {\n const errText = await response.text();\n throw new ConfigurationError(\n `OAuth token exchange failed: HTTP ${response.status}: ${errText.slice(0, 200)}`,\n { code: \"oauth_token_exchange_failed\" },\n );\n }\n const data = (await response.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n const obtainedAt = Date.now();\n return {\n accessToken: data.access_token,\n ...(data.refresh_token !== undefined ? { refreshToken: data.refresh_token } : {}),\n // EC-10: default 3600s when expires_in absent.\n expiresAt: obtainedAt + (data.expires_in ?? 3600) * 1000,\n obtainedAt,\n ...(data.scope !== undefined ? { scope: data.scope } : {}),\n };\n } finally {\n cleanup();\n }\n}\n\n/**\n * Start a localhost HTTP server on a free port; return the redirect URI,\n * a promise that resolves with the code+state from the first valid request,\n * and a close handle.\n *\n * @internal\n */\nasync function openLocalhostCallback(\n expectedState: string,\n timeoutMs: number,\n): Promise<{\n redirectUri: string;\n waitFor: Promise<{ code: string; state: string }>;\n close: () => void;\n}> {\n let resolveCode: ((value: { code: string; state: string }) => void) | undefined;\n let rejectCode: ((reason: unknown) => void) | undefined;\n const waitFor = new Promise<{ code: string; state: string }>((res, rej) => {\n resolveCode = res;\n rejectCode = rej;\n });\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n if (typeof code !== \"string\" || typeof state !== \"string\") {\n res.statusCode = 400;\n res.end(\"Missing code or state\");\n return;\n }\n // EC-2: state must match the one we generated. We DO NOT trust any\n // localhost GET — only the one carrying our exact state.\n if (state !== expectedState) {\n res.statusCode = 400;\n res.end(\"State mismatch — request rejected.\");\n return;\n }\n res.statusCode = 200;\n res.end(\"Authentication successful. You can close this tab and return to the terminal.\");\n resolveCode?.({ code, state });\n });\n server.listen(0, \"127.0.0.1\");\n const timeoutHandle = setTimeout(() => {\n rejectCode?.(new ConfigurationError(\"OAuth flow timed out\", { code: \"oauth_timeout\" }));\n }, timeoutMs);\n // Wait for server.listen to bind so we can read the port.\n await new Promise<void>((r) => {\n if (server.listening) r();\n else server.once(\"listening\", () => r());\n });\n const address = server.address();\n if (typeof address !== \"object\" || address === null) {\n server.close();\n throw new ConfigurationError(\"OAuth localhost callback failed to bind\", {\n code: \"oauth_bind_failed\",\n });\n }\n const port = address.port;\n return {\n redirectUri: `http://127.0.0.1:${port}/callback`,\n waitFor,\n close: () => {\n clearTimeout(timeoutHandle);\n server.close();\n },\n };\n}\n\n/**\n * Read `code` (and `state`) from stdin (manual mode). User pastes the\n * full callback URL or just the code value.\n *\n * @internal\n */\nasync function readCodeFromStdin(\n expectedState: string,\n timeoutMs: number,\n): Promise<{ code: string; state: string }> {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const promise = new Promise<{ code: string; state: string }>((resolve, reject) => {\n rl.question(\"Paste the full callback URL (or just the code): \")\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stdin reader handles 2 input formats (full URL vs raw code) inline; splitting fragments the manual-mode UX.\n .then((answer) => {\n rl.close();\n const trimmed = answer.trim();\n // Try to parse as URL first.\n if (trimmed.includes(\"?\")) {\n try {\n const parsed = new URL(trimmed);\n const code = parsed.searchParams.get(\"code\");\n const state = parsed.searchParams.get(\"state\") ?? \"\";\n if (typeof code === \"string\") {\n resolve({ code, state });\n return;\n }\n } catch {\n // not a URL — fall through\n }\n }\n // Treat the entire input as the code. State validation will fail\n // unless the user also provided state — but in manual mode they\n // typically paste the URL with state baked in.\n resolve({ code: trimmed, state: expectedState });\n })\n .catch(reject);\n setTimeout(() => {\n rl.close();\n reject(new ConfigurationError(\"OAuth manual input timed out\", { code: \"oauth_timeout\" }));\n }, timeoutMs);\n });\n return promise;\n}\n"]}