@theokit/sdk 5.15.1 → 5.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (355) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/a2a/index.cjs +3 -3
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent-D6WBBNGR.cjs +72 -0
  5. package/dist/{agent-CB27KF6O.cjs.map → agent-D6WBBNGR.cjs.map} +1 -1
  6. package/dist/agent-QRIFX2SY.js +63 -0
  7. package/dist/{agent-66U5QCPF.js.map → agent-QRIFX2SY.js.map} +1 -1
  8. package/dist/agent-session-store-2LQEPS4H.js +6 -0
  9. package/dist/{agent-session-store-22GKA7O4.js.map → agent-session-store-2LQEPS4H.js.map} +1 -1
  10. package/dist/agent-session-store-IOH6BREF.cjs +23 -0
  11. package/dist/{agent-session-store-WP6NGDVX.cjs.map → agent-session-store-IOH6BREF.cjs.map} +1 -1
  12. package/dist/auth/index.cjs +15 -15
  13. package/dist/auth/index.js +3 -3
  14. package/dist/{batch-N2XDYZED.js → batch-7IGV2OKA.js} +8 -8
  15. package/dist/{batch-N2XDYZED.js.map → batch-7IGV2OKA.js.map} +1 -1
  16. package/dist/{batch-VFR2MAUE.cjs → batch-FIWQZ3JD.cjs} +14 -14
  17. package/dist/{batch-VFR2MAUE.cjs.map → batch-FIWQZ3JD.cjs.map} +1 -1
  18. package/dist/{chunk-AT2PESXB.cjs → chunk-2UYAL4N7.cjs} +5 -5
  19. package/dist/chunk-2UYAL4N7.cjs.map +1 -0
  20. package/dist/{chunk-K2BQQ445.js → chunk-3GQYMKVJ.js} +3 -3
  21. package/dist/{chunk-K2BQQ445.js.map → chunk-3GQYMKVJ.js.map} +1 -1
  22. package/dist/{chunk-YSTXFWQE.cjs → chunk-3HL43XBD.cjs} +4 -4
  23. package/dist/{chunk-YSTXFWQE.cjs.map → chunk-3HL43XBD.cjs.map} +1 -1
  24. package/dist/{chunk-XESYJ4JC.js → chunk-3VX7JHJI.js} +7 -7
  25. package/dist/{chunk-XESYJ4JC.js.map → chunk-3VX7JHJI.js.map} +1 -1
  26. package/dist/{chunk-6XQLTQB6.cjs → chunk-3YCNBOX7.cjs} +3 -3
  27. package/dist/{chunk-6XQLTQB6.cjs.map → chunk-3YCNBOX7.cjs.map} +1 -1
  28. package/dist/{chunk-CHKV2L2Y.cjs → chunk-46YYJIHL.cjs} +30 -30
  29. package/dist/chunk-46YYJIHL.cjs.map +1 -0
  30. package/dist/{chunk-73IITAF7.js → chunk-4C37ELQL.js} +9 -9
  31. package/dist/{chunk-73IITAF7.js.map → chunk-4C37ELQL.js.map} +1 -1
  32. package/dist/{chunk-AGO5S5WD.js → chunk-4E4D6H77.js} +3 -3
  33. package/dist/{chunk-AGO5S5WD.js.map → chunk-4E4D6H77.js.map} +1 -1
  34. package/dist/{chunk-R35ZJAYT.cjs → chunk-4JF52NED.cjs} +12 -12
  35. package/dist/{chunk-R35ZJAYT.cjs.map → chunk-4JF52NED.cjs.map} +1 -1
  36. package/dist/{chunk-INVEGVGO.js → chunk-4TA47IK4.js} +8 -8
  37. package/dist/{chunk-INVEGVGO.js.map → chunk-4TA47IK4.js.map} +1 -1
  38. package/dist/{chunk-MLGETTYX.js → chunk-4YUIYSZO.js} +6 -6
  39. package/dist/{chunk-MLGETTYX.js.map → chunk-4YUIYSZO.js.map} +1 -1
  40. package/dist/{chunk-RZL2W4C3.js → chunk-5L7S2VOL.js} +5 -5
  41. package/dist/{chunk-RZL2W4C3.js.map → chunk-5L7S2VOL.js.map} +1 -1
  42. package/dist/{chunk-3WKWBYPO.cjs → chunk-6EHOJLJ3.cjs} +20 -20
  43. package/dist/chunk-6EHOJLJ3.cjs.map +1 -0
  44. package/dist/{chunk-XOU3CL7S.cjs → chunk-6HQFPX7N.cjs} +28 -28
  45. package/dist/chunk-6HQFPX7N.cjs.map +1 -0
  46. package/dist/{chunk-3E3VSMB6.cjs → chunk-6XT5LAZG.cjs} +58 -58
  47. package/dist/chunk-6XT5LAZG.cjs.map +1 -0
  48. package/dist/{chunk-R427EOZE.cjs → chunk-7EFT6N5C.cjs} +13 -13
  49. package/dist/{chunk-R427EOZE.cjs.map → chunk-7EFT6N5C.cjs.map} +1 -1
  50. package/dist/{chunk-L7V4DDIE.cjs → chunk-7VNFOGRD.cjs} +12 -12
  51. package/dist/chunk-7VNFOGRD.cjs.map +1 -0
  52. package/dist/{chunk-YKNBTHMD.js → chunk-AQ23NII7.js} +3 -3
  53. package/dist/{chunk-YKNBTHMD.js.map → chunk-AQ23NII7.js.map} +1 -1
  54. package/dist/{chunk-O2RCS3SJ.js → chunk-ATGSV4GS.js} +4 -4
  55. package/dist/{chunk-O2RCS3SJ.js.map → chunk-ATGSV4GS.js.map} +1 -1
  56. package/dist/{chunk-H7HD6RXO.cjs → chunk-AW72G4TC.cjs} +5 -5
  57. package/dist/{chunk-H7HD6RXO.cjs.map → chunk-AW72G4TC.cjs.map} +1 -1
  58. package/dist/{chunk-M4U24U6G.js → chunk-AZK3QM36.js} +5 -5
  59. package/dist/{chunk-M4U24U6G.js.map → chunk-AZK3QM36.js.map} +1 -1
  60. package/dist/{chunk-QK2ERTO3.js → chunk-BH6M2DGV.js} +4 -4
  61. package/dist/{chunk-QK2ERTO3.js.map → chunk-BH6M2DGV.js.map} +1 -1
  62. package/dist/{chunk-26UQG242.cjs → chunk-BTGYRM4J.cjs} +264 -264
  63. package/dist/chunk-BTGYRM4J.cjs.map +1 -0
  64. package/dist/{chunk-ZQWRUJHE.js → chunk-CG64VPPU.js} +50 -50
  65. package/dist/{chunk-ZQWRUJHE.js.map → chunk-CG64VPPU.js.map} +1 -1
  66. package/dist/{chunk-CBBT42VX.js → chunk-CMDM4VF6.js} +3 -3
  67. package/dist/{chunk-CBBT42VX.js.map → chunk-CMDM4VF6.js.map} +1 -1
  68. package/dist/{chunk-OLJOI4LK.js → chunk-CN732Z5C.js} +4 -4
  69. package/dist/{chunk-OLJOI4LK.js.map → chunk-CN732Z5C.js.map} +1 -1
  70. package/dist/{chunk-SETHRLQS.cjs → chunk-D3BL3EEB.cjs} +9 -9
  71. package/dist/chunk-D3BL3EEB.cjs.map +1 -0
  72. package/dist/{chunk-LCCT5ZXJ.js → chunk-DB5RYCXX.js} +13 -13
  73. package/dist/{chunk-LCCT5ZXJ.js.map → chunk-DB5RYCXX.js.map} +1 -1
  74. package/dist/{chunk-SV63WTA2.js → chunk-DBH2WA2U.js} +4 -4
  75. package/dist/{chunk-SV63WTA2.js.map → chunk-DBH2WA2U.js.map} +1 -1
  76. package/dist/{chunk-XE3CAY6Z.cjs → chunk-DEHPRORL.cjs} +4 -4
  77. package/dist/{chunk-XE3CAY6Z.cjs.map → chunk-DEHPRORL.cjs.map} +1 -1
  78. package/dist/{chunk-UKMBRMGT.js → chunk-DGO4LPLP.js} +4 -4
  79. package/dist/{chunk-UKMBRMGT.js.map → chunk-DGO4LPLP.js.map} +1 -1
  80. package/dist/{chunk-RS7YQR4X.cjs → chunk-EBX6XUN7.cjs} +7 -7
  81. package/dist/{chunk-RS7YQR4X.cjs.map → chunk-EBX6XUN7.cjs.map} +1 -1
  82. package/dist/chunk-EDIYR4VR.cjs +18 -0
  83. package/dist/{chunk-SPEN7RJU.cjs.map → chunk-EDIYR4VR.cjs.map} +1 -1
  84. package/dist/{chunk-QGDPMM3C.js → chunk-EF5IONLL.js} +5 -5
  85. package/dist/{chunk-QGDPMM3C.js.map → chunk-EF5IONLL.js.map} +1 -1
  86. package/dist/{chunk-MSW7LB2V.cjs → chunk-EOWIUDKG.cjs} +5 -5
  87. package/dist/{chunk-MSW7LB2V.cjs.map → chunk-EOWIUDKG.cjs.map} +1 -1
  88. package/dist/{chunk-L7JPXZ2C.cjs → chunk-ER3BF23R.cjs} +19 -19
  89. package/dist/{chunk-L7JPXZ2C.cjs.map → chunk-ER3BF23R.cjs.map} +1 -1
  90. package/dist/{chunk-BNEUB52I.cjs → chunk-ERBKPA2N.cjs} +4 -4
  91. package/dist/{chunk-BNEUB52I.cjs.map → chunk-ERBKPA2N.cjs.map} +1 -1
  92. package/dist/{chunk-4QCJAJAG.js → chunk-F54PXZIA.js} +5 -5
  93. package/dist/{chunk-4QCJAJAG.js.map → chunk-F54PXZIA.js.map} +1 -1
  94. package/dist/{chunk-2XWAYCFM.cjs → chunk-FBT2SF2S.cjs} +12 -12
  95. package/dist/{chunk-2XWAYCFM.cjs.map → chunk-FBT2SF2S.cjs.map} +1 -1
  96. package/dist/{chunk-AUH2EVWY.cjs → chunk-FZSPVIFK.cjs} +16 -16
  97. package/dist/chunk-FZSPVIFK.cjs.map +1 -0
  98. package/dist/{chunk-CYWOJA6B.js → chunk-GA27FFT5.js} +3 -3
  99. package/dist/{chunk-CYWOJA6B.js.map → chunk-GA27FFT5.js.map} +1 -1
  100. package/dist/{chunk-HWMGR3HA.js → chunk-GEQLHBJM.js} +6 -6
  101. package/dist/{chunk-HWMGR3HA.js.map → chunk-GEQLHBJM.js.map} +1 -1
  102. package/dist/{chunk-IJ7M6GOG.cjs → chunk-GKERJ52A.cjs} +4 -4
  103. package/dist/{chunk-IJ7M6GOG.cjs.map → chunk-GKERJ52A.cjs.map} +1 -1
  104. package/dist/{chunk-NEH3BPFD.cjs → chunk-HI5TJWQE.cjs} +19 -19
  105. package/dist/{chunk-NEH3BPFD.cjs.map → chunk-HI5TJWQE.cjs.map} +1 -1
  106. package/dist/{chunk-ZOFRNNZD.cjs → chunk-IZV72OEI.cjs} +11 -11
  107. package/dist/chunk-IZV72OEI.cjs.map +1 -0
  108. package/dist/{chunk-KU5O7WPK.js → chunk-JD3EKKKB.js} +4 -4
  109. package/dist/{chunk-KU5O7WPK.js.map → chunk-JD3EKKKB.js.map} +1 -1
  110. package/dist/{chunk-DFBWYETS.js → chunk-JRP2W2DR.js} +3 -3
  111. package/dist/{chunk-DFBWYETS.js.map → chunk-JRP2W2DR.js.map} +1 -1
  112. package/dist/{chunk-26GI3OYA.js → chunk-JRQJMZKY.js} +13 -13
  113. package/dist/{chunk-26GI3OYA.js.map → chunk-JRQJMZKY.js.map} +1 -1
  114. package/dist/{chunk-YQ3XC6C2.cjs → chunk-JVH3NNJ3.cjs} +13 -13
  115. package/dist/chunk-JVH3NNJ3.cjs.map +1 -0
  116. package/dist/{chunk-VWYFGE27.cjs → chunk-KC2HKUPT.cjs} +56 -56
  117. package/dist/chunk-KC2HKUPT.cjs.map +1 -0
  118. package/dist/{chunk-PDOXYXWX.cjs → chunk-KDJTECE6.cjs} +4 -4
  119. package/dist/{chunk-PDOXYXWX.cjs.map → chunk-KDJTECE6.cjs.map} +1 -1
  120. package/dist/{chunk-QD6B6W6I.js → chunk-L2KC2G7H.js} +5 -5
  121. package/dist/{chunk-QD6B6W6I.js.map → chunk-L2KC2G7H.js.map} +1 -1
  122. package/dist/{chunk-3BBTHFGJ.js → chunk-L5B7EWWH.js} +5 -5
  123. package/dist/{chunk-3BBTHFGJ.js.map → chunk-L5B7EWWH.js.map} +1 -1
  124. package/dist/{chunk-X7CE7Y5W.js → chunk-LG4JCJEI.js} +11 -11
  125. package/dist/{chunk-X7CE7Y5W.js.map → chunk-LG4JCJEI.js.map} +1 -1
  126. package/dist/{chunk-2HXTNVLM.js → chunk-LSURFRJA.js} +6 -6
  127. package/dist/{chunk-2HXTNVLM.js.map → chunk-LSURFRJA.js.map} +1 -1
  128. package/dist/{chunk-55LLQFHW.cjs → chunk-MJGY3E3C.cjs} +4 -4
  129. package/dist/{chunk-55LLQFHW.cjs.map → chunk-MJGY3E3C.cjs.map} +1 -1
  130. package/dist/{chunk-EQ5IDL6W.cjs → chunk-MKS5FFH5.cjs} +15 -15
  131. package/dist/chunk-MKS5FFH5.cjs.map +1 -0
  132. package/dist/{chunk-WM646HEN.js → chunk-MTNCJ7MQ.js} +6 -6
  133. package/dist/{chunk-WM646HEN.js.map → chunk-MTNCJ7MQ.js.map} +1 -1
  134. package/dist/{chunk-SA6K24NB.cjs → chunk-MXJJMP4U.cjs} +7 -7
  135. package/dist/chunk-MXJJMP4U.cjs.map +1 -0
  136. package/dist/{chunk-FTXY4D44.cjs → chunk-N2ORTDSO.cjs} +20 -20
  137. package/dist/chunk-N2ORTDSO.cjs.map +1 -0
  138. package/dist/{chunk-7YUPSBDV.cjs → chunk-NDXZXGVP.cjs} +6 -6
  139. package/dist/{chunk-7YUPSBDV.cjs.map → chunk-NDXZXGVP.cjs.map} +1 -1
  140. package/dist/{chunk-3UMPP553.cjs → chunk-NMRNE6QX.cjs} +11 -11
  141. package/dist/{chunk-3UMPP553.cjs.map → chunk-NMRNE6QX.cjs.map} +1 -1
  142. package/dist/{chunk-PKRPV3R7.js → chunk-NO6AG22P.js} +6 -6
  143. package/dist/{chunk-PKRPV3R7.js.map → chunk-NO6AG22P.js.map} +1 -1
  144. package/dist/{chunk-NK5EOTDY.js → chunk-OIOSY5G6.js} +3 -3
  145. package/dist/{chunk-NK5EOTDY.js.map → chunk-OIOSY5G6.js.map} +1 -1
  146. package/dist/{chunk-RGVMJU57.js → chunk-P7B64NFK.js} +8 -8
  147. package/dist/{chunk-RGVMJU57.js.map → chunk-P7B64NFK.js.map} +1 -1
  148. package/dist/{chunk-TDED5XES.js → chunk-PCPYTBVV.js} +6 -6
  149. package/dist/chunk-PCPYTBVV.js.map +1 -0
  150. package/dist/{chunk-FBIDOOJM.cjs → chunk-PDFSLD5P.cjs} +6 -6
  151. package/dist/{chunk-FBIDOOJM.cjs.map → chunk-PDFSLD5P.cjs.map} +1 -1
  152. package/dist/{chunk-YMVTUV5K.js → chunk-PISZRLES.js} +5 -5
  153. package/dist/{chunk-YMVTUV5K.js.map → chunk-PISZRLES.js.map} +1 -1
  154. package/dist/{chunk-BUUUWQMB.cjs → chunk-PNL63WDP.cjs} +4 -4
  155. package/dist/{chunk-BUUUWQMB.cjs.map → chunk-PNL63WDP.cjs.map} +1 -1
  156. package/dist/{chunk-VNRNZ3WI.js → chunk-PSMWZYW6.js} +4 -4
  157. package/dist/{chunk-VNRNZ3WI.js.map → chunk-PSMWZYW6.js.map} +1 -1
  158. package/dist/{chunk-5645PMVU.cjs → chunk-PXYINWBC.cjs} +20 -20
  159. package/dist/chunk-PXYINWBC.cjs.map +1 -0
  160. package/dist/{chunk-RTDVSHJR.cjs → chunk-Q4UOCMAO.cjs} +5 -5
  161. package/dist/{chunk-RTDVSHJR.cjs.map → chunk-Q4UOCMAO.cjs.map} +1 -1
  162. package/dist/{chunk-5IRDK5BC.js → chunk-QH6MWGOA.js} +4 -4
  163. package/dist/{chunk-5IRDK5BC.js.map → chunk-QH6MWGOA.js.map} +1 -1
  164. package/dist/{chunk-3LMVJTNJ.js → chunk-QPUKIZOT.js} +3 -3
  165. package/dist/{chunk-3LMVJTNJ.js.map → chunk-QPUKIZOT.js.map} +1 -1
  166. package/dist/{chunk-SWALPLFQ.cjs → chunk-RTCO3USA.cjs} +16 -16
  167. package/dist/chunk-RTCO3USA.cjs.map +1 -0
  168. package/dist/{chunk-SAGRF4IB.js → chunk-S2CMEJ5F.js} +3 -3
  169. package/dist/{chunk-SAGRF4IB.js.map → chunk-S2CMEJ5F.js.map} +1 -1
  170. package/dist/{chunk-VZGE7NAI.js → chunk-S5ERB3CH.js} +3 -3
  171. package/dist/{chunk-VZGE7NAI.js.map → chunk-S5ERB3CH.js.map} +1 -1
  172. package/dist/{chunk-XJ3WU5CZ.js → chunk-S7IZEVXX.js} +6 -6
  173. package/dist/{chunk-XJ3WU5CZ.js.map → chunk-S7IZEVXX.js.map} +1 -1
  174. package/dist/{chunk-Q7UG242V.js → chunk-TIYQDJFK.js} +3 -3
  175. package/dist/{chunk-Q7UG242V.js.map → chunk-TIYQDJFK.js.map} +1 -1
  176. package/dist/{chunk-POBZXULR.cjs → chunk-TTNJOM5W.cjs} +16 -16
  177. package/dist/{chunk-POBZXULR.cjs.map → chunk-TTNJOM5W.cjs.map} +1 -1
  178. package/dist/{chunk-VCQ37TC5.js → chunk-TTXRNCXY.js} +3 -3
  179. package/dist/{chunk-VCQ37TC5.js.map → chunk-TTXRNCXY.js.map} +1 -1
  180. package/dist/{chunk-3HA7N2BB.cjs → chunk-TYKBAKAS.cjs} +5 -5
  181. package/dist/{chunk-3HA7N2BB.cjs.map → chunk-TYKBAKAS.cjs.map} +1 -1
  182. package/dist/{chunk-A77UMVMD.cjs → chunk-UMCCYXFZ.cjs} +8 -8
  183. package/dist/{chunk-A77UMVMD.cjs.map → chunk-UMCCYXFZ.cjs.map} +1 -1
  184. package/dist/{chunk-3GTN4HOO.js → chunk-UNP4NCMZ.js} +3 -3
  185. package/dist/{chunk-3GTN4HOO.js.map → chunk-UNP4NCMZ.js.map} +1 -1
  186. package/dist/{chunk-BPL5CVZ5.js → chunk-VFT63FJF.js} +3 -3
  187. package/dist/{chunk-BPL5CVZ5.js.map → chunk-VFT63FJF.js.map} +1 -1
  188. package/dist/{chunk-3KIUY67P.cjs → chunk-VHY6NVCJ.cjs} +30 -30
  189. package/dist/chunk-VHY6NVCJ.cjs.map +1 -0
  190. package/dist/{chunk-TRPRTZEH.cjs → chunk-VT3NWHFH.cjs} +6 -6
  191. package/dist/{chunk-TRPRTZEH.cjs.map → chunk-VT3NWHFH.cjs.map} +1 -1
  192. package/dist/{chunk-FJWQP6EE.js → chunk-WJ6OGKAO.js} +3 -3
  193. package/dist/{chunk-FJWQP6EE.js.map → chunk-WJ6OGKAO.js.map} +1 -1
  194. package/dist/{chunk-FLDHYF5C.cjs → chunk-X2XLSE2N.cjs} +9 -9
  195. package/dist/chunk-X2XLSE2N.cjs.map +1 -0
  196. package/dist/{chunk-UDAKAE4Z.cjs → chunk-X4ZYEZPD.cjs} +12 -12
  197. package/dist/chunk-X4ZYEZPD.cjs.map +1 -0
  198. package/dist/{chunk-QG4SXZ2A.cjs → chunk-XR6O6G3B.cjs} +27 -27
  199. package/dist/chunk-XR6O6G3B.cjs.map +1 -0
  200. package/dist/{chunk-BWYC7RZG.cjs → chunk-XTQWTVVI.cjs} +11 -11
  201. package/dist/chunk-XTQWTVVI.cjs.map +1 -0
  202. package/dist/{chunk-MLJDW2YK.js → chunk-YSGS57DA.js} +4 -4
  203. package/dist/{chunk-MLJDW2YK.js.map → chunk-YSGS57DA.js.map} +1 -1
  204. package/dist/{chunk-KCM3RMKR.js → chunk-YUQNHLKN.js} +8 -8
  205. package/dist/{chunk-KCM3RMKR.js.map → chunk-YUQNHLKN.js.map} +1 -1
  206. package/dist/{chunk-P7QYG4RZ.cjs → chunk-Z5MB2HAN.cjs} +8 -8
  207. package/dist/{chunk-P7QYG4RZ.cjs.map → chunk-Z5MB2HAN.cjs.map} +1 -1
  208. package/dist/{chunk-HJ2LV464.js → chunk-ZUWVO442.js} +4 -4
  209. package/dist/{chunk-HJ2LV464.js.map → chunk-ZUWVO442.js.map} +1 -1
  210. package/dist/{compact-session-CHBJOYWP.cjs → compact-session-5DWFHMW4.cjs} +21 -21
  211. package/dist/{compact-session-CHBJOYWP.cjs.map → compact-session-5DWFHMW4.cjs.map} +1 -1
  212. package/dist/{compact-session-F3J3FMEU.js → compact-session-AL65PEMX.js} +12 -12
  213. package/dist/{compact-session-F3J3FMEU.js.map → compact-session-AL65PEMX.js.map} +1 -1
  214. package/dist/context/index.cjs +11 -11
  215. package/dist/context/index.js +6 -6
  216. package/dist/context-4XSD2V3G.js +7 -0
  217. package/dist/{context-7EBZST3L.js.map → context-4XSD2V3G.js.map} +1 -1
  218. package/dist/context-ZX2VBGSX.cjs +24 -0
  219. package/dist/{context-4RSI3AXT.cjs.map → context-ZX2VBGSX.cjs.map} +1 -1
  220. package/dist/cron.cjs +40 -40
  221. package/dist/cron.js +39 -39
  222. package/dist/eval.cjs +51 -51
  223. package/dist/eval.cjs.map +1 -1
  224. package/dist/eval.js +41 -41
  225. package/dist/{executor-THUXNAFR.js → executor-ZHIUSHRV.js} +7 -7
  226. package/dist/{executor-THUXNAFR.js.map → executor-ZHIUSHRV.js.map} +1 -1
  227. package/dist/{executor-5QL5AXIZ.cjs → executor-ZTLJZ5LK.cjs} +24 -24
  228. package/dist/{executor-5QL5AXIZ.cjs.map → executor-ZTLJZ5LK.cjs.map} +1 -1
  229. package/dist/filesystem/index.cjs +14 -14
  230. package/dist/filesystem/index.cjs.map +1 -1
  231. package/dist/filesystem/index.js +4 -4
  232. package/dist/{fork-agent-S2EPIML7.js → fork-agent-BHVTALT5.js} +3 -3
  233. package/dist/{fork-agent-S2EPIML7.js.map → fork-agent-BHVTALT5.js.map} +1 -1
  234. package/dist/{fork-agent-WAEQI2DL.cjs → fork-agent-DCOPPXM2.cjs} +4 -4
  235. package/dist/{fork-agent-WAEQI2DL.cjs.map → fork-agent-DCOPPXM2.cjs.map} +1 -1
  236. package/dist/fs-session-store-EZ32TFGB.js +11 -0
  237. package/dist/{fs-session-store-MYQEVUFL.js.map → fs-session-store-EZ32TFGB.js.map} +1 -1
  238. package/dist/fs-session-store-G664LDDN.cjs +20 -0
  239. package/dist/{fs-session-store-CYNTEPJZ.cjs.map → fs-session-store-G664LDDN.cjs.map} +1 -1
  240. package/dist/generate-object-JFZTK567.cjs +20 -0
  241. package/dist/{generate-object-A5F576IT.cjs.map → generate-object-JFZTK567.cjs.map} +1 -1
  242. package/dist/{generate-object-TBDOBBYW.js → generate-object-RPBXY2U3.js} +4 -4
  243. package/dist/{generate-object-TBDOBBYW.js.map → generate-object-RPBXY2U3.js.map} +1 -1
  244. package/dist/index-manager-2MJEEN2O.js +18 -0
  245. package/dist/{index-manager-NF2WRLOU.js.map → index-manager-2MJEEN2O.js.map} +1 -1
  246. package/dist/index-manager-CT6MMG7S.cjs +27 -0
  247. package/dist/{index-manager-2KH75BRW.cjs.map → index-manager-CT6MMG7S.cjs.map} +1 -1
  248. package/dist/index.cjs +130 -130
  249. package/dist/index.cjs.map +1 -1
  250. package/dist/index.js +56 -56
  251. package/dist/{inject-session-LC2TROHM.js → inject-session-E2SZ4A35.js} +6 -6
  252. package/dist/{inject-session-LC2TROHM.js.map → inject-session-E2SZ4A35.js.map} +1 -1
  253. package/dist/{inject-session-T4RXANG3.cjs → inject-session-QZULG65O.cjs} +8 -8
  254. package/dist/{inject-session-T4RXANG3.cjs.map → inject-session-QZULG65O.cjs.map} +1 -1
  255. package/dist/internal/memory/adapters/index.cjs +4 -4
  256. package/dist/internal/memory/adapters/index.js +3 -3
  257. package/dist/internal/memory/storage/index.cjs +45 -45
  258. package/dist/internal/memory/storage/index.js +9 -9
  259. package/dist/internal/persistence/index.cjs +22 -22
  260. package/dist/internal/persistence/index.js +6 -6
  261. package/dist/internal/security/index.cjs +9 -9
  262. package/dist/internal/security/index.js +2 -2
  263. package/dist/mcp-auth.cjs +8 -8
  264. package/dist/mcp-auth.js +3 -3
  265. package/dist/models.cjs +30 -30
  266. package/dist/models.cjs.map +1 -1
  267. package/dist/models.js +8 -8
  268. package/dist/{oauth-transaction-store-U34YLEGP.js → oauth-transaction-store-QQBWGNE2.js} +3 -3
  269. package/dist/{oauth-transaction-store-U34YLEGP.js.map → oauth-transaction-store-QQBWGNE2.js.map} +1 -1
  270. package/dist/{oauth-transaction-store-OMX436YB.cjs → oauth-transaction-store-YF7WOA6B.cjs} +10 -10
  271. package/dist/{oauth-transaction-store-OMX436YB.cjs.map → oauth-transaction-store-YF7WOA6B.cjs.map} +1 -1
  272. package/dist/path-safety.cjs +9 -9
  273. package/dist/path-safety.js +2 -2
  274. package/dist/persistence.cjs +41 -41
  275. package/dist/persistence.cjs.map +1 -1
  276. package/dist/persistence.js +11 -11
  277. package/dist/project.cjs +7 -7
  278. package/dist/project.cjs.map +1 -1
  279. package/dist/project.js +4 -4
  280. package/dist/providers.cjs +6 -6
  281. package/dist/providers.js +4 -4
  282. package/dist/{registry-5TDAF7RK.js → registry-DOYBR237.js} +6 -6
  283. package/dist/{registry-5TDAF7RK.js.map → registry-DOYBR237.js.map} +1 -1
  284. package/dist/{registry-W7TSCLQO.cjs → registry-PB7JFVUJ.cjs} +14 -14
  285. package/dist/{registry-W7TSCLQO.cjs.map → registry-PB7JFVUJ.cjs.map} +1 -1
  286. package/dist/sandbox/index.cjs +41 -41
  287. package/dist/sandbox/index.cjs.map +1 -1
  288. package/dist/sandbox/index.js +7 -7
  289. package/dist/sanitize/index.cjs +2 -2
  290. package/dist/sanitize/index.js +1 -1
  291. package/dist/server/auth/index.cjs +9 -9
  292. package/dist/server/auth/index.cjs.map +1 -1
  293. package/dist/server/auth/index.js +4 -4
  294. package/dist/{session-transcript-7TZ6HXSX.cjs → session-transcript-EBVGLZ6B.cjs} +17 -17
  295. package/dist/{session-transcript-7TZ6HXSX.cjs.map → session-transcript-EBVGLZ6B.cjs.map} +1 -1
  296. package/dist/{session-transcript-BSHZYYY6.js → session-transcript-GU2VE7JX.js} +4 -4
  297. package/dist/{session-transcript-BSHZYYY6.js.map → session-transcript-GU2VE7JX.js.map} +1 -1
  298. package/dist/skills.cjs +7 -7
  299. package/dist/skills.js +4 -4
  300. package/dist/stream-object-3AU7QDHT.js +7 -0
  301. package/dist/{stream-object-EKM4WGTI.js.map → stream-object-3AU7QDHT.js.map} +1 -1
  302. package/dist/stream-object-SLGR2KIA.cjs +20 -0
  303. package/dist/{stream-object-AS4YYM4B.cjs.map → stream-object-SLGR2KIA.cjs.map} +1 -1
  304. package/dist/subagents-loader-4PQS7ULK.cjs +16 -0
  305. package/dist/{subagents-loader-KLWF4QPD.cjs.map → subagents-loader-4PQS7ULK.cjs.map} +1 -1
  306. package/dist/subagents-loader-CPFVLWLH.js +7 -0
  307. package/dist/{subagents-loader-SXETS2F2.js.map → subagents-loader-CPFVLWLH.js.map} +1 -1
  308. package/dist/subagents-loader.cjs +4 -4
  309. package/dist/subagents-loader.js +3 -3
  310. package/dist/subagents.cjs +2 -2
  311. package/dist/subagents.js +1 -1
  312. package/dist/task-store.cjs +5 -5
  313. package/dist/task-store.js +2 -2
  314. package/dist/workflow.cjs +28 -28
  315. package/dist/workflow.js +5 -5
  316. package/package.json +1 -1
  317. package/dist/agent-66U5QCPF.js +0 -63
  318. package/dist/agent-CB27KF6O.cjs +0 -72
  319. package/dist/agent-session-store-22GKA7O4.js +0 -6
  320. package/dist/agent-session-store-WP6NGDVX.cjs +0 -23
  321. package/dist/chunk-26UQG242.cjs.map +0 -1
  322. package/dist/chunk-3E3VSMB6.cjs.map +0 -1
  323. package/dist/chunk-3KIUY67P.cjs.map +0 -1
  324. package/dist/chunk-3WKWBYPO.cjs.map +0 -1
  325. package/dist/chunk-5645PMVU.cjs.map +0 -1
  326. package/dist/chunk-AT2PESXB.cjs.map +0 -1
  327. package/dist/chunk-AUH2EVWY.cjs.map +0 -1
  328. package/dist/chunk-BWYC7RZG.cjs.map +0 -1
  329. package/dist/chunk-CHKV2L2Y.cjs.map +0 -1
  330. package/dist/chunk-EQ5IDL6W.cjs.map +0 -1
  331. package/dist/chunk-FLDHYF5C.cjs.map +0 -1
  332. package/dist/chunk-FTXY4D44.cjs.map +0 -1
  333. package/dist/chunk-L7V4DDIE.cjs.map +0 -1
  334. package/dist/chunk-QG4SXZ2A.cjs.map +0 -1
  335. package/dist/chunk-SA6K24NB.cjs.map +0 -1
  336. package/dist/chunk-SETHRLQS.cjs.map +0 -1
  337. package/dist/chunk-SPEN7RJU.cjs +0 -18
  338. package/dist/chunk-SWALPLFQ.cjs.map +0 -1
  339. package/dist/chunk-TDED5XES.js.map +0 -1
  340. package/dist/chunk-UDAKAE4Z.cjs.map +0 -1
  341. package/dist/chunk-VWYFGE27.cjs.map +0 -1
  342. package/dist/chunk-XOU3CL7S.cjs.map +0 -1
  343. package/dist/chunk-YQ3XC6C2.cjs.map +0 -1
  344. package/dist/chunk-ZOFRNNZD.cjs.map +0 -1
  345. package/dist/context-4RSI3AXT.cjs +0 -24
  346. package/dist/context-7EBZST3L.js +0 -7
  347. package/dist/fs-session-store-CYNTEPJZ.cjs +0 -20
  348. package/dist/fs-session-store-MYQEVUFL.js +0 -11
  349. package/dist/generate-object-A5F576IT.cjs +0 -20
  350. package/dist/index-manager-2KH75BRW.cjs +0 -27
  351. package/dist/index-manager-NF2WRLOU.js +0 -18
  352. package/dist/stream-object-AS4YYM4B.cjs +0 -20
  353. package/dist/stream-object-EKM4WGTI.js +0 -7
  354. package/dist/subagents-loader-KLWF4QPD.cjs +0 -16
  355. package/dist/subagents-loader-SXETS2F2.js +0 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/memory/storage/chunk-markdown.ts","../src/internal/memory/corpus-sync.ts","../src/internal/memory/escape-like-pattern.ts","../src/internal/memory/memory-index.ts","../src/internal/memory/lance-memory-adapter.ts","../src/internal/memory/index-manager-dispatch.ts","../src/internal/memory/index-repository.ts","../src/internal/memory/sqlite-vec-loader.ts","../src/internal/memory/vec-index.ts","../src/internal/memory/index-manager.ts"],"names":["createHash"],"mappings":";;;;;;;;AA6BA,IAAM,UAAA,GAAa,uBAAA;AASZ,SAAS,aAAA,CAAc,IAAA,EAAc,OAAA,GAAgC,EAAC,EAAkB;AAC7F,EAAA,MAAM,QAAA,GAAW,QAAQ,QAAA,IAAY,GAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAC/B,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC7B,EAAA,MAAM,GAAA,GAAwB,EAAE,MAAA,EAAQ,EAAC,EAAG,KAAA,EAAO,EAAC,EAAG,KAAA,EAAO,CAAA,EAAG,OAAA,EAAS,MAAA,EAAU;AACpF,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,IAAA,GAAO,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA;AACzB,IAAA,MAAM,aAAa,CAAA,GAAI,CAAA;AACvB,IAAA,WAAA,CAAY,GAAA,EAAK,IAAA,EAAM,UAAA,EAAY,QAAQ,CAAA;AAAA,EAC7C;AACA,EAAA,gBAAA,CAAiB,GAAA,EAAK,KAAA,CAAM,MAAA,EAAQ,QAAQ,CAAA;AAC5C,EAAA,OAAO,GAAA,CAAI,MAAA;AACb;AAEA,SAAS,WAA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;AAAA,EAEQ,iBACN,GAAA,EAC8C;AAC9C,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,cAAA,CAAe,GAAG,CAAA;AACzC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAC,GAAA,KAAQ;AACvB,MAAA,MAAM,SAAA,GAAY,MAAA,CAAO,GAAA,CAAI,UAAA,IAAc,CAAC,CAAA;AAC5C,MAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,QAAA,IAAY,CAAC,CAAA;AACxC,MAAA,MAAM,IAAA,GAAO,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAChC,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AAAA,QACtB,IAAA;AAAA,QACA,SAAA;AAAA,QACA,OAAA;AAAA,QACA,KAAA,EAAO,CAAA;AAAA,QACP,SAAA,EAAW,CAAA;AAAA,QACX,SAAS,eAAA,CAAgB,MAAA,CAAO,GAAA,CAAI,IAAA,IAAQ,EAAE,CAAC,CAAA;AAAA,QAC/C,MAAA,EAAQ,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AAAA,QACzB,UAAU,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,SAAS,IAAI,OAAO,CAAA;AAAA,OAC3C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,KAAK,KAAA,EAAM;AAAA,EAClB;AACF","file":"chunk-3BBTHFGJ.js","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport type { MemoryChunk } from \"../types.js\";\n\n/**\n * Split a markdown document into semantically meaningful chunks (ADR D1 of\n * memory-system-peer-project-parity).\n *\n * Algorithm:\n * 1. Walk lines tracking the current heading (latest `^#+ ` line).\n * 2. Split chunks at the next heading boundary AND on blank-line paragraph\n * boundaries.\n * 3. If a single paragraph exceeds `maxChars`, split it at the nearest\n * whitespace ≤ maxChars (word-aligned per edge-case review EC-6) —\n * never mid-word.\n *\n * Mirrors peer-project's `chunkMarkdown` from\n * `packages/memory-host-sdk/src/host/chunk-markdown.ts`.\n *\n * @internal\n */\n\nexport interface ChunkMarkdownOptions {\n /** Maximum chars per chunk. Default 800. */\n maxChars?: number;\n /** Minimum chars per chunk (avoids splintering tiny lines). Default 80. */\n minChars?: number;\n}\n\nconst HEADING_RE = /^(#{1,6})\\s+(.+?)\\s*$/;\n\ninterface ChunkAccumulator {\n chunks: MemoryChunk[];\n lines: string[];\n start: number;\n heading: string | undefined;\n}\n\nexport function chunkMarkdown(text: string, options: ChunkMarkdownOptions = {}): MemoryChunk[] {\n const maxChars = options.maxChars ?? 800;\n if (text.length === 0) return [];\n const lines = text.split(\"\\n\");\n const acc: ChunkAccumulator = { chunks: [], lines: [], start: 1, heading: undefined };\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n const lineNumber = i + 1;\n processLine(acc, line, lineNumber, maxChars);\n }\n flushAccumulator(acc, lines.length, maxChars);\n return acc.chunks;\n}\n\nfunction processLine(\n acc: ChunkAccumulator,\n line: string,\n lineNumber: number,\n maxChars: number,\n): void {\n const headingMatch = HEADING_RE.exec(line);\n const isBlank = line.trim().length === 0;\n if (headingMatch !== null && acc.lines.length > 0) {\n flushAccumulator(acc, lineNumber - 1, maxChars);\n }\n if (headingMatch !== null) acc.heading = headingMatch[2];\n acc.lines.push(line);\n if (isBlank && acc.lines.length > 1) {\n const joined = acc.lines.join(\"\\n\");\n if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);\n }\n}\n\nfunction flushAccumulator(acc: ChunkAccumulator, endLineExclusive: number, maxChars: number): void {\n if (acc.lines.length === 0) return;\n const chunkText = acc.lines.join(\"\\n\");\n if (chunkText.trim().length === 0) {\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n return;\n }\n if (chunkText.length > maxChars) {\n pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);\n } else {\n acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));\n }\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n}\n\nfunction buildChunk(\n text: string,\n startLine: number,\n endLine: number,\n heading: string | undefined,\n): MemoryChunk {\n return {\n startLine,\n endLine,\n text,\n hash: createHash(\"sha256\").update(text).digest(\"hex\"),\n ...(heading !== undefined ? { heading } : {}),\n };\n}\n\nfunction pushOversizedSlices(\n chunks: MemoryChunk[],\n text: string,\n startLine: number,\n heading: string | undefined,\n maxChars: number,\n): void {\n let remaining = text;\n let lineCursor = startLine;\n while (remaining.length > maxChars) {\n const splitAt = findWordBoundarySplit(remaining, maxChars);\n const slice = remaining.slice(0, splitAt);\n const sliceLines = slice.split(\"\\n\").length;\n chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));\n remaining = remaining.slice(splitAt).replace(/^\\s+/, \"\");\n lineCursor += sliceLines - 1;\n }\n if (remaining.length > 0) {\n const sliceLines = remaining.split(\"\\n\").length;\n chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));\n }\n}\n\n/**\n * Find a split point ≤ maxChars that lands on a whitespace boundary so we\n * don't slice a word in half. Falls back to maxChars if no whitespace is\n * within range (very rare — a single token > maxChars).\n */\nfunction findWordBoundarySplit(text: string, maxChars: number): number {\n if (text.length <= maxChars) return text.length;\n // Walk backward from maxChars looking for whitespace.\n for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {\n if (/\\s/.test(text[i] ?? \"x\")) return i;\n }\n // No whitespace within 200 chars of the cap — accept a hard split.\n return maxChars;\n}\n","/**\n * The corpus walk: read every markdown file under the memory root, and re-chunk the ones that\n * changed.\n *\n * One of the four concerns that shared `IndexManager`, and the one with the most distinct reason to\n * change — \"which files are in the corpus and when is one stale\" is a question about the filesystem,\n * not about search or about the schema. It takes a {@link MemoryIndexRepository} rather than a\n * database, so it cannot reach past it into SQL.\n *\n * The staleness test is the content hash, NOT the mtime. mtime is written into `files` for\n * observability; a file touched without being edited must not cost a re-chunk, and a file restored\n * from a backup with an older mtime must not be skipped.\n *\n * @internal\n */\n\nimport { readFile, stat } from \"node:fs/promises\";\nimport { collectMarkdownFiles, sha256 } from \"./index-manager-helpers.js\";\nimport type { MemoryIndexRepository } from \"./index-repository.js\";\nimport { chunkMarkdown } from \"./storage/chunk-markdown.js\";\nimport type { MemoryRoot } from \"./storage/memory-root.js\";\n\nexport interface CorpusSyncCounts {\n readonly filesScanned: number;\n readonly filesUpdated: number;\n readonly chunksWritten: number;\n}\n\nexport async function syncCorpus(\n repo: MemoryIndexRepository,\n memoryRoot: MemoryRoot,\n): Promise<CorpusSyncCounts> {\n const files = await collectMarkdownFiles(memoryRoot);\n const existingByPath = repo.filesByPath();\n let filesUpdated = 0;\n let chunksWritten = 0;\n\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n if (existingByPath.get(entry.absolutePath)?.hash === hash) continue;\n\n const stats = await stat(entry.absolutePath);\n const fileId = repo.upsertFile({\n absPath: entry.absolutePath,\n relPath: entry.relPath,\n hash,\n mtimeMs: stats.mtimeMs,\n source: entry.source,\n });\n repo.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) repo.insertChunk({ fileId, ...chunk });\n\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n\n return { filesScanned: files.length, filesUpdated, chunksWritten };\n}\n","/**\n * Escapes a user query for a SQL `LIKE ... ESCAPE '\\'` clause.\n *\n * The order of the three replacements is the whole correctness argument, so it is its own\n * function rather than a chain inline at the call site.\n *\n * The previous version escaped `%` and `_` but not the escape character itself, which is the\n * defect CodeQL reports as `js/incomplete-sanitization` (alerts #14, #15). Two things went wrong,\n * and the second is the one that matters:\n *\n * \"back\\slash\" -> \"%back\\slash%\" the `\\s` is an escape of `s`, which LIKE does not define\n * \"x\\%y\" -> \"%x\\\\%y%\" the inserted `\\` is consumed escaping the user's `\\`,\n * leaving `%` UNESCAPED — a wildcard the caller did not\n * write, matching anything between `x\\` and `y`\n *\n * The second is wildcard injection: a search for a literal string silently becomes a scan. In a\n * memory index that is both a wrong answer and a way to pull back rows the query never asked for.\n *\n * Escaping the backslash FIRST is what fixes it — afterwards every `\\` in the string is one this\n * function put there, so the later replacements cannot collide with a user-supplied one.\n */\nexport function escapeLikePattern(query: string): string {\n return `%${query.replace(/\\\\/g, \"\\\\\\\\\").replace(/%/g, \"\\\\%\").replace(/_/g, \"\\\\_\")}%`;\n}\n","/**\n * Common `MemoryIndex` interface shared between the SQLite-backed\n * `IndexManager` (default) and the Lance-backed adapter (ADR D43, shipped\n * v1.4.0 via lancedb-backend-ship-v1-1 plan).\n *\n * Consumers (`local-agent-memory.ts`, `active-memory.ts`, `tools.ts`,\n * `runActiveMemory`) only ever call `sync()`, `search()`, `status()`,\n * `close()` — the union of those four methods is the portable surface.\n *\n * Why a separate file (vs declaring inline in `index-manager.ts`)? D43\n * promised \"extract an abstract `MemoryIndex` interface in\n * `internal/memory/index-interface.ts`\". Keeping the contract physically\n * separated from one of its implementations preserves OCP — future\n * backends (Qdrant, PGVector) can land without touching IndexManager.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\n\n// Re-export consumer-facing shapes for stable internal import paths.\nexport type { IndexStatus, MemorySearchHit, SearchOptions };\n\nexport interface SyncResult {\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n /**\n * Whether this backend actually walked a corpus.\n *\n * REQUIRED, not optional, and that is the point. `MemoryIndex` has two implementers and consumers\n * hold the interface: `IndexManager` walks files, and `LanceMemoryAdapter` has no corpus to walk —\n * it is a vector store fed by explicit `addFacts`. The adapter used to answer with a frozen\n * all-zeros result, which a caller cannot tell apart from a real sync that found nothing to do.\n * The comment above it stated that as the intention (\"so callers' existing logging does not\n * break\"), which is the substitution defect written down as a feature.\n *\n * A required boolean forces every implementer to say which case it is in, and forces the compiler\n * to notice a new implementer that forgot. An optional flag would have let the next backend\n * reproduce the silence.\n */\n supported: boolean;\n}\n\n/**\n * Common search-options parser used by both `IndexManager.search` and\n * `LanceMemoryAdapter.search`. Returns the normalized cap + minimum-score\n * floor — eliminates jscpd duplication while keeping per-backend search\n * logic distinct.\n */\nexport function parseSearchOptions(options: SearchOptions = {}): {\n maxResults: number;\n minScore: number;\n} {\n return {\n maxResults: Math.max(1, options.maxResults ?? 10),\n minScore: options.minScore ?? 0,\n };\n}\n\nexport interface MemoryIndex {\n /**\n * Walk the memory corpus + reindex changed files. Lance backend has no\n * markdown corpus to walk — its adapter returns zero counts (no-op) and\n * relies on explicit `addFact` calls instead.\n */\n sync(): Promise<SyncResult>;\n\n /**\n * Semantic + textual search over the indexed corpus. Both backends\n * return the same `MemorySearchHit[]` shape; Lance leaves `textScore`\n * undefined (vector-only — no FTS5 layer).\n */\n search(query: string, options?: SearchOptions): Promise<MemorySearchHit[]>;\n\n /** Snapshot of the index health (backend type + counts). */\n status(): IndexStatus;\n\n /** Release native handles. Idempotent. */\n close(): Promise<void> | void;\n}\n","/**\n * `LanceMemoryAdapter` — wraps `LanceIndex` to expose the common\n * `MemoryIndex` interface (sync/search/status/close) so consumers of\n * `IndexManager.open({ backend: \"lance\" })` get a drop-in replacement\n * for the SQLite-backed `IndexManager`.\n *\n * Semantic deltas vs SQLite (documented so callers know what to expect):\n *\n * - `sync()` is a NO-OP. Lance is a pure vector store — there is no\n * markdown corpus to crawl. It returns zero counts with `supported: false`\n * so the result is not mistaken for a sync that found nothing. Consumers\n * writing facts hold a `LanceIndex` and call `addFacts` on it; the adapter\n * does not hand its adaptee out.\n * - `search()` is HYBRID, not vector-only. Lance supplies the vector distance\n * and `translateLanceHit` adds a client-side term-overlap ratio (T4.5), so\n * `textScore` is a real number in 0..1 and `score` is `0.7 * vectorScore +\n * 0.3 * textScore` — never `=== vectorScore`. This block said the opposite\n * for as long as T4.5 has been shipped, while the docblock 90 lines below\n * described the change correctly, so the two halves of one file disagreed\n * and the header is the half a caller reads.\n * - `status()` reports `backend: \"hybrid\"` only when an embedding runtime\n * is wired (always the case for Lance — embedding is required at open).\n * Both counts are 0 with `countsExact: false`: the port declares `status()`\n * synchronous and Lance's row count is async, so nothing can be measured\n * here. The zeros are placeholders and the flag says which.\n *\n * Ships with the lancedb-backend-ship-v1-1 plan (close D12, supersede via\n * D43). v1.4.0 of `@theokit/sdk`.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\nimport { type HybridWeights, resolveWeights } from \"./index-manager-helpers.js\";\nimport type { LanceIndex } from \"./lance-index.js\";\nimport { type MemoryIndex, parseSearchOptions, type SyncResult } from \"./memory-index.js\";\n\n/**\n * Default namespace used when consumers call `search()` without specifying\n * one. The SQLite `IndexManager` does not surface namespace in its public\n * `search()` signature either — both backends therefore behave consistently\n * under the \"single-workspace, single-namespace\" assumption that v1.4 ships.\n *\n * v1.5 candidate: surface `namespace` in `SearchOptions` (additive — no\n * breaking change) so multi-tenant Lance consumers can scope queries.\n */\nconst DEFAULT_NAMESPACE = \"default\";\n\n/**\n * Lance has no corpus to walk, and the result now SAYS so.\n *\n * The counts stay zero — inventing numbers would trade one false claim for another. What changed is\n * `supported: false`: an all-zeros result was previously indistinguishable from a real sync that\n * found nothing to reindex, and the comment above this constant used to present that as the goal\n * (\"so callers' existing logging does not break\"). A caller can now tell \"nothing to do\" from\n * \"this backend does not do this\".\n */\nconst UNSUPPORTED_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n supported: false,\n});\n\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * Not applicable to Lance — see file header. Returns zero counts with `supported: false` so a\n * caller can distinguish this from a real sync that found nothing.\n */\n async sync(): Promise<SyncResult> {\n return UNSUPPORTED_SYNC_RESULT;\n }\n\n // jscpd:ignore-start — search signature + early-out is idiomatic\n // overlap with IndexManager.search; further factoring would hurt\n // readability (the bodies diverge sharply right after).\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n // jscpd:ignore-end\n const lanceHits = await this.inner.search(query, {\n namespace: DEFAULT_NAMESPACE,\n limit: maxResults * 2,\n ...(options.sources !== undefined ? { sources: options.sources } : {}),\n });\n return lanceHits\n .filter((h) => h.score >= minScore)\n .slice(0, maxResults)\n .map((h) => translateLanceHit(h, query, resolveWeights(options)));\n }\n\n status(): IndexStatus {\n // The Lance API is async and `status()` is not, so no count can be taken here. The zeros are\n // placeholders and `countsExact: false` says so — previously they were indistinguishable from a\n // measured empty index, so a caller testing `chunksIndexed > 0` got a false negative on every\n // run regardless of how many rows the table held.\n //\n // There is deliberately no escape hatch. This class used to carry `unwrap(): LanceIndex`,\n // documented as being for \"the migration tool, benchmark script\" — measured 2026-09-01, it had\n // ZERO callers anywhere in the monorepo, including those two, which hold a `LanceIndex`\n // directly and never open the adapter. What it did have was this comment pointing at it, which\n // made the leak read as the supported way to work around the limitation. A caller that needs\n // the real count needs `LanceIndex`, and the honest way to get one is to open one.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n countsExact: false,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\n }\n}\n\n/**\n * Translate `LanceSearchHit` to `MemorySearchHit`. Field mapping:\n *\n * - `id` → `path` (Lance has no file-system provenance; use opaque id)\n * - `text` → `snippet` (truncated to 200 chars matching IndexManager convention)\n * - `score` → combined (0.7 × vectorScore + 0.3 × textScore)\n * - `vectorScore` → from Lance's distance metric\n * - `textScore` → T4.5 client-side term-overlap ratio (removes ADR D43 vector-only caveat)\n * - `source` → `source`\n * - synthetic `startLine: 0, endLine: 0` (Lance has no line info)\n * - synthetic `citation: id` (no path:line citation available)\n */\nfunction translateLanceHit(\n hit: { id: string; text: string; source: \"memory\" | \"sessions\" | \"wiki\"; score: number },\n query: string | undefined,\n weights: HybridWeights,\n): MemorySearchHit {\n const textScore = query !== undefined ? computeTermOverlapScore(query, hit.text) : 0;\n const vectorScore = hit.score;\n // The CALLER's weights, through the same `resolveWeights` the SQLite path uses. These were the\n // literals 0.7 and 0.3, so a caller that tuned `vectorWeight` / `textWeight` had its tuning applied\n // on one backend and silently dropped on the other — the shape of failure that makes a swap-in\n // backend untrustworthy. The defaults differ between the two (0.6/0.4 from resolveWeights, versus\n // the 0.7/0.3 written here), so unweighted results move slightly; that is the point, since one of\n // the two numbers was not the contract's.\n const combined =\n (vectorScore * weights.vectorWeight + textScore * weights.textWeight) / weights.total;\n return {\n path: hit.id,\n startLine: 0,\n endLine: 0,\n score: combined,\n textScore,\n vectorScore,\n snippet: hit.text.slice(0, 200),\n source: hit.source,\n citation: hit.id,\n };\n}\n\n/**\n * T4.5 — Client-side term-overlap score for Lance hybrid search.\n * Counts what fraction of query terms appear in the text (case-insensitive).\n * Simple but effective for re-ranking vector hits by lexical relevance.\n * Returns 0..1 where 1 = all query terms present.\n */\nfunction computeTermOverlapScore(query: string, text: string): number {\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 1);\n if (queryTerms.length === 0) return 0;\n const textLower = text.toLowerCase();\n const matched = queryTerms.filter((term) => textLower.includes(term)).length;\n return matched / queryTerms.length;\n}\n","/**\n * Dispatch helpers for `IndexManager.open`. Extracted to keep\n * `index-manager.ts` under the G8 400-LoC budget (lancedb-backend-ship-v1-1).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryBackend, OpenIndexOptions } from \"./index-manager-contract.js\";\nimport { LanceIndex } from \"./lance-index.js\";\nimport { LanceMemoryAdapter } from \"./lance-memory-adapter.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\n\n/** Valid backend identifiers — runtime guard against TS-narrowing escapes (EC-1). */\nexport const VALID_BACKENDS: readonly MemoryBackend[] = [\"sqlite-vec\", \"lance\"];\n\n/**\n * EC-1: runtime guard for `opts.backend`. TS union is compile-time only;\n * consumers passing JS `as any` typos must hit a typed error, not silent\n * SQLite fallback.\n */\nexport function assertValidBackend(backend: string): asserts backend is MemoryBackend {\n if (!VALID_BACKENDS.includes(backend as MemoryBackend)) {\n throw new ConfigurationError(\n `Invalid memory backend \"${backend}\". Valid values: ${VALID_BACKENDS.join(\", \")}.`,\n { code: \"invalid_memory_backend\" },\n );\n }\n}\n\n/**\n * Lance-path open. Throws `lance_requires_embedding` when no embedding\n * runtime is provided (Lance is vector-only — no FTS fallback).\n * Surfaces `lance_backend_unavailable` from LanceIndex.open when peer\n * dep is absent.\n */\nexport async function openLanceIndex(opts: OpenIndexOptions): Promise<MemoryIndex> {\n if (opts.embedding === undefined) {\n throw new ConfigurationError(\n \"Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).\",\n { code: \"lance_requires_embedding\" },\n );\n }\n const lance = await LanceIndex.open({\n cwd: opts.cwd,\n embedding: opts.embedding,\n ...(opts.filePath !== undefined ? { storagePath: opts.filePath } : {}),\n });\n return new LanceMemoryAdapter(lance);\n}\n","/**\n * Every SQL string the memory index runs, in one place.\n *\n * `IndexManager` answered four questions with four independent reasons to change: the corpus walk,\n * the BM25-to-score normalisation, the vector-cache strategy, and the schema. This is the fourth.\n * Changing a column, an index or a join is now a change to THIS file, and the caller above it reads\n * as search logic rather than as SQL with scoring in between.\n *\n * The row-to-`MemorySearchHit` mapping deliberately stays with the caller: turning a row into a hit\n * involves a score, a snippet and a citation, none of which the schema knows about. Keeping it here\n * would move the normalisation into the repository and re-create the same mixture one layer down.\n *\n * Rows come back as `Record<string, unknown>` for the same reason: the repository knows what it\n * SELECTed, not what the caller will make of it.\n *\n * @internal\n */\n\nimport type { MemoryDb } from \"./index-db.js\";\n\n/** What `files` holds for one path — the pair the corpus walk compares against disk. */\nexport interface FileRow {\n readonly id: number;\n readonly hash: string;\n}\n\nexport class MemoryIndexRepository {\n constructor(private readonly db: MemoryDb) {}\n\n counts(): { files: number; chunks: number } {\n const files = this.db.prepare(\"SELECT COUNT(*) as n FROM files\").get() ?? { n: 0 };\n const chunks = this.db.prepare(\"SELECT COUNT(*) as n FROM chunks\").get() ?? { n: 0 };\n return { files: Number(files.n ?? 0), chunks: Number(chunks.n ?? 0) };\n }\n\n /**\n * FTS5 match, ordered by bm25. THROWS on an FTS5 error rather than swallowing it — whether that\n * error means \"CJK input the default tokenizer cannot segment\" or \"the table is missing\" is a\n * judgement the caller makes, and it makes it differently for each.\n */\n ftsRows(sanitizedQuery: string, limit: number): Array<Record<string, unknown>> {\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text, bm25(chunks_fts) as bm25_score\n FROM chunks_fts\n JOIN chunks ON chunks_fts.rowid = chunks.id\n JOIN files ON chunks.file_id = files.id\n WHERE chunks_fts MATCH ?\n ORDER BY bm25_score\n LIMIT ?`,\n )\n .all(sanitizedQuery, limit);\n }\n\n /** Substring scan — the CJK fallback. No relevance score exists here; the caller supplies one. */\n likeRows(escapedPattern: string, limit: number): Array<Record<string, unknown>> {\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks\n JOIN files ON chunks.file_id = files.id\n WHERE chunks.text LIKE ? ESCAPE '\\\\'\n LIMIT ?`,\n )\n .all(escapedPattern, limit) as Array<Record<string, unknown>>;\n }\n\n /** Hydrate the chunks a vector search returned by id. Empty in, empty out — no query runs. */\n chunkRowsByIds(ids: ReadonlyArray<number>): Array<Record<string, unknown>> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks JOIN files ON chunks.file_id = files.id\n WHERE chunks.id IN (${placeholders})`,\n )\n .all(...ids);\n }\n\n /** Absolute path → its row, for the corpus walk to compare hashes against disk. */\n filesByPath(): Map<string, FileRow> {\n const rows = this.db.prepare(\"SELECT id, path, hash FROM files\").all() as Array<{\n id: number;\n path: string;\n hash: string;\n }>;\n return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));\n }\n\n upsertFile(file: {\n absPath: string;\n relPath: string;\n hash: string;\n mtimeMs: number;\n source: \"memory\" | \"wiki\" | \"sessions\";\n }): number {\n const row = this.db\n .prepare(\n `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source\n RETURNING id`,\n )\n .get(file.absPath, file.relPath, Math.floor(file.mtimeMs), file.hash, file.source) as {\n id: number;\n };\n return row.id;\n }\n\n deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n insertChunk(chunk: {\n fileId: number;\n startLine: number;\n endLine: number;\n text: string;\n hash: string;\n }): void {\n this.db\n .prepare(\n \"INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(chunk.fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n\n close(): void {\n this.db.close();\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Load the `sqlite-vec` extension into an opened SQLite connection.\n *\n * Wraps the native `load(db)` call from the `sqlite-vec` npm package with a\n * typed error path (EC-8 of the edge-case review) so callers see a\n * `sqlite_vec_unavailable` ConfigurationError instead of a raw native error.\n *\n * @internal\n */\nexport async function loadSqliteVecExtension(db: MemoryDb): Promise<void> {\n try {\n const mod = await import(\"sqlite-vec\");\n const loadFn = (mod as { load?: (db: unknown) => void }).load;\n if (typeof loadFn !== \"function\") {\n throw new Error(\"sqlite-vec module exposes no `load` export\");\n }\n loadFn(db);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `sqlite-vec extension unavailable. Install \\`sqlite-vec\\` and ensure the native binary matches your Node + OS. Cause: ${message}`,\n { code: \"sqlite_vec_unavailable\", cause },\n );\n }\n}\n","import type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Vector index helpers (ADR D2 + D4 of memory-system-peer-project-parity).\n *\n * Embeddings live in `embeddings(chunk_id, vec)` — a `vec0` virtual table\n * provided by the sqlite-vec extension. Embedding identity (providerId +\n * model + dimension) lives in the `meta` table; mismatches force a full\n * re-embed sweep (EC-1).\n *\n * @internal\n */\n\nexport const META_KEY_PROVIDER_ID = \"embedding.providerId\";\nexport const META_KEY_MODEL = \"embedding.model\";\nexport const META_KEY_DIMENSION = \"embedding.dimension\";\n\nexport interface EmbeddingIdentity {\n providerId: string;\n model: string;\n dimension: number;\n}\n\nexport function readEmbeddingIdentity(db: MemoryDb): EmbeddingIdentity | undefined {\n const get = (key: string): string | undefined => {\n const row = db.prepare(\"SELECT value FROM meta WHERE key = ?\").get(key);\n return row !== undefined ? String(row.value) : undefined;\n };\n const providerId = get(META_KEY_PROVIDER_ID);\n const model = get(META_KEY_MODEL);\n const dimRaw = get(META_KEY_DIMENSION);\n if (providerId === undefined || model === undefined || dimRaw === undefined) return undefined;\n const dimension = Number(dimRaw);\n if (!Number.isFinite(dimension) || dimension <= 0) return undefined;\n return { providerId, model, dimension };\n}\n\nexport function writeEmbeddingIdentity(db: MemoryDb, identity: EmbeddingIdentity): void {\n const stmt = db.prepare(\n \"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\",\n );\n stmt.run(META_KEY_PROVIDER_ID, identity.providerId);\n stmt.run(META_KEY_MODEL, identity.model);\n stmt.run(META_KEY_DIMENSION, String(identity.dimension));\n}\n\nexport function identityMatches(a: EmbeddingIdentity, b: EmbeddingIdentity): boolean {\n return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;\n}\n\nexport function dropVectorIndex(db: MemoryDb): void {\n db.exec(\"DROP TABLE IF EXISTS embeddings\");\n}\n\nexport function createVectorIndex(db: MemoryDb, dimension: number): void {\n db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(\n chunk_id INTEGER PRIMARY KEY,\n vec FLOAT[${dimension}]\n )`);\n}\n\n/** Pack a Float32Array into a Buffer suitable for sqlite-vec BLOB binding. */\nexport function packVector(vec: ReadonlyArray<number>): Buffer {\n const f32 = new Float32Array(vec.length);\n for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;\n return Buffer.from(f32.buffer);\n}\n\nexport function upsertEmbedding(db: MemoryDb, chunkId: number, vec: ReadonlyArray<number>): void {\n // sqlite-vec vec0 virtual tables don't support UPSERT — emulate via\n // DELETE-then-INSERT. vec0 REJECTS JS Number for chunk_id columns; it\n // requires BigInt binding. Verified via repro against vec0 v0.1.9.\n const id = BigInt(chunkId);\n db.prepare(\"DELETE FROM embeddings WHERE chunk_id = ?\").run(id);\n db.prepare(\"INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)\").run(id, packVector(vec));\n}\n\nexport interface VectorHitRow {\n chunk_id: number;\n distance: number;\n}\n\nexport function vectorSearch(\n db: MemoryDb,\n query: ReadonlyArray<number>,\n k: number,\n): VectorHitRow[] {\n // sqlite-vec returns distance (lower = closer). Use KNN syntax. k needs\n // a BigInt-typed binding too.\n const rows = db\n .prepare(\n `SELECT chunk_id, distance FROM embeddings\n WHERE vec MATCH ? AND k = ?\n ORDER BY distance`,\n )\n .all(packVector(query), BigInt(k));\n return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));\n}\n\nexport interface EmbedAllArgs {\n db: MemoryDb;\n runtime: EmbeddingRuntime;\n}\n\n/** Embed every chunk that doesn't yet have a vector. */\nexport async function embedMissingChunks(args: EmbedAllArgs): Promise<number> {\n const rows = args.db\n .prepare(\n `SELECT chunks.id as id, chunks.text as text\n FROM chunks\n LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id\n WHERE embeddings.chunk_id IS NULL`,\n )\n .all();\n if (rows.length === 0) return 0;\n const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? \"\") }));\n const vectors = await args.runtime.embed(normalized.map((r) => r.text));\n for (let i = 0; i < normalized.length; i++) {\n const row = normalized[i];\n const vector = vectors[i];\n if (row === undefined || vector === undefined) continue;\n upsertEmbedding(args.db, row.id, vector);\n }\n return normalized.length;\n}\n","import { createHash } from \"node:crypto\";\nimport { diag } from \"../diagnostics.js\";\nimport { containsCjk, sanitizeFts5Query } from \"../persistence/fts5-sanitize.js\";\nimport { syncCorpus } from \"./corpus-sync.js\";\nimport type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport { LruEmbeddingCache } from \"./embedding-cache.js\";\nimport { escapeLikePattern } from \"./escape-like-pattern.js\";\nimport { defaultIndexPath, type MemoryDb, openMemoryDb } from \"./index-db.js\";\nimport { assertValidBackend, openLanceIndex } from \"./index-manager-dispatch.js\";\nimport { blendScores, resolveWeights, truncateSnippet } from \"./index-manager-helpers.js\";\nimport { MemoryIndexRepository } from \"./index-repository.js\";\nimport type { SyncResult } from \"./memory-index.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport { type MemoryRoot, memoryIndexRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n// T4.1 — query-vector LRU cache (DR4 finding #1). Keyed by\n// sha256(query); caches the embedding vector so repeated search\n// queries skip the HTTP round-trip (p99 1.5-3s → ~0ms on hit).\n// Process-wide singleton with bounded capacity (default 2000 queries).\nconst queryVectorCache = new LruEmbeddingCache(2000);\n\nimport {\n createVectorIndex,\n dropVectorIndex,\n embedMissingChunks,\n identityMatches,\n readEmbeddingIdentity,\n vectorSearch,\n writeEmbeddingIdentity,\n} from \"./vec-index.js\";\n\n/**\n * Memory index manager (ADR D2). FTS5-only at Phase 3; vector index lands in\n * Phase 5.\n *\n * Lifecycle:\n * const idx = await IndexManager.open({ cwd });\n * await idx.sync();\n * const hits = await idx.search(\"query\");\n * idx.close();\n *\n * @internal\n */\n\n// T2.1 / ADR D433 — these types now live in `index-manager-contract.ts`\n// to break the 3-cycle memory cluster. Re-exported here for back-compat\n// with downstream importers that historically pulled from this file.\nexport type {\n IndexStatus,\n MemoryBackend,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nimport type {\n IndexStatus,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nexport class IndexManager implements MemoryIndex {\n private lastSyncMs: number | undefined;\n private vectorReady = false;\n\n /** Every SQL string this class used to hold. See `index-repository.ts` for why it moved. */\n private readonly repo: MemoryIndexRepository;\n\n private constructor(\n private readonly memoryRoot: MemoryRoot,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {\n this.repo = new MemoryIndexRepository(db);\n }\n\n /**\n * Open a memory index. Dispatches to SQLite (default) or Lance (opt-in\n * via `backend: \"lance\"`). See `openLanceInternal` for Lance-specific\n * preconditions + typed errors.\n */\n static async open(opts: OpenIndexOptions & { backend: \"lance\" }): Promise<MemoryIndex>;\n static async open(\n opts: Omit<OpenIndexOptions, \"backend\"> | (OpenIndexOptions & { backend?: \"sqlite-vec\" }),\n ): Promise<IndexManager>;\n static async open(opts: OpenIndexOptions): Promise<MemoryIndex> {\n const backend = opts.backend ?? \"sqlite-vec\";\n assertValidBackend(backend);\n if (backend === \"lance\") return await openLanceIndex(opts);\n return await IndexManager.openSqliteInternal(opts);\n }\n\n /** Internal SQLite-path open. Renamed from previous public `open`. */\n private static async openSqliteInternal(opts: OpenIndexOptions): Promise<IndexManager> {\n const memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);\n // What gets INDEXED and where the DATABASE lives are two decisions, and they diverge —\n // for one directory, not for every directory (theokit-sdk#554).\n //\n // The database stays in the project store when `memory.directory` names the directory the\n // Claude Code CLI manages, because that CLI has no index format and a binary there is an\n // artefact the partner does not understand inside a directory it owns\n // (`docs/memory-decisions.md` § 1). That argument covers exactly that directory.\n //\n // It does not reach a plain directory, and treating every root as if it did leaked: the index\n // holds `chunks.text` — the fact TEXT, which FTS5 needs — so leaving it in `<cwd>` while the\n // facts move writes one operator's personal store into every repository the agent runs in.\n const filePath = opts.filePath ?? defaultIndexPath(memoryIndexRoot(opts.cwd, memoryRoot));\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(memoryRoot, db, opts.embedding);\n if (opts.embedding !== undefined) await manager.initVectorBackend(opts.embedding);\n return manager;\n }\n\n private async initVectorBackend(runtime: EmbeddingRuntime): Promise<void> {\n await loadSqliteVecExtension(this.db);\n const currentIdentity = {\n providerId: runtime.id,\n model: runtime.model,\n dimension: runtime.dimension,\n };\n const persisted = readEmbeddingIdentity(this.db);\n if (persisted !== undefined && !identityMatches(persisted, currentIdentity)) {\n // EC-1: dimension/model/provider changed — drop the vector index and\n // force a full re-embed on next sync.\n dropVectorIndex(this.db);\n }\n createVectorIndex(this.db, runtime.dimension);\n writeEmbeddingIdentity(this.db, currentIdentity);\n this.vectorReady = true;\n }\n\n /** Walk the memory corpus + (re)index changed files. */\n // Declares `Promise<SyncResult>` rather than repeating the shape inline. The inline version was a\n // structural copy of the interface it implements, so widening `SyncResult` with `supported` left\n // this method silently no longer assignable to `MemoryIndex` — the compiler caught it, which is\n // the argument for naming the type instead of restating it.\n async sync(): Promise<SyncResult> {\n const counts = await syncCorpus(this.repo, this.memoryRoot);\n let chunksEmbedded = 0;\n if (this.vectorReady && this.embedding !== undefined) {\n chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });\n }\n this.lastSyncMs = Date.now();\n // `supported: true` — this implementer genuinely walks the corpus, so its counts are a\n // measurement rather than a placeholder. See SyncResult.supported.\n return { ...counts, chunksEmbedded, supported: true };\n }\n\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n const textHits = this.ftsSearch(query, maxResults * 2);\n const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);\n const combined = this.combineHybridScores(textHits, vectorHitsById, options);\n return combined\n .filter((h) => h.score >= minScore)\n .filter((h) => options.sources === undefined || options.sources.includes(h.source))\n .slice(0, maxResults);\n }\n\n status(): IndexStatus {\n const { files, chunks } = this.repo.counts();\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: files,\n chunksIndexed: chunks,\n // Counted with SELECT COUNT(*) just above — these are measurements, not placeholders.\n countsExact: true,\n };\n if (this.lastSyncMs !== undefined) status.lastSyncMs = this.lastSyncMs;\n return status;\n }\n\n // ───── search internals ──────────────────────────────────────────────\n\n private ftsSearch(query: string, limit: number): Array<MemorySearchHit & { chunkId: number }> {\n // EC-3: short-circuit when sanitizer reduces input to empty string.\n // Calling `MATCH ''` would error inside FTS5 on some SQLite versions.\n const sanitized = sanitizeFts5Query(query);\n if (sanitized.length === 0) return [];\n let rows: Array<Record<string, unknown>> = [];\n try {\n rows = this.repo.ftsRows(sanitized, limit);\n } catch (err) {\n // T4.8 — CJK fallback: FTS5's default tokenizer chokes on CJK characters (no word boundaries).\n // Instead of returning empty, fall back to a LIKE search, which handles CJK correctly (slower\n // but correct). ADR D64 documents the trigram-routing deferral.\n //\n // GATED on the condition it was written for, and reported otherwise. The catch used to be\n // unconditional, so a corrupt database, a missing `chunks_fts` table (which happens when FTS5\n // is unavailable at open) and a disk error all became a LIKE scan over the whole table\n // returning plausible hits at a hardcoded 0.5 — degraded relevance with no signal that\n // anything had failed. The fallback still runs, because returning nothing would be worse; what\n // changes is that the operator learns the query is not being answered by the index.\n if (!containsCjk(query)) {\n diag(\n `memory FTS query failed for a non-CJK query and fell back to a LIKE scan — relevance is ` +\n `degraded and the index may be missing or corrupt: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n return this.likeSearchFallback(query, limit);\n }\n return rows.map((row) => {\n const bm25 = Number(row.bm25_score ?? 0);\n const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n path,\n startLine,\n endLine,\n score: textScore,\n textScore,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n // sneak the chunk id through for the hybrid join below\n // (cast away later)\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n /**\n * T4.8 — LIKE-based fallback for CJK and other scripts that FTS5's\n * default tokenizer cannot segment. Slower than FTS5 (full table scan)\n * but correct for any Unicode input. Returns the same shape as\n * `ftsSearch` so callers are unaware of the fallback.\n */\n private likeSearchFallback(\n query: string,\n limit: number,\n ): Array<MemorySearchHit & { chunkId: number }> {\n const rows = this.repo.likeRows(escapeLikePattern(query), limit);\n return rows.map((row) => {\n const path = String(row.rel_path ?? \"\");\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n return {\n path,\n startLine,\n endLine,\n score: 0.5, // LIKE has no relevance score — use a neutral midpoint\n textScore: 0.5,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n private async vectorSearchById(\n query: string,\n limit: number,\n ): Promise<Map<number, { vectorScore: number; snippet?: string }>> {\n if (!this.vectorReady || this.embedding === undefined) return new Map();\n // T4.1 — query-vector LRU cache. The embed call is the p99 hottest\n // path (1.5-3s per hit). Cache by sha256(query) so repeated queries\n // skip the HTTP round-trip entirely. The embedding cache (T4.4\n // globalEmbeddingCache) catches text-level dedup; this catches the\n // query-level search-result dedup on top.\n const cacheKey = createHash(\"sha256\").update(query).digest(\"hex\");\n const cached = queryVectorCache.get(cacheKey);\n const queryVec = cached ?? (await this.embedding.embed([query]))[0];\n if (queryVec === undefined) return new Map();\n if (cached === undefined) queryVectorCache.set(cacheKey, queryVec);\n const rows = vectorSearch(this.db, queryVec, limit);\n // sqlite-vec distance: lower = closer. Normalize to 0..1 with higher = better.\n const out = new Map<number, { vectorScore: number }>();\n for (const row of rows) {\n const score = 1 / (1 + Math.max(0, row.distance));\n out.set(row.chunk_id, { vectorScore: score });\n }\n return out;\n }\n\n private combineHybridScores(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n options: SearchOptions,\n ): MemorySearchHit[] {\n const weights = resolveWeights(options);\n const merged = this.mergeHits(textHits, vectorHitsById);\n const combined = [...merged.values()].map((hit) =>\n blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights),\n );\n return combined.sort((a, b) => b.score - a.score);\n }\n\n private mergeHits(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n ): Map<number, MemorySearchHit & { chunkId: number }> {\n const merged = new Map<number, MemorySearchHit & { chunkId: number }>();\n for (const hit of textHits) merged.set(hit.chunkId, hit);\n const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));\n if (missingIds.length > 0) {\n for (const hit of this.fetchChunksByIds(missingIds)) {\n merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });\n }\n }\n return merged;\n }\n\n private fetchChunksByIds(\n ids: ReadonlyArray<number>,\n ): Array<MemorySearchHit & { chunkId: number }> {\n const rows = this.repo.chunkRowsByIds(ids);\n return rows.map((row) => {\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n chunkId: Number(row.id),\n path,\n startLine,\n endLine,\n score: 0,\n textScore: 0,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n };\n });\n }\n\n close(): void {\n this.repo.close();\n }\n}\n\n// Replaced by `sanitizeFts5Query` from `internal/persistence/fts5-sanitize.ts`\n// (T5.2, ADR D64). The new sanitizer is the 6-step port of Hermes'\n// `_sanitize_fts5_query` and handles hyphens/dots/underscores correctly\n// without quoting every token.\n"]}
1
+ {"version":3,"sources":["../src/internal/memory/storage/chunk-markdown.ts","../src/internal/memory/corpus-sync.ts","../src/internal/memory/escape-like-pattern.ts","../src/internal/memory/memory-index.ts","../src/internal/memory/lance-memory-adapter.ts","../src/internal/memory/index-manager-dispatch.ts","../src/internal/memory/index-repository.ts","../src/internal/memory/sqlite-vec-loader.ts","../src/internal/memory/vec-index.ts","../src/internal/memory/index-manager.ts"],"names":["createHash"],"mappings":";;;;;;;;AA6BA,IAAM,UAAA,GAAa,uBAAA;AASZ,SAAS,aAAA,CAAc,IAAA,EAAc,OAAA,GAAgC,EAAC,EAAkB;AAC7F,EAAA,MAAM,QAAA,GAAW,QAAQ,QAAA,IAAY,GAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAC/B,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC7B,EAAA,MAAM,GAAA,GAAwB,EAAE,MAAA,EAAQ,EAAC,EAAG,KAAA,EAAO,EAAC,EAAG,KAAA,EAAO,CAAA,EAAG,OAAA,EAAS,MAAA,EAAU;AACpF,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,IAAA,GAAO,KAA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AACF","file":"chunk-L5B7EWWH.js","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport type { MemoryChunk } from \"../types.js\";\n\n/**\n * Split a markdown document into semantically meaningful chunks (ADR D1 of\n * memory-system-peer-project-parity).\n *\n * Algorithm:\n * 1. Walk lines tracking the current heading (latest `^#+ ` line).\n * 2. Split chunks at the next heading boundary AND on blank-line paragraph\n * boundaries.\n * 3. If a single paragraph exceeds `maxChars`, split it at the nearest\n * whitespace ≤ maxChars (word-aligned per edge-case review EC-6) —\n * never mid-word.\n *\n * Mirrors peer-project's `chunkMarkdown` from\n * `packages/memory-host-sdk/src/host/chunk-markdown.ts`.\n *\n * @internal\n */\n\nexport interface ChunkMarkdownOptions {\n /** Maximum chars per chunk. Default 800. */\n maxChars?: number;\n /** Minimum chars per chunk (avoids splintering tiny lines). Default 80. */\n minChars?: number;\n}\n\nconst HEADING_RE = /^(#{1,6})\\s+(.+?)\\s*$/;\n\ninterface ChunkAccumulator {\n chunks: MemoryChunk[];\n lines: string[];\n start: number;\n heading: string | undefined;\n}\n\nexport function chunkMarkdown(text: string, options: ChunkMarkdownOptions = {}): MemoryChunk[] {\n const maxChars = options.maxChars ?? 800;\n if (text.length === 0) return [];\n const lines = text.split(\"\\n\");\n const acc: ChunkAccumulator = { chunks: [], lines: [], start: 1, heading: undefined };\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n const lineNumber = i + 1;\n processLine(acc, line, lineNumber, maxChars);\n }\n flushAccumulator(acc, lines.length, maxChars);\n return acc.chunks;\n}\n\nfunction processLine(\n acc: ChunkAccumulator,\n line: string,\n lineNumber: number,\n maxChars: number,\n): void {\n const headingMatch = HEADING_RE.exec(line);\n const isBlank = line.trim().length === 0;\n if (headingMatch !== null && acc.lines.length > 0) {\n flushAccumulator(acc, lineNumber - 1, maxChars);\n }\n if (headingMatch !== null) acc.heading = headingMatch[2];\n acc.lines.push(line);\n if (isBlank && acc.lines.length > 1) {\n const joined = acc.lines.join(\"\\n\");\n if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);\n }\n}\n\nfunction flushAccumulator(acc: ChunkAccumulator, endLineExclusive: number, maxChars: number): void {\n if (acc.lines.length === 0) return;\n const chunkText = acc.lines.join(\"\\n\");\n if (chunkText.trim().length === 0) {\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n return;\n }\n if (chunkText.length > maxChars) {\n pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);\n } else {\n acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));\n }\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n}\n\nfunction buildChunk(\n text: string,\n startLine: number,\n endLine: number,\n heading: string | undefined,\n): MemoryChunk {\n return {\n startLine,\n endLine,\n text,\n hash: createHash(\"sha256\").update(text).digest(\"hex\"),\n ...(heading !== undefined ? { heading } : {}),\n };\n}\n\nfunction pushOversizedSlices(\n chunks: MemoryChunk[],\n text: string,\n startLine: number,\n heading: string | undefined,\n maxChars: number,\n): void {\n let remaining = text;\n let lineCursor = startLine;\n while (remaining.length > maxChars) {\n const splitAt = findWordBoundarySplit(remaining, maxChars);\n const slice = remaining.slice(0, splitAt);\n const sliceLines = slice.split(\"\\n\").length;\n chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));\n remaining = remaining.slice(splitAt).replace(/^\\s+/, \"\");\n lineCursor += sliceLines - 1;\n }\n if (remaining.length > 0) {\n const sliceLines = remaining.split(\"\\n\").length;\n chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));\n }\n}\n\n/**\n * Find a split point ≤ maxChars that lands on a whitespace boundary so we\n * don't slice a word in half. Falls back to maxChars if no whitespace is\n * within range (very rare — a single token > maxChars).\n */\nfunction findWordBoundarySplit(text: string, maxChars: number): number {\n if (text.length <= maxChars) return text.length;\n // Walk backward from maxChars looking for whitespace.\n for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {\n if (/\\s/.test(text[i] ?? \"x\")) return i;\n }\n // No whitespace within 200 chars of the cap — accept a hard split.\n return maxChars;\n}\n","/**\n * The corpus walk: read every markdown file under the memory root, and re-chunk the ones that\n * changed.\n *\n * One of the four concerns that shared `IndexManager`, and the one with the most distinct reason to\n * change — \"which files are in the corpus and when is one stale\" is a question about the filesystem,\n * not about search or about the schema. It takes a {@link MemoryIndexRepository} rather than a\n * database, so it cannot reach past it into SQL.\n *\n * The staleness test is the content hash, NOT the mtime. mtime is written into `files` for\n * observability; a file touched without being edited must not cost a re-chunk, and a file restored\n * from a backup with an older mtime must not be skipped.\n *\n * @internal\n */\n\nimport { readFile, stat } from \"node:fs/promises\";\nimport { collectMarkdownFiles, sha256 } from \"./index-manager-helpers.js\";\nimport type { MemoryIndexRepository } from \"./index-repository.js\";\nimport { chunkMarkdown } from \"./storage/chunk-markdown.js\";\nimport type { MemoryRoot } from \"./storage/memory-root.js\";\n\nexport interface CorpusSyncCounts {\n readonly filesScanned: number;\n readonly filesUpdated: number;\n readonly chunksWritten: number;\n}\n\nexport async function syncCorpus(\n repo: MemoryIndexRepository,\n memoryRoot: MemoryRoot,\n): Promise<CorpusSyncCounts> {\n const files = await collectMarkdownFiles(memoryRoot);\n const existingByPath = repo.filesByPath();\n let filesUpdated = 0;\n let chunksWritten = 0;\n\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n if (existingByPath.get(entry.absolutePath)?.hash === hash) continue;\n\n const stats = await stat(entry.absolutePath);\n const fileId = repo.upsertFile({\n absPath: entry.absolutePath,\n relPath: entry.relPath,\n hash,\n mtimeMs: stats.mtimeMs,\n source: entry.source,\n });\n repo.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) repo.insertChunk({ fileId, ...chunk });\n\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n\n return { filesScanned: files.length, filesUpdated, chunksWritten };\n}\n","/**\n * Escapes a user query for a SQL `LIKE ... ESCAPE '\\'` clause.\n *\n * The order of the three replacements is the whole correctness argument, so it is its own\n * function rather than a chain inline at the call site.\n *\n * The previous version escaped `%` and `_` but not the escape character itself, which is the\n * defect CodeQL reports as `js/incomplete-sanitization` (alerts #14, #15). Two things went wrong,\n * and the second is the one that matters:\n *\n * \"back\\slash\" -> \"%back\\slash%\" the `\\s` is an escape of `s`, which LIKE does not define\n * \"x\\%y\" -> \"%x\\\\%y%\" the inserted `\\` is consumed escaping the user's `\\`,\n * leaving `%` UNESCAPED — a wildcard the caller did not\n * write, matching anything between `x\\` and `y`\n *\n * The second is wildcard injection: a search for a literal string silently becomes a scan. In a\n * memory index that is both a wrong answer and a way to pull back rows the query never asked for.\n *\n * Escaping the backslash FIRST is what fixes it — afterwards every `\\` in the string is one this\n * function put there, so the later replacements cannot collide with a user-supplied one.\n */\nexport function escapeLikePattern(query: string): string {\n return `%${query.replace(/\\\\/g, \"\\\\\\\\\").replace(/%/g, \"\\\\%\").replace(/_/g, \"\\\\_\")}%`;\n}\n","/**\n * Common `MemoryIndex` interface shared between the SQLite-backed\n * `IndexManager` (default) and the Lance-backed adapter (ADR D43, shipped\n * v1.4.0 via lancedb-backend-ship-v1-1 plan).\n *\n * Consumers (`local-agent-memory.ts`, `active-memory.ts`, `tools.ts`,\n * `runActiveMemory`) only ever call `sync()`, `search()`, `status()`,\n * `close()` — the union of those four methods is the portable surface.\n *\n * Why a separate file (vs declaring inline in `index-manager.ts`)? D43\n * promised \"extract an abstract `MemoryIndex` interface in\n * `internal/memory/index-interface.ts`\". Keeping the contract physically\n * separated from one of its implementations preserves OCP — future\n * backends (Qdrant, PGVector) can land without touching IndexManager.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\n\n// Re-export consumer-facing shapes for stable internal import paths.\nexport type { IndexStatus, MemorySearchHit, SearchOptions };\n\nexport interface SyncResult {\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n /**\n * Whether this backend actually walked a corpus.\n *\n * REQUIRED, not optional, and that is the point. `MemoryIndex` has two implementers and consumers\n * hold the interface: `IndexManager` walks files, and `LanceMemoryAdapter` has no corpus to walk —\n * it is a vector store fed by explicit `addFacts`. The adapter used to answer with a frozen\n * all-zeros result, which a caller cannot tell apart from a real sync that found nothing to do.\n * The comment above it stated that as the intention (\"so callers' existing logging does not\n * break\"), which is the substitution defect written down as a feature.\n *\n * A required boolean forces every implementer to say which case it is in, and forces the compiler\n * to notice a new implementer that forgot. An optional flag would have let the next backend\n * reproduce the silence.\n */\n supported: boolean;\n}\n\n/**\n * Common search-options parser used by both `IndexManager.search` and\n * `LanceMemoryAdapter.search`. Returns the normalized cap + minimum-score\n * floor — eliminates jscpd duplication while keeping per-backend search\n * logic distinct.\n */\nexport function parseSearchOptions(options: SearchOptions = {}): {\n maxResults: number;\n minScore: number;\n} {\n return {\n maxResults: Math.max(1, options.maxResults ?? 10),\n minScore: options.minScore ?? 0,\n };\n}\n\nexport interface MemoryIndex {\n /**\n * Walk the memory corpus + reindex changed files. Lance backend has no\n * markdown corpus to walk — its adapter returns zero counts (no-op) and\n * relies on explicit `addFact` calls instead.\n */\n sync(): Promise<SyncResult>;\n\n /**\n * Semantic + textual search over the indexed corpus. Both backends\n * return the same `MemorySearchHit[]` shape; Lance leaves `textScore`\n * undefined (vector-only — no FTS5 layer).\n */\n search(query: string, options?: SearchOptions): Promise<MemorySearchHit[]>;\n\n /** Snapshot of the index health (backend type + counts). */\n status(): IndexStatus;\n\n /** Release native handles. Idempotent. */\n close(): Promise<void> | void;\n}\n","/**\n * `LanceMemoryAdapter` — wraps `LanceIndex` to expose the common\n * `MemoryIndex` interface (sync/search/status/close) so consumers of\n * `IndexManager.open({ backend: \"lance\" })` get a drop-in replacement\n * for the SQLite-backed `IndexManager`.\n *\n * Semantic deltas vs SQLite (documented so callers know what to expect):\n *\n * - `sync()` is a NO-OP. Lance is a pure vector store — there is no\n * markdown corpus to crawl. It returns zero counts with `supported: false`\n * so the result is not mistaken for a sync that found nothing. Consumers\n * writing facts hold a `LanceIndex` and call `addFacts` on it; the adapter\n * does not hand its adaptee out.\n * - `search()` is HYBRID, not vector-only. Lance supplies the vector distance\n * and `translateLanceHit` adds a client-side term-overlap ratio (T4.5), so\n * `textScore` is a real number in 0..1 and `score` is `0.7 * vectorScore +\n * 0.3 * textScore` — never `=== vectorScore`. This block said the opposite\n * for as long as T4.5 has been shipped, while the docblock 90 lines below\n * described the change correctly, so the two halves of one file disagreed\n * and the header is the half a caller reads.\n * - `status()` reports `backend: \"hybrid\"` only when an embedding runtime\n * is wired (always the case for Lance — embedding is required at open).\n * Both counts are 0 with `countsExact: false`: the port declares `status()`\n * synchronous and Lance's row count is async, so nothing can be measured\n * here. The zeros are placeholders and the flag says which.\n *\n * Ships with the lancedb-backend-ship-v1-1 plan (close D12, supersede via\n * D43). v1.4.0 of `@theokit/sdk`.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\nimport { type HybridWeights, resolveWeights } from \"./index-manager-helpers.js\";\nimport type { LanceIndex } from \"./lance-index.js\";\nimport { type MemoryIndex, parseSearchOptions, type SyncResult } from \"./memory-index.js\";\n\n/**\n * Default namespace used when consumers call `search()` without specifying\n * one. The SQLite `IndexManager` does not surface namespace in its public\n * `search()` signature either — both backends therefore behave consistently\n * under the \"single-workspace, single-namespace\" assumption that v1.4 ships.\n *\n * v1.5 candidate: surface `namespace` in `SearchOptions` (additive — no\n * breaking change) so multi-tenant Lance consumers can scope queries.\n */\nconst DEFAULT_NAMESPACE = \"default\";\n\n/**\n * Lance has no corpus to walk, and the result now SAYS so.\n *\n * The counts stay zero — inventing numbers would trade one false claim for another. What changed is\n * `supported: false`: an all-zeros result was previously indistinguishable from a real sync that\n * found nothing to reindex, and the comment above this constant used to present that as the goal\n * (\"so callers' existing logging does not break\"). A caller can now tell \"nothing to do\" from\n * \"this backend does not do this\".\n */\nconst UNSUPPORTED_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n supported: false,\n});\n\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * Not applicable to Lance — see file header. Returns zero counts with `supported: false` so a\n * caller can distinguish this from a real sync that found nothing.\n */\n async sync(): Promise<SyncResult> {\n return UNSUPPORTED_SYNC_RESULT;\n }\n\n // jscpd:ignore-start — search signature + early-out is idiomatic\n // overlap with IndexManager.search; further factoring would hurt\n // readability (the bodies diverge sharply right after).\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n // jscpd:ignore-end\n const lanceHits = await this.inner.search(query, {\n namespace: DEFAULT_NAMESPACE,\n limit: maxResults * 2,\n ...(options.sources !== undefined ? { sources: options.sources } : {}),\n });\n return lanceHits\n .filter((h) => h.score >= minScore)\n .slice(0, maxResults)\n .map((h) => translateLanceHit(h, query, resolveWeights(options)));\n }\n\n status(): IndexStatus {\n // The Lance API is async and `status()` is not, so no count can be taken here. The zeros are\n // placeholders and `countsExact: false` says so — previously they were indistinguishable from a\n // measured empty index, so a caller testing `chunksIndexed > 0` got a false negative on every\n // run regardless of how many rows the table held.\n //\n // There is deliberately no escape hatch. This class used to carry `unwrap(): LanceIndex`,\n // documented as being for \"the migration tool, benchmark script\" — measured 2026-09-01, it had\n // ZERO callers anywhere in the monorepo, including those two, which hold a `LanceIndex`\n // directly and never open the adapter. What it did have was this comment pointing at it, which\n // made the leak read as the supported way to work around the limitation. A caller that needs\n // the real count needs `LanceIndex`, and the honest way to get one is to open one.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n countsExact: false,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\n }\n}\n\n/**\n * Translate `LanceSearchHit` to `MemorySearchHit`. Field mapping:\n *\n * - `id` → `path` (Lance has no file-system provenance; use opaque id)\n * - `text` → `snippet` (truncated to 200 chars matching IndexManager convention)\n * - `score` → combined (0.7 × vectorScore + 0.3 × textScore)\n * - `vectorScore` → from Lance's distance metric\n * - `textScore` → T4.5 client-side term-overlap ratio (removes ADR D43 vector-only caveat)\n * - `source` → `source`\n * - synthetic `startLine: 0, endLine: 0` (Lance has no line info)\n * - synthetic `citation: id` (no path:line citation available)\n */\nfunction translateLanceHit(\n hit: { id: string; text: string; source: \"memory\" | \"sessions\" | \"wiki\"; score: number },\n query: string | undefined,\n weights: HybridWeights,\n): MemorySearchHit {\n const textScore = query !== undefined ? computeTermOverlapScore(query, hit.text) : 0;\n const vectorScore = hit.score;\n // The CALLER's weights, through the same `resolveWeights` the SQLite path uses. These were the\n // literals 0.7 and 0.3, so a caller that tuned `vectorWeight` / `textWeight` had its tuning applied\n // on one backend and silently dropped on the other — the shape of failure that makes a swap-in\n // backend untrustworthy. The defaults differ between the two (0.6/0.4 from resolveWeights, versus\n // the 0.7/0.3 written here), so unweighted results move slightly; that is the point, since one of\n // the two numbers was not the contract's.\n const combined =\n (vectorScore * weights.vectorWeight + textScore * weights.textWeight) / weights.total;\n return {\n path: hit.id,\n startLine: 0,\n endLine: 0,\n score: combined,\n textScore,\n vectorScore,\n snippet: hit.text.slice(0, 200),\n source: hit.source,\n citation: hit.id,\n };\n}\n\n/**\n * T4.5 — Client-side term-overlap score for Lance hybrid search.\n * Counts what fraction of query terms appear in the text (case-insensitive).\n * Simple but effective for re-ranking vector hits by lexical relevance.\n * Returns 0..1 where 1 = all query terms present.\n */\nfunction computeTermOverlapScore(query: string, text: string): number {\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 1);\n if (queryTerms.length === 0) return 0;\n const textLower = text.toLowerCase();\n const matched = queryTerms.filter((term) => textLower.includes(term)).length;\n return matched / queryTerms.length;\n}\n","/**\n * Dispatch helpers for `IndexManager.open`. Extracted to keep\n * `index-manager.ts` under the G8 400-LoC budget (lancedb-backend-ship-v1-1).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryBackend, OpenIndexOptions } from \"./index-manager-contract.js\";\nimport { LanceIndex } from \"./lance-index.js\";\nimport { LanceMemoryAdapter } from \"./lance-memory-adapter.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\n\n/** Valid backend identifiers — runtime guard against TS-narrowing escapes (EC-1). */\nexport const VALID_BACKENDS: readonly MemoryBackend[] = [\"sqlite-vec\", \"lance\"];\n\n/**\n * EC-1: runtime guard for `opts.backend`. TS union is compile-time only;\n * consumers passing JS `as any` typos must hit a typed error, not silent\n * SQLite fallback.\n */\nexport function assertValidBackend(backend: string): asserts backend is MemoryBackend {\n if (!VALID_BACKENDS.includes(backend as MemoryBackend)) {\n throw new ConfigurationError(\n `Invalid memory backend \"${backend}\". Valid values: ${VALID_BACKENDS.join(\", \")}.`,\n { code: \"invalid_memory_backend\" },\n );\n }\n}\n\n/**\n * Lance-path open. Throws `lance_requires_embedding` when no embedding\n * runtime is provided (Lance is vector-only — no FTS fallback).\n * Surfaces `lance_backend_unavailable` from LanceIndex.open when peer\n * dep is absent.\n */\nexport async function openLanceIndex(opts: OpenIndexOptions): Promise<MemoryIndex> {\n if (opts.embedding === undefined) {\n throw new ConfigurationError(\n \"Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).\",\n { code: \"lance_requires_embedding\" },\n );\n }\n const lance = await LanceIndex.open({\n cwd: opts.cwd,\n embedding: opts.embedding,\n ...(opts.filePath !== undefined ? { storagePath: opts.filePath } : {}),\n });\n return new LanceMemoryAdapter(lance);\n}\n","/**\n * Every SQL string the memory index runs, in one place.\n *\n * `IndexManager` answered four questions with four independent reasons to change: the corpus walk,\n * the BM25-to-score normalisation, the vector-cache strategy, and the schema. This is the fourth.\n * Changing a column, an index or a join is now a change to THIS file, and the caller above it reads\n * as search logic rather than as SQL with scoring in between.\n *\n * The row-to-`MemorySearchHit` mapping deliberately stays with the caller: turning a row into a hit\n * involves a score, a snippet and a citation, none of which the schema knows about. Keeping it here\n * would move the normalisation into the repository and re-create the same mixture one layer down.\n *\n * Rows come back as `Record<string, unknown>` for the same reason: the repository knows what it\n * SELECTed, not what the caller will make of it.\n *\n * @internal\n */\n\nimport type { MemoryDb } from \"./index-db.js\";\n\n/** What `files` holds for one path — the pair the corpus walk compares against disk. */\nexport interface FileRow {\n readonly id: number;\n readonly hash: string;\n}\n\nexport class MemoryIndexRepository {\n constructor(private readonly db: MemoryDb) {}\n\n counts(): { files: number; chunks: number } {\n const files = this.db.prepare(\"SELECT COUNT(*) as n FROM files\").get() ?? { n: 0 };\n const chunks = this.db.prepare(\"SELECT COUNT(*) as n FROM chunks\").get() ?? { n: 0 };\n return { files: Number(files.n ?? 0), chunks: Number(chunks.n ?? 0) };\n }\n\n /**\n * FTS5 match, ordered by bm25. THROWS on an FTS5 error rather than swallowing it — whether that\n * error means \"CJK input the default tokenizer cannot segment\" or \"the table is missing\" is a\n * judgement the caller makes, and it makes it differently for each.\n */\n ftsRows(sanitizedQuery: string, limit: number): Array<Record<string, unknown>> {\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text, bm25(chunks_fts) as bm25_score\n FROM chunks_fts\n JOIN chunks ON chunks_fts.rowid = chunks.id\n JOIN files ON chunks.file_id = files.id\n WHERE chunks_fts MATCH ?\n ORDER BY bm25_score\n LIMIT ?`,\n )\n .all(sanitizedQuery, limit);\n }\n\n /** Substring scan — the CJK fallback. No relevance score exists here; the caller supplies one. */\n likeRows(escapedPattern: string, limit: number): Array<Record<string, unknown>> {\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks\n JOIN files ON chunks.file_id = files.id\n WHERE chunks.text LIKE ? ESCAPE '\\\\'\n LIMIT ?`,\n )\n .all(escapedPattern, limit) as Array<Record<string, unknown>>;\n }\n\n /** Hydrate the chunks a vector search returned by id. Empty in, empty out — no query runs. */\n chunkRowsByIds(ids: ReadonlyArray<number>): Array<Record<string, unknown>> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n return this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks JOIN files ON chunks.file_id = files.id\n WHERE chunks.id IN (${placeholders})`,\n )\n .all(...ids);\n }\n\n /** Absolute path → its row, for the corpus walk to compare hashes against disk. */\n filesByPath(): Map<string, FileRow> {\n const rows = this.db.prepare(\"SELECT id, path, hash FROM files\").all() as Array<{\n id: number;\n path: string;\n hash: string;\n }>;\n return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));\n }\n\n upsertFile(file: {\n absPath: string;\n relPath: string;\n hash: string;\n mtimeMs: number;\n source: \"memory\" | \"wiki\" | \"sessions\";\n }): number {\n const row = this.db\n .prepare(\n `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source\n RETURNING id`,\n )\n .get(file.absPath, file.relPath, Math.floor(file.mtimeMs), file.hash, file.source) as {\n id: number;\n };\n return row.id;\n }\n\n deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n insertChunk(chunk: {\n fileId: number;\n startLine: number;\n endLine: number;\n text: string;\n hash: string;\n }): void {\n this.db\n .prepare(\n \"INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(chunk.fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n\n close(): void {\n this.db.close();\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Load the `sqlite-vec` extension into an opened SQLite connection.\n *\n * Wraps the native `load(db)` call from the `sqlite-vec` npm package with a\n * typed error path (EC-8 of the edge-case review) so callers see a\n * `sqlite_vec_unavailable` ConfigurationError instead of a raw native error.\n *\n * @internal\n */\nexport async function loadSqliteVecExtension(db: MemoryDb): Promise<void> {\n try {\n const mod = await import(\"sqlite-vec\");\n const loadFn = (mod as { load?: (db: unknown) => void }).load;\n if (typeof loadFn !== \"function\") {\n throw new Error(\"sqlite-vec module exposes no `load` export\");\n }\n loadFn(db);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `sqlite-vec extension unavailable. Install \\`sqlite-vec\\` and ensure the native binary matches your Node + OS. Cause: ${message}`,\n { code: \"sqlite_vec_unavailable\", cause },\n );\n }\n}\n","import type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Vector index helpers (ADR D2 + D4 of memory-system-peer-project-parity).\n *\n * Embeddings live in `embeddings(chunk_id, vec)` — a `vec0` virtual table\n * provided by the sqlite-vec extension. Embedding identity (providerId +\n * model + dimension) lives in the `meta` table; mismatches force a full\n * re-embed sweep (EC-1).\n *\n * @internal\n */\n\nexport const META_KEY_PROVIDER_ID = \"embedding.providerId\";\nexport const META_KEY_MODEL = \"embedding.model\";\nexport const META_KEY_DIMENSION = \"embedding.dimension\";\n\nexport interface EmbeddingIdentity {\n providerId: string;\n model: string;\n dimension: number;\n}\n\nexport function readEmbeddingIdentity(db: MemoryDb): EmbeddingIdentity | undefined {\n const get = (key: string): string | undefined => {\n const row = db.prepare(\"SELECT value FROM meta WHERE key = ?\").get(key);\n return row !== undefined ? String(row.value) : undefined;\n };\n const providerId = get(META_KEY_PROVIDER_ID);\n const model = get(META_KEY_MODEL);\n const dimRaw = get(META_KEY_DIMENSION);\n if (providerId === undefined || model === undefined || dimRaw === undefined) return undefined;\n const dimension = Number(dimRaw);\n if (!Number.isFinite(dimension) || dimension <= 0) return undefined;\n return { providerId, model, dimension };\n}\n\nexport function writeEmbeddingIdentity(db: MemoryDb, identity: EmbeddingIdentity): void {\n const stmt = db.prepare(\n \"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\",\n );\n stmt.run(META_KEY_PROVIDER_ID, identity.providerId);\n stmt.run(META_KEY_MODEL, identity.model);\n stmt.run(META_KEY_DIMENSION, String(identity.dimension));\n}\n\nexport function identityMatches(a: EmbeddingIdentity, b: EmbeddingIdentity): boolean {\n return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;\n}\n\nexport function dropVectorIndex(db: MemoryDb): void {\n db.exec(\"DROP TABLE IF EXISTS embeddings\");\n}\n\nexport function createVectorIndex(db: MemoryDb, dimension: number): void {\n db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(\n chunk_id INTEGER PRIMARY KEY,\n vec FLOAT[${dimension}]\n )`);\n}\n\n/** Pack a Float32Array into a Buffer suitable for sqlite-vec BLOB binding. */\nexport function packVector(vec: ReadonlyArray<number>): Buffer {\n const f32 = new Float32Array(vec.length);\n for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;\n return Buffer.from(f32.buffer);\n}\n\nexport function upsertEmbedding(db: MemoryDb, chunkId: number, vec: ReadonlyArray<number>): void {\n // sqlite-vec vec0 virtual tables don't support UPSERT — emulate via\n // DELETE-then-INSERT. vec0 REJECTS JS Number for chunk_id columns; it\n // requires BigInt binding. Verified via repro against vec0 v0.1.9.\n const id = BigInt(chunkId);\n db.prepare(\"DELETE FROM embeddings WHERE chunk_id = ?\").run(id);\n db.prepare(\"INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)\").run(id, packVector(vec));\n}\n\nexport interface VectorHitRow {\n chunk_id: number;\n distance: number;\n}\n\nexport function vectorSearch(\n db: MemoryDb,\n query: ReadonlyArray<number>,\n k: number,\n): VectorHitRow[] {\n // sqlite-vec returns distance (lower = closer). Use KNN syntax. k needs\n // a BigInt-typed binding too.\n const rows = db\n .prepare(\n `SELECT chunk_id, distance FROM embeddings\n WHERE vec MATCH ? AND k = ?\n ORDER BY distance`,\n )\n .all(packVector(query), BigInt(k));\n return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));\n}\n\nexport interface EmbedAllArgs {\n db: MemoryDb;\n runtime: EmbeddingRuntime;\n}\n\n/** Embed every chunk that doesn't yet have a vector. */\nexport async function embedMissingChunks(args: EmbedAllArgs): Promise<number> {\n const rows = args.db\n .prepare(\n `SELECT chunks.id as id, chunks.text as text\n FROM chunks\n LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id\n WHERE embeddings.chunk_id IS NULL`,\n )\n .all();\n if (rows.length === 0) return 0;\n const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? \"\") }));\n const vectors = await args.runtime.embed(normalized.map((r) => r.text));\n for (let i = 0; i < normalized.length; i++) {\n const row = normalized[i];\n const vector = vectors[i];\n if (row === undefined || vector === undefined) continue;\n upsertEmbedding(args.db, row.id, vector);\n }\n return normalized.length;\n}\n","import { createHash } from \"node:crypto\";\nimport { diag } from \"../diagnostics.js\";\nimport { containsCjk, sanitizeFts5Query } from \"../persistence/fts5-sanitize.js\";\nimport { syncCorpus } from \"./corpus-sync.js\";\nimport type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport { LruEmbeddingCache } from \"./embedding-cache.js\";\nimport { escapeLikePattern } from \"./escape-like-pattern.js\";\nimport { defaultIndexPath, type MemoryDb, openMemoryDb } from \"./index-db.js\";\nimport { assertValidBackend, openLanceIndex } from \"./index-manager-dispatch.js\";\nimport { blendScores, resolveWeights, truncateSnippet } from \"./index-manager-helpers.js\";\nimport { MemoryIndexRepository } from \"./index-repository.js\";\nimport type { SyncResult } from \"./memory-index.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport { type MemoryRoot, memoryIndexRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n// T4.1 — query-vector LRU cache (DR4 finding #1). Keyed by\n// sha256(query); caches the embedding vector so repeated search\n// queries skip the HTTP round-trip (p99 1.5-3s → ~0ms on hit).\n// Process-wide singleton with bounded capacity (default 2000 queries).\nconst queryVectorCache = new LruEmbeddingCache(2000);\n\nimport {\n createVectorIndex,\n dropVectorIndex,\n embedMissingChunks,\n identityMatches,\n readEmbeddingIdentity,\n vectorSearch,\n writeEmbeddingIdentity,\n} from \"./vec-index.js\";\n\n/**\n * Memory index manager (ADR D2). FTS5-only at Phase 3; vector index lands in\n * Phase 5.\n *\n * Lifecycle:\n * const idx = await IndexManager.open({ cwd });\n * await idx.sync();\n * const hits = await idx.search(\"query\");\n * idx.close();\n *\n * @internal\n */\n\n// T2.1 / ADR D433 — these types now live in `index-manager-contract.ts`\n// to break the 3-cycle memory cluster. Re-exported here for back-compat\n// with downstream importers that historically pulled from this file.\nexport type {\n IndexStatus,\n MemoryBackend,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nimport type {\n IndexStatus,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nexport class IndexManager implements MemoryIndex {\n private lastSyncMs: number | undefined;\n private vectorReady = false;\n\n /** Every SQL string this class used to hold. See `index-repository.ts` for why it moved. */\n private readonly repo: MemoryIndexRepository;\n\n private constructor(\n private readonly memoryRoot: MemoryRoot,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {\n this.repo = new MemoryIndexRepository(db);\n }\n\n /**\n * Open a memory index. Dispatches to SQLite (default) or Lance (opt-in\n * via `backend: \"lance\"`). See `openLanceInternal` for Lance-specific\n * preconditions + typed errors.\n */\n static async open(opts: OpenIndexOptions & { backend: \"lance\" }): Promise<MemoryIndex>;\n static async open(\n opts: Omit<OpenIndexOptions, \"backend\"> | (OpenIndexOptions & { backend?: \"sqlite-vec\" }),\n ): Promise<IndexManager>;\n static async open(opts: OpenIndexOptions): Promise<MemoryIndex> {\n const backend = opts.backend ?? \"sqlite-vec\";\n assertValidBackend(backend);\n if (backend === \"lance\") return await openLanceIndex(opts);\n return await IndexManager.openSqliteInternal(opts);\n }\n\n /** Internal SQLite-path open. Renamed from previous public `open`. */\n private static async openSqliteInternal(opts: OpenIndexOptions): Promise<IndexManager> {\n const memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);\n // What gets INDEXED and where the DATABASE lives are two decisions, and they diverge —\n // for one directory, not for every directory (theokit-sdk#554).\n //\n // The database stays in the project store when `memory.directory` names the directory the\n // Claude Code CLI manages, because that CLI has no index format and a binary there is an\n // artefact the partner does not understand inside a directory it owns\n // (`docs/memory-decisions.md` § 1). That argument covers exactly that directory.\n //\n // It does not reach a plain directory, and treating every root as if it did leaked: the index\n // holds `chunks.text` — the fact TEXT, which FTS5 needs — so leaving it in `<cwd>` while the\n // facts move writes one operator's personal store into every repository the agent runs in.\n const filePath = opts.filePath ?? defaultIndexPath(memoryIndexRoot(opts.cwd, memoryRoot));\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(memoryRoot, db, opts.embedding);\n if (opts.embedding !== undefined) await manager.initVectorBackend(opts.embedding);\n return manager;\n }\n\n private async initVectorBackend(runtime: EmbeddingRuntime): Promise<void> {\n await loadSqliteVecExtension(this.db);\n const currentIdentity = {\n providerId: runtime.id,\n model: runtime.model,\n dimension: runtime.dimension,\n };\n const persisted = readEmbeddingIdentity(this.db);\n if (persisted !== undefined && !identityMatches(persisted, currentIdentity)) {\n // EC-1: dimension/model/provider changed — drop the vector index and\n // force a full re-embed on next sync.\n dropVectorIndex(this.db);\n }\n createVectorIndex(this.db, runtime.dimension);\n writeEmbeddingIdentity(this.db, currentIdentity);\n this.vectorReady = true;\n }\n\n /** Walk the memory corpus + (re)index changed files. */\n // Declares `Promise<SyncResult>` rather than repeating the shape inline. The inline version was a\n // structural copy of the interface it implements, so widening `SyncResult` with `supported` left\n // this method silently no longer assignable to `MemoryIndex` — the compiler caught it, which is\n // the argument for naming the type instead of restating it.\n async sync(): Promise<SyncResult> {\n const counts = await syncCorpus(this.repo, this.memoryRoot);\n let chunksEmbedded = 0;\n if (this.vectorReady && this.embedding !== undefined) {\n chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });\n }\n this.lastSyncMs = Date.now();\n // `supported: true` — this implementer genuinely walks the corpus, so its counts are a\n // measurement rather than a placeholder. See SyncResult.supported.\n return { ...counts, chunksEmbedded, supported: true };\n }\n\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n const textHits = this.ftsSearch(query, maxResults * 2);\n const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);\n const combined = this.combineHybridScores(textHits, vectorHitsById, options);\n return combined\n .filter((h) => h.score >= minScore)\n .filter((h) => options.sources === undefined || options.sources.includes(h.source))\n .slice(0, maxResults);\n }\n\n status(): IndexStatus {\n const { files, chunks } = this.repo.counts();\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: files,\n chunksIndexed: chunks,\n // Counted with SELECT COUNT(*) just above — these are measurements, not placeholders.\n countsExact: true,\n };\n if (this.lastSyncMs !== undefined) status.lastSyncMs = this.lastSyncMs;\n return status;\n }\n\n // ───── search internals ──────────────────────────────────────────────\n\n private ftsSearch(query: string, limit: number): Array<MemorySearchHit & { chunkId: number }> {\n // EC-3: short-circuit when sanitizer reduces input to empty string.\n // Calling `MATCH ''` would error inside FTS5 on some SQLite versions.\n const sanitized = sanitizeFts5Query(query);\n if (sanitized.length === 0) return [];\n let rows: Array<Record<string, unknown>> = [];\n try {\n rows = this.repo.ftsRows(sanitized, limit);\n } catch (err) {\n // T4.8 — CJK fallback: FTS5's default tokenizer chokes on CJK characters (no word boundaries).\n // Instead of returning empty, fall back to a LIKE search, which handles CJK correctly (slower\n // but correct). ADR D64 documents the trigram-routing deferral.\n //\n // GATED on the condition it was written for, and reported otherwise. The catch used to be\n // unconditional, so a corrupt database, a missing `chunks_fts` table (which happens when FTS5\n // is unavailable at open) and a disk error all became a LIKE scan over the whole table\n // returning plausible hits at a hardcoded 0.5 — degraded relevance with no signal that\n // anything had failed. The fallback still runs, because returning nothing would be worse; what\n // changes is that the operator learns the query is not being answered by the index.\n if (!containsCjk(query)) {\n diag(\n `memory FTS query failed for a non-CJK query and fell back to a LIKE scan — relevance is ` +\n `degraded and the index may be missing or corrupt: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n return this.likeSearchFallback(query, limit);\n }\n return rows.map((row) => {\n const bm25 = Number(row.bm25_score ?? 0);\n const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n path,\n startLine,\n endLine,\n score: textScore,\n textScore,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n // sneak the chunk id through for the hybrid join below\n // (cast away later)\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n /**\n * T4.8 — LIKE-based fallback for CJK and other scripts that FTS5's\n * default tokenizer cannot segment. Slower than FTS5 (full table scan)\n * but correct for any Unicode input. Returns the same shape as\n * `ftsSearch` so callers are unaware of the fallback.\n */\n private likeSearchFallback(\n query: string,\n limit: number,\n ): Array<MemorySearchHit & { chunkId: number }> {\n const rows = this.repo.likeRows(escapeLikePattern(query), limit);\n return rows.map((row) => {\n const path = String(row.rel_path ?? \"\");\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n return {\n path,\n startLine,\n endLine,\n score: 0.5, // LIKE has no relevance score — use a neutral midpoint\n textScore: 0.5,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n private async vectorSearchById(\n query: string,\n limit: number,\n ): Promise<Map<number, { vectorScore: number; snippet?: string }>> {\n if (!this.vectorReady || this.embedding === undefined) return new Map();\n // T4.1 — query-vector LRU cache. The embed call is the p99 hottest\n // path (1.5-3s per hit). Cache by sha256(query) so repeated queries\n // skip the HTTP round-trip entirely. The embedding cache (T4.4\n // globalEmbeddingCache) catches text-level dedup; this catches the\n // query-level search-result dedup on top.\n const cacheKey = createHash(\"sha256\").update(query).digest(\"hex\");\n const cached = queryVectorCache.get(cacheKey);\n const queryVec = cached ?? (await this.embedding.embed([query]))[0];\n if (queryVec === undefined) return new Map();\n if (cached === undefined) queryVectorCache.set(cacheKey, queryVec);\n const rows = vectorSearch(this.db, queryVec, limit);\n // sqlite-vec distance: lower = closer. Normalize to 0..1 with higher = better.\n const out = new Map<number, { vectorScore: number }>();\n for (const row of rows) {\n const score = 1 / (1 + Math.max(0, row.distance));\n out.set(row.chunk_id, { vectorScore: score });\n }\n return out;\n }\n\n private combineHybridScores(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n options: SearchOptions,\n ): MemorySearchHit[] {\n const weights = resolveWeights(options);\n const merged = this.mergeHits(textHits, vectorHitsById);\n const combined = [...merged.values()].map((hit) =>\n blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights),\n );\n return combined.sort((a, b) => b.score - a.score);\n }\n\n private mergeHits(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n ): Map<number, MemorySearchHit & { chunkId: number }> {\n const merged = new Map<number, MemorySearchHit & { chunkId: number }>();\n for (const hit of textHits) merged.set(hit.chunkId, hit);\n const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));\n if (missingIds.length > 0) {\n for (const hit of this.fetchChunksByIds(missingIds)) {\n merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });\n }\n }\n return merged;\n }\n\n private fetchChunksByIds(\n ids: ReadonlyArray<number>,\n ): Array<MemorySearchHit & { chunkId: number }> {\n const rows = this.repo.chunkRowsByIds(ids);\n return rows.map((row) => {\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n chunkId: Number(row.id),\n path,\n startLine,\n endLine,\n score: 0,\n textScore: 0,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n };\n });\n }\n\n close(): void {\n this.repo.close();\n }\n}\n\n// Replaced by `sanitizeFts5Query` from `internal/persistence/fts5-sanitize.ts`\n// (T5.2, ADR D64). The new sanitizer is the 6-step port of Hermes'\n// `_sanitize_fts5_query` and handles hyphens/dots/underscores correctly\n// without quoting every token.\n"]}
@@ -1,14 +1,14 @@
1
- import { atomicWriteJson } from './chunk-M4U24U6G.js';
2
- import { assertSecureModes } from './chunk-QD6B6W6I.js';
1
+ import { atomicWriteJson } from './chunk-AZK3QM36.js';
2
+ import { assertSecureModes } from './chunk-L2KC2G7H.js';
3
3
  import { ConfigurationError } from './chunk-TNFOU6SB.js';
4
4
  import { diag } from './chunk-3OY6H3I7.js';
5
- import { existsSync, readFileSync, chmodSync, mkdirSync } from 'fs';
6
- import { createRequire } from 'module';
7
- import { homedir } from 'os';
8
- import { dirname, join } from 'path';
9
- import { randomBytes, createHash } from 'crypto';
10
- import { createServer } from 'http';
11
- import { createInterface } from 'readline/promises';
5
+ import { existsSync, readFileSync, chmodSync, mkdirSync } from 'node:fs';
6
+ import { createRequire } from 'node:module';
7
+ import { homedir } from 'node:os';
8
+ import { dirname, join } from 'node:path';
9
+ import { randomBytes, createHash } from 'node:crypto';
10
+ import { createServer } from 'node:http';
11
+ import { createInterface } from 'node:readline/promises';
12
12
 
13
13
  var KEYTAR_SERVICE = "theokit-mcp";
14
14
  function storeFilePath() {
@@ -301,5 +301,5 @@ async function readCodeFromStdin(expectedState, timeoutMs) {
301
301
  }
302
302
 
303
303
  export { getTokens, lockedRefresh, refreshAccessToken, runPkceFlow, setTokens };
304
- //# sourceMappingURL=chunk-X7CE7Y5W.js.map
305
- //# sourceMappingURL=chunk-X7CE7Y5W.js.map
304
+ //# sourceMappingURL=chunk-LG4JCJEI.js.map
305
+ //# sourceMappingURL=chunk-LG4JCJEI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/mcp/token-storage.ts","../src/internal/mcp/oauth.ts"],"names":[],"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,EAAM,KAAK,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,UAAU,OAAA,EAAQ;AAC7E,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK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W;AAChF,IAAA,EAAA,CAAG,QAAA,CAAS,kDAAkD,CAAA,CAE3D,IAAA,CAAK,CAAC,MAAA,KAAW;AAChB,MAAA,EAAA,CAAG,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,IAAI,kBAAA,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":"chunk-X7CE7Y5W.js","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"]}
1
+ {"version":3,"sources":["../src/internal/mcp/token-storage.ts","../src/internal/mcp/oauth.ts"],"names":[],"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,EAAM,KAAK,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;AAC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irSync, 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"]}
@@ -1,8 +1,8 @@
1
- import { safePathJoin, assertNoSymlinkEscape } from './chunk-PKRPV3R7.js';
2
- import { readWorkspaceDir, parseSimpleYaml } from './chunk-Q7UG242V.js';
1
+ import { safePathJoin, assertNoSymlinkEscape } from './chunk-NO6AG22P.js';
2
+ import { readWorkspaceDir, parseSimpleYaml } from './chunk-TIYQDJFK.js';
3
3
  import { ConfigurationError } from './chunk-TNFOU6SB.js';
4
- import { readFile } from 'fs/promises';
5
- import { join } from 'path';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
6
 
7
7
  // src/internal/runtime/skills/skill-frontmatter.ts
8
8
  function asString(v) {
@@ -169,5 +169,5 @@ ${lines.join("\n")}
169
169
  }
170
170
 
171
171
  export { buildSkillsBlock, discoverSkills, escapeBlockBody, loadSkillInstructions, stripSkillFrontmatter };
172
- //# sourceMappingURL=chunk-2HXTNVLM.js.map
173
- //# sourceMappingURL=chunk-2HXTNVLM.js.map
172
+ //# sourceMappingURL=chunk-LSURFRJA.js.map
173
+ //# sourceMappingURL=chunk-LSURFRJA.js.map