@theokit/sdk 4.52.1 → 4.53.1

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 (385) hide show
  1. package/CHANGELOG.md +48 -8
  2. package/LICENSE +2 -2
  3. package/README.md +5 -5
  4. package/bin/theokit-migrate-config.mjs +11 -2
  5. package/dist/{agent-BiCINq25.d.ts → agent-B9HXlwID.d.ts} +21 -8
  6. package/dist/agent-FFVV4U5N.js +50 -0
  7. package/dist/{agent-RDHK6MVT.js.map → agent-FFVV4U5N.js.map} +1 -1
  8. package/dist/agent-YLAHVHEH.cjs +59 -0
  9. package/dist/{agent-U2R2R5JP.cjs.map → agent-YLAHVHEH.cjs.map} +1 -1
  10. package/dist/{agent-Zta1kvGH.d.cts → agent-nLqeXKIX.d.cts} +21 -8
  11. package/dist/agent-session-store-DUGBAX5V.cjs +23 -0
  12. package/dist/{agent-session-store-EPX2WQI4.cjs.map → agent-session-store-DUGBAX5V.cjs.map} +1 -1
  13. package/dist/agent-session-store-TNCGL5RN.js +6 -0
  14. package/dist/{agent-session-store-JMU7ASDB.js.map → agent-session-store-TNCGL5RN.js.map} +1 -1
  15. package/dist/agent.d.ts +16 -1
  16. package/dist/auth/index.cjs +29 -28
  17. package/dist/auth/index.cjs.map +1 -1
  18. package/dist/auth/index.d.cts +1 -1
  19. package/dist/auth/index.d.ts +1 -1
  20. package/dist/auth/index.js +6 -5
  21. package/dist/auth/index.js.map +1 -1
  22. package/dist/{batch-NLIS4QTW.js → batch-UPKN4SG6.js} +9 -9
  23. package/dist/{batch-NLIS4QTW.js.map → batch-UPKN4SG6.js.map} +1 -1
  24. package/dist/{batch-WQ3AJCDV.cjs → batch-ZEFN5SO7.cjs} +26 -26
  25. package/dist/{batch-WQ3AJCDV.cjs.map → batch-ZEFN5SO7.cjs.map} +1 -1
  26. package/dist/{chunk-CY7MIMI4.cjs → chunk-2D43RD5D.cjs} +8 -8
  27. package/dist/{chunk-CY7MIMI4.cjs.map → chunk-2D43RD5D.cjs.map} +1 -1
  28. package/dist/{chunk-WLESQ3ZQ.cjs → chunk-2FYEVT2B.cjs} +121 -121
  29. package/dist/{chunk-WLESQ3ZQ.cjs.map → chunk-2FYEVT2B.cjs.map} +1 -1
  30. package/dist/{chunk-BBZYXVLZ.cjs → chunk-2ZPEDVLM.cjs} +2 -2
  31. package/dist/chunk-2ZPEDVLM.cjs.map +1 -0
  32. package/dist/{chunk-T6QUCG7L.cjs → chunk-3BK6YR5P.cjs} +4 -4
  33. package/dist/{chunk-T6QUCG7L.cjs.map → chunk-3BK6YR5P.cjs.map} +1 -1
  34. package/dist/chunk-3V7UJLQT.js +147 -0
  35. package/dist/chunk-3V7UJLQT.js.map +1 -0
  36. package/dist/{chunk-ITQ4NO4P.js → chunk-3WVMJY7F.js} +3 -3
  37. package/dist/{chunk-ITQ4NO4P.js.map → chunk-3WVMJY7F.js.map} +1 -1
  38. package/dist/{chunk-RAACTJ7C.cjs → chunk-3X6PM7DU.cjs} +4 -4
  39. package/dist/{chunk-RAACTJ7C.cjs.map → chunk-3X6PM7DU.cjs.map} +1 -1
  40. package/dist/{chunk-DEZ75ET5.js → chunk-4Q4K4WB5.js} +3 -3
  41. package/dist/{chunk-DEZ75ET5.js.map → chunk-4Q4K4WB5.js.map} +1 -1
  42. package/dist/{chunk-4X3SBHPK.js → chunk-5F5NWKPN.js} +20 -4
  43. package/dist/chunk-5F5NWKPN.js.map +1 -0
  44. package/dist/chunk-5YKNEMXR.cjs +155 -0
  45. package/dist/chunk-5YKNEMXR.cjs.map +1 -0
  46. package/dist/{chunk-3YYDHUNH.cjs → chunk-665SFFFR.cjs} +11 -11
  47. package/dist/{chunk-3YYDHUNH.cjs.map → chunk-665SFFFR.cjs.map} +1 -1
  48. package/dist/{chunk-CHVSMEKM.js → chunk-6AZDM6LK.js} +3 -3
  49. package/dist/chunk-6AZDM6LK.js.map +1 -0
  50. package/dist/{chunk-AMYY3JHQ.cjs → chunk-ADLLFY3H.cjs} +9 -9
  51. package/dist/{chunk-AMYY3JHQ.cjs.map → chunk-ADLLFY3H.cjs.map} +1 -1
  52. package/dist/{chunk-J4RY5DTI.js → chunk-B6HOIWQ6.js} +5 -5
  53. package/dist/{chunk-J4RY5DTI.js.map → chunk-B6HOIWQ6.js.map} +1 -1
  54. package/dist/{chunk-EQMLJ52C.cjs → chunk-BDTVFIPB.cjs} +26 -26
  55. package/dist/{chunk-EQMLJ52C.cjs.map → chunk-BDTVFIPB.cjs.map} +1 -1
  56. package/dist/{chunk-UJ3SXRZZ.js → chunk-BERBYXFH.js} +3 -3
  57. package/dist/{chunk-UJ3SXRZZ.js.map → chunk-BERBYXFH.js.map} +1 -1
  58. package/dist/{chunk-KZBB4YKU.js → chunk-BFYGJGC5.js} +3 -3
  59. package/dist/{chunk-KZBB4YKU.js.map → chunk-BFYGJGC5.js.map} +1 -1
  60. package/dist/{chunk-SXSPMRSV.cjs → chunk-BM6N4KHO.cjs} +21 -3
  61. package/dist/chunk-BM6N4KHO.cjs.map +1 -0
  62. package/dist/{chunk-2CFEET3Y.cjs → chunk-C4H6PB5J.cjs} +4 -4
  63. package/dist/chunk-C4H6PB5J.cjs.map +1 -0
  64. package/dist/{chunk-NFATC6ZF.cjs → chunk-C5DEO6OI.cjs} +4 -4
  65. package/dist/{chunk-NFATC6ZF.cjs.map → chunk-C5DEO6OI.cjs.map} +1 -1
  66. package/dist/{chunk-EUBGGYPH.cjs → chunk-CZ2GKKYL.cjs} +5 -5
  67. package/dist/{chunk-EUBGGYPH.cjs.map → chunk-CZ2GKKYL.cjs.map} +1 -1
  68. package/dist/{chunk-I732VEDW.js → chunk-D24WJWN2.js} +3 -3
  69. package/dist/{chunk-I732VEDW.js.map → chunk-D24WJWN2.js.map} +1 -1
  70. package/dist/{chunk-3R4ZCQAZ.cjs → chunk-D75S2X6I.cjs} +5 -5
  71. package/dist/{chunk-3R4ZCQAZ.cjs.map → chunk-D75S2X6I.cjs.map} +1 -1
  72. package/dist/{chunk-5XXUYU3M.js → chunk-DGOG5NXR.js} +3 -3
  73. package/dist/{chunk-5XXUYU3M.js.map → chunk-DGOG5NXR.js.map} +1 -1
  74. package/dist/{chunk-RTLUZKDL.cjs → chunk-E7FJOO4G.cjs} +11 -11
  75. package/dist/{chunk-RTLUZKDL.cjs.map → chunk-E7FJOO4G.cjs.map} +1 -1
  76. package/dist/{chunk-BWGXYOBZ.cjs → chunk-ELKO4ZLR.cjs} +4 -4
  77. package/dist/{chunk-BWGXYOBZ.cjs.map → chunk-ELKO4ZLR.cjs.map} +1 -1
  78. package/dist/{chunk-FBZMSLDC.cjs → chunk-EZ2YEF4F.cjs} +4 -4
  79. package/dist/{chunk-FBZMSLDC.cjs.map → chunk-EZ2YEF4F.cjs.map} +1 -1
  80. package/dist/{chunk-6GS7JI64.cjs → chunk-F77UENR6.cjs} +343 -324
  81. package/dist/chunk-F77UENR6.cjs.map +1 -0
  82. package/dist/{chunk-OZXPA3ME.js → chunk-FFM3SJTQ.js} +4 -4
  83. package/dist/{chunk-OZXPA3ME.js.map → chunk-FFM3SJTQ.js.map} +1 -1
  84. package/dist/{chunk-PLUCC4N5.js → chunk-FIOCJYLA.js} +3 -3
  85. package/dist/{chunk-PLUCC4N5.js.map → chunk-FIOCJYLA.js.map} +1 -1
  86. package/dist/{chunk-Z5U2JGEK.cjs → chunk-FOXKFTVZ.cjs} +11 -11
  87. package/dist/{chunk-Z5U2JGEK.cjs.map → chunk-FOXKFTVZ.cjs.map} +1 -1
  88. package/dist/{chunk-K42QGAKM.cjs → chunk-FPYT5WZP.cjs} +10 -10
  89. package/dist/{chunk-K42QGAKM.cjs.map → chunk-FPYT5WZP.cjs.map} +1 -1
  90. package/dist/{chunk-KELIQH7K.js → chunk-G3JWXOGY.js} +78 -58
  91. package/dist/chunk-G3JWXOGY.js.map +1 -0
  92. package/dist/{chunk-DHVNJYTO.js → chunk-GBBDINFK.js} +3 -3
  93. package/dist/{chunk-DHVNJYTO.js.map → chunk-GBBDINFK.js.map} +1 -1
  94. package/dist/{chunk-V45L2OYP.cjs → chunk-GD63JPGC.cjs} +9 -9
  95. package/dist/{chunk-V45L2OYP.cjs.map → chunk-GD63JPGC.cjs.map} +1 -1
  96. package/dist/{chunk-42PLABFU.js → chunk-GOVJO4YE.js} +5 -5
  97. package/dist/{chunk-42PLABFU.js.map → chunk-GOVJO4YE.js.map} +1 -1
  98. package/dist/{chunk-CZHPR2G7.cjs → chunk-HAWE74GQ.cjs} +8 -8
  99. package/dist/{chunk-CZHPR2G7.cjs.map → chunk-HAWE74GQ.cjs.map} +1 -1
  100. package/dist/{chunk-KIX45IKP.js → chunk-HE4BIAOS.js} +4 -4
  101. package/dist/{chunk-KIX45IKP.js.map → chunk-HE4BIAOS.js.map} +1 -1
  102. package/dist/{chunk-AM2CNBKE.js → chunk-HKCKOAIO.js} +2 -2
  103. package/dist/chunk-HKCKOAIO.js.map +1 -0
  104. package/dist/{chunk-V2EJLKGA.js → chunk-HSQ5Q3I5.js} +10 -11
  105. package/dist/chunk-HSQ5Q3I5.js.map +1 -0
  106. package/dist/{chunk-QLAWEGTZ.cjs → chunk-JIQRXKTA.cjs} +7 -7
  107. package/dist/chunk-JIQRXKTA.cjs.map +1 -0
  108. package/dist/{chunk-EFXJ5C7X.js → chunk-KSWHTR54.js} +5 -5
  109. package/dist/{chunk-EFXJ5C7X.js.map → chunk-KSWHTR54.js.map} +1 -1
  110. package/dist/{chunk-6PTCKXD3.js → chunk-LD4MOBFX.js} +8 -8
  111. package/dist/{chunk-6PTCKXD3.js.map → chunk-LD4MOBFX.js.map} +1 -1
  112. package/dist/{chunk-2YGIBOUH.cjs → chunk-LPVIRJVF.cjs} +9 -9
  113. package/dist/chunk-LPVIRJVF.cjs.map +1 -0
  114. package/dist/{chunk-M5EK7N6R.js → chunk-LS3LMQ23.js} +9 -9
  115. package/dist/{chunk-M5EK7N6R.js.map → chunk-LS3LMQ23.js.map} +1 -1
  116. package/dist/{chunk-N43XLTHZ.js → chunk-LTSTGCL6.js} +3 -3
  117. package/dist/{chunk-N43XLTHZ.js.map → chunk-LTSTGCL6.js.map} +1 -1
  118. package/dist/{chunk-W4FV7JBH.js → chunk-MSFLYJDY.js} +4 -4
  119. package/dist/chunk-MSFLYJDY.js.map +1 -0
  120. package/dist/{chunk-C4EU627W.js → chunk-N5CR3TJZ.js} +4 -4
  121. package/dist/{chunk-C4EU627W.js.map → chunk-N5CR3TJZ.js.map} +1 -1
  122. package/dist/{chunk-NACDF3PK.js → chunk-NZL4BNFQ.js} +4 -4
  123. package/dist/chunk-NZL4BNFQ.js.map +1 -0
  124. package/dist/{chunk-OI6RHLGC.cjs → chunk-OUOXM36O.cjs} +11 -11
  125. package/dist/{chunk-OI6RHLGC.cjs.map → chunk-OUOXM36O.cjs.map} +1 -1
  126. package/dist/{chunk-BXVSBYGW.js → chunk-OY7O3Q6R.js} +5 -5
  127. package/dist/{chunk-BXVSBYGW.js.map → chunk-OY7O3Q6R.js.map} +1 -1
  128. package/dist/{chunk-L7EGRCKJ.js → chunk-PBZ7HMBP.js} +4 -4
  129. package/dist/{chunk-L7EGRCKJ.js.map → chunk-PBZ7HMBP.js.map} +1 -1
  130. package/dist/{chunk-OIBHY6JQ.js → chunk-PGP7IOJ2.js} +4 -4
  131. package/dist/{chunk-OIBHY6JQ.js.map → chunk-PGP7IOJ2.js.map} +1 -1
  132. package/dist/{chunk-R7TKOQMJ.js → chunk-POWRZSK4.js} +3 -3
  133. package/dist/{chunk-R7TKOQMJ.js.map → chunk-POWRZSK4.js.map} +1 -1
  134. package/dist/{chunk-R3CKCRK3.cjs → chunk-Q4RESANI.cjs} +4 -4
  135. package/dist/{chunk-R3CKCRK3.cjs.map → chunk-Q4RESANI.cjs.map} +1 -1
  136. package/dist/{chunk-ZNEE4WWQ.cjs → chunk-QBTVATSF.cjs} +25 -24
  137. package/dist/chunk-QBTVATSF.cjs.map +1 -0
  138. package/dist/{chunk-ZSJPRPN7.js → chunk-R5YZACGK.js} +3 -3
  139. package/dist/{chunk-ZSJPRPN7.js.map → chunk-R5YZACGK.js.map} +1 -1
  140. package/dist/{chunk-ADVZIC43.cjs → chunk-RAHSWE5C.cjs} +10 -10
  141. package/dist/{chunk-ADVZIC43.cjs.map → chunk-RAHSWE5C.cjs.map} +1 -1
  142. package/dist/{chunk-NOS7PTKP.js → chunk-SEL2ZQMT.js} +7 -7
  143. package/dist/{chunk-NOS7PTKP.js.map → chunk-SEL2ZQMT.js.map} +1 -1
  144. package/dist/{chunk-XWCTBGYK.js → chunk-SK4QLUBK.js} +3 -3
  145. package/dist/chunk-SK4QLUBK.js.map +1 -0
  146. package/dist/chunk-SSDD676S.js +171 -0
  147. package/dist/chunk-SSDD676S.js.map +1 -0
  148. package/dist/{chunk-E3OCRJU6.cjs → chunk-SVO5WPZX.cjs} +11 -11
  149. package/dist/{chunk-E3OCRJU6.cjs.map → chunk-SVO5WPZX.cjs.map} +1 -1
  150. package/dist/{chunk-44IISBRZ.cjs → chunk-SZHU7A5B.cjs} +4 -4
  151. package/dist/{chunk-44IISBRZ.cjs.map → chunk-SZHU7A5B.cjs.map} +1 -1
  152. package/dist/{chunk-SDJYLCJK.cjs → chunk-TTJ54H3E.cjs} +6 -6
  153. package/dist/chunk-TTJ54H3E.cjs.map +1 -0
  154. package/dist/{chunk-HI4ZW62S.js → chunk-U4UJHOSH.js} +4 -4
  155. package/dist/chunk-U4UJHOSH.js.map +1 -0
  156. package/dist/{chunk-XGYI2KQH.js → chunk-UFIXH26P.js} +4 -4
  157. package/dist/{chunk-XGYI2KQH.js.map → chunk-UFIXH26P.js.map} +1 -1
  158. package/dist/{chunk-JJZ4NIAG.js → chunk-V26QVGUG.js} +7 -6
  159. package/dist/chunk-V26QVGUG.js.map +1 -0
  160. package/dist/{chunk-GNPI5IWZ.js → chunk-V6HWJQQV.js} +6 -5
  161. package/dist/chunk-V6HWJQQV.js.map +1 -0
  162. package/dist/{chunk-MV4TOCUK.js → chunk-VC5ABJXC.js} +3 -3
  163. package/dist/{chunk-MV4TOCUK.js.map → chunk-VC5ABJXC.js.map} +1 -1
  164. package/dist/chunk-VF7X6HDR.cjs +177 -0
  165. package/dist/chunk-VF7X6HDR.cjs.map +1 -0
  166. package/dist/{chunk-7HQVDLFI.cjs → chunk-VGPXHHF3.cjs} +11 -9
  167. package/dist/chunk-VGPXHHF3.cjs.map +1 -0
  168. package/dist/{chunk-T6ZCG5AP.cjs → chunk-VUKQL3L2.cjs} +18 -19
  169. package/dist/chunk-VUKQL3L2.cjs.map +1 -0
  170. package/dist/{chunk-PVBANCWU.cjs → chunk-VW6M4B3Z.cjs} +5 -5
  171. package/dist/{chunk-PVBANCWU.cjs.map → chunk-VW6M4B3Z.cjs.map} +1 -1
  172. package/dist/{chunk-KNZU4YO5.cjs → chunk-WQ53UQL4.cjs} +4 -4
  173. package/dist/{chunk-KNZU4YO5.cjs.map → chunk-WQ53UQL4.cjs.map} +1 -1
  174. package/dist/{chunk-6DCTL32L.cjs → chunk-XPR366DL.cjs} +17 -17
  175. package/dist/{chunk-6DCTL32L.cjs.map → chunk-XPR366DL.cjs.map} +1 -1
  176. package/dist/{chunk-7TB5U7RK.js → chunk-XROIW6BH.js} +6 -6
  177. package/dist/{chunk-7TB5U7RK.js.map → chunk-XROIW6BH.js.map} +1 -1
  178. package/dist/{chunk-ECPL5RV6.cjs → chunk-Y4AXQOT4.cjs} +8 -8
  179. package/dist/{chunk-ECPL5RV6.cjs.map → chunk-Y4AXQOT4.cjs.map} +1 -1
  180. package/dist/{chunk-E6T264NS.js → chunk-Y4I4EQFK.js} +3 -3
  181. package/dist/{chunk-E6T264NS.js.map → chunk-Y4I4EQFK.js.map} +1 -1
  182. package/dist/{chunk-FUASIT3E.cjs → chunk-ZN2DGEY3.cjs} +15 -15
  183. package/dist/{chunk-FUASIT3E.cjs.map → chunk-ZN2DGEY3.cjs.map} +1 -1
  184. package/dist/{chunk-YTO5BRBD.cjs → chunk-ZT57WTUJ.cjs} +8 -8
  185. package/dist/chunk-ZT57WTUJ.cjs.map +1 -0
  186. package/dist/compact-session-4MNKNMO2.js +21 -0
  187. package/dist/{compact-session-XLXC2CZN.js.map → compact-session-4MNKNMO2.js.map} +1 -1
  188. package/dist/compact-session-EPFBQ46Z.cjs +58 -0
  189. package/dist/{compact-session-FBVWO6B3.cjs.map → compact-session-EPFBQ46Z.cjs.map} +1 -1
  190. package/dist/compaction.cjs +16 -16
  191. package/dist/compaction.js +3 -3
  192. package/dist/concurrency.cjs +6 -6
  193. package/dist/concurrency.js +4 -4
  194. package/dist/context-7USNN6LP.cjs +22 -0
  195. package/dist/{context-4HGPCOH6.cjs.map → context-7USNN6LP.cjs.map} +1 -1
  196. package/dist/context-ENXZNF6J.js +5 -0
  197. package/dist/{context-DCECDKWN.js.map → context-ENXZNF6J.js.map} +1 -1
  198. package/dist/{cron-DyWQsEG6.d.ts → cron-BMjgFH-_.d.ts} +1 -1
  199. package/dist/{cron-DgHJnMAK.d.cts → cron-DFDdCdMM.d.cts} +1 -1
  200. package/dist/cron.cjs +33 -32
  201. package/dist/cron.d.cts +2 -2
  202. package/dist/cron.d.ts +2 -2
  203. package/dist/cron.js +32 -31
  204. package/dist/errors.cjs +21 -21
  205. package/dist/errors.js +2 -2
  206. package/dist/eval.cjs +43 -42
  207. package/dist/eval.cjs.map +1 -1
  208. package/dist/eval.js +33 -32
  209. package/dist/eval.js.map +1 -1
  210. package/dist/{executor-4SW7QGZ4.cjs → executor-2Z3LGG3I.cjs} +24 -24
  211. package/dist/{executor-4SW7QGZ4.cjs.map → executor-2Z3LGG3I.cjs.map} +1 -1
  212. package/dist/{executor-3CGPLVJL.js → executor-2Z6XJJJG.js} +7 -7
  213. package/dist/{executor-3CGPLVJL.js.map → executor-2Z6XJJJG.js.map} +1 -1
  214. package/dist/filesystem/index.cjs +7 -7
  215. package/dist/filesystem/index.js +3 -3
  216. package/dist/fs-session-store-R5FD3EN6.js +10 -0
  217. package/dist/{fs-session-store-2TF3ZWMT.js.map → fs-session-store-R5FD3EN6.js.map} +1 -1
  218. package/dist/fs-session-store-VVY2AHWG.cjs +19 -0
  219. package/dist/{fs-session-store-TL4RJTXZ.cjs.map → fs-session-store-VVY2AHWG.cjs.map} +1 -1
  220. package/dist/generate-object-AVXOJK2I.cjs +20 -0
  221. package/dist/{generate-object-E465DX5I.cjs.map → generate-object-AVXOJK2I.cjs.map} +1 -1
  222. package/dist/generate-object-WQRCXFD2.js +7 -0
  223. package/dist/{generate-object-TVQCW2IZ.js.map → generate-object-WQRCXFD2.js.map} +1 -1
  224. package/dist/index-manager-VRU3A2YL.cjs +21 -0
  225. package/dist/{index-manager-HGGL4DD5.cjs.map → index-manager-VRU3A2YL.cjs.map} +1 -1
  226. package/dist/index-manager-WS7TVKUW.js +12 -0
  227. package/dist/{index-manager-EA6FGIQG.js.map → index-manager-WS7TVKUW.js.map} +1 -1
  228. package/dist/index.cjs +143 -134
  229. package/dist/index.cjs.map +1 -1
  230. package/dist/index.d.cts +64 -8
  231. package/dist/index.d.ts +64 -8
  232. package/dist/index.js +45 -44
  233. package/dist/index.js.map +1 -1
  234. package/dist/{inject-session-UBAQ7I3G.cjs → inject-session-AUQLBDRS.cjs} +9 -9
  235. package/dist/{inject-session-UBAQ7I3G.cjs.map → inject-session-AUQLBDRS.cjs.map} +1 -1
  236. package/dist/{inject-session-UEH5MAKU.js → inject-session-GMBMJVNZ.js} +7 -7
  237. package/dist/{inject-session-UEH5MAKU.js.map → inject-session-GMBMJVNZ.js.map} +1 -1
  238. package/dist/internal/auth/auth-types.d.ts +1 -1
  239. package/dist/internal/auth/oauth-device.d.ts +2 -2
  240. package/dist/internal/local-agent/mcp-pool.d.ts +2 -4
  241. package/dist/internal/mcp/oauth.d.ts +14 -0
  242. package/dist/internal/mcp/token-storage.d.ts +18 -0
  243. package/dist/internal/memory/adapters/index.cjs +8 -8
  244. package/dist/internal/memory/adapters/index.js +7 -7
  245. package/dist/internal/persistence/atomic-write.d.cts +93 -0
  246. package/dist/internal/persistence/atomic-write.d.ts +93 -0
  247. package/dist/internal/persistence/file-lock.d.cts +13 -1
  248. package/dist/internal/persistence/file-lock.d.ts +13 -1
  249. package/dist/internal/persistence/fts5-sanitize.d.cts +9 -1
  250. package/dist/internal/persistence/fts5-sanitize.d.ts +9 -1
  251. package/dist/internal/persistence/index.cjs +25 -25
  252. package/dist/internal/persistence/index.js +6 -6
  253. package/dist/internal/persistence/session-dir.d.cts +1 -0
  254. package/dist/internal/persistence/session-dir.d.ts +1 -0
  255. package/dist/internal/persistence/session-writer.d.cts +13 -0
  256. package/dist/internal/persistence/session-writer.d.ts +13 -0
  257. package/dist/internal/persistence/sqlite-wal.d.cts +9 -1
  258. package/dist/internal/persistence/sqlite-wal.d.ts +9 -1
  259. package/dist/internal/persistence/transcript-ops.d.cts +6 -7
  260. package/dist/internal/persistence/transcript-ops.d.ts +6 -7
  261. package/dist/internal/providers/builtin/cerebras.d.ts +2 -2
  262. package/dist/internal/providers/builtin/deepinfra.d.ts +1 -1
  263. package/dist/internal/providers/catalog-source-models-dev.d.ts +1 -1
  264. package/dist/internal/runtime/lifecycle/env-policy.d.ts +1 -3
  265. package/dist/internal/security/index.cjs +13 -13
  266. package/dist/internal/security/index.js +3 -3
  267. package/dist/internal/security/path-guard.d.cts +61 -0
  268. package/dist/internal/security/path-guard.d.ts +61 -0
  269. package/dist/internal/session/compact-session.d.ts +2 -2
  270. package/dist/internal/telemetry/tracer.d.ts +24 -0
  271. package/dist/judge-call-G5SGV2M2.cjs +22 -0
  272. package/dist/{judge-call-GVIJWQVE.cjs.map → judge-call-G5SGV2M2.cjs.map} +1 -1
  273. package/dist/judge-call-MDIPTBJI.js +5 -0
  274. package/dist/{judge-call-QMKGC2ZK.js.map → judge-call-MDIPTBJI.js.map} +1 -1
  275. package/dist/mcp-auth.cjs +299 -0
  276. package/dist/mcp-auth.cjs.map +1 -0
  277. package/dist/mcp-auth.d.cts +17 -0
  278. package/dist/mcp-auth.d.ts +17 -0
  279. package/dist/mcp-auth.js +292 -0
  280. package/dist/mcp-auth.js.map +1 -0
  281. package/dist/models.cjs +22 -21
  282. package/dist/models.cjs.map +1 -1
  283. package/dist/models.js +7 -6
  284. package/dist/models.js.map +1 -1
  285. package/dist/path-safety.cjs +10 -10
  286. package/dist/path-safety.js +3 -3
  287. package/dist/persistence.cjs +38 -29
  288. package/dist/persistence.cjs.map +1 -1
  289. package/dist/persistence.js +18 -9
  290. package/dist/persistence.js.map +1 -1
  291. package/dist/project.cjs +5 -5
  292. package/dist/project.js +3 -3
  293. package/dist/registry-63ASMXT4.cjs +46 -0
  294. package/dist/{registry-UBY26R4I.cjs.map → registry-63ASMXT4.cjs.map} +1 -1
  295. package/dist/registry-O7FJ2MPM.js +9 -0
  296. package/dist/{registry-GC7BQMSV.js.map → registry-O7FJ2MPM.js.map} +1 -1
  297. package/dist/retry.cjs +4 -4
  298. package/dist/retry.js +3 -3
  299. package/dist/sandbox/bwrap.d.cts +1 -2
  300. package/dist/sandbox/bwrap.d.ts +1 -2
  301. package/dist/sandbox/index.cjs +20 -20
  302. package/dist/sandbox/index.cjs.map +1 -1
  303. package/dist/sandbox/index.js +5 -5
  304. package/dist/sandbox/index.js.map +1 -1
  305. package/dist/server/errors-envelope.cjs +14 -14
  306. package/dist/server/errors-envelope.js +3 -3
  307. package/dist/session-transcript-DOM3UTXR.cjs +50 -0
  308. package/dist/{session-transcript-TNAJ4O3M.cjs.map → session-transcript-DOM3UTXR.cjs.map} +1 -1
  309. package/dist/session-transcript-RAKEK76V.js +5 -0
  310. package/dist/{session-transcript-SKIRBEJE.js.map → session-transcript-RAKEK76V.js.map} +1 -1
  311. package/dist/skills.cjs +7 -7
  312. package/dist/skills.js +5 -5
  313. package/dist/stream-object-L3Q7PBMF.cjs +20 -0
  314. package/dist/{stream-object-T4DAMNVB.cjs.map → stream-object-L3Q7PBMF.cjs.map} +1 -1
  315. package/dist/stream-object-ZYXWS4B2.js +7 -0
  316. package/dist/{stream-object-QMNR3YFF.js.map → stream-object-ZYXWS4B2.js.map} +1 -1
  317. package/dist/subagents-loader-I56GSKAQ.js +6 -0
  318. package/dist/{subagents-loader-WN2SB6PV.js.map → subagents-loader-I56GSKAQ.js.map} +1 -1
  319. package/dist/subagents-loader-VRW73QQT.cjs +15 -0
  320. package/dist/{subagents-loader-3CXBQWWY.cjs.map → subagents-loader-VRW73QQT.cjs.map} +1 -1
  321. package/dist/subagents-loader.cjs +6 -6
  322. package/dist/subagents-loader.d.cts +1 -1
  323. package/dist/subagents-loader.d.ts +1 -1
  324. package/dist/subagents-loader.js +4 -4
  325. package/dist/subscription/index.cjs +3 -3
  326. package/dist/subscription/index.js +2 -2
  327. package/dist/task-store.cjs +7 -7
  328. package/dist/task-store.js +4 -4
  329. package/dist/types/agent.d.ts +19 -6
  330. package/dist/types/provider-profile.d.ts +2 -2
  331. package/dist/workflow.cjs +27 -27
  332. package/dist/workflow.js +6 -6
  333. package/package.json +28 -18
  334. package/dist/agent-RDHK6MVT.js +0 -49
  335. package/dist/agent-U2R2R5JP.cjs +0 -58
  336. package/dist/agent-session-store-EPX2WQI4.cjs +0 -23
  337. package/dist/agent-session-store-JMU7ASDB.js +0 -6
  338. package/dist/chunk-2CFEET3Y.cjs.map +0 -1
  339. package/dist/chunk-2YGIBOUH.cjs.map +0 -1
  340. package/dist/chunk-4X3SBHPK.js.map +0 -1
  341. package/dist/chunk-6GS7JI64.cjs.map +0 -1
  342. package/dist/chunk-7HQVDLFI.cjs.map +0 -1
  343. package/dist/chunk-AM2CNBKE.js.map +0 -1
  344. package/dist/chunk-BBZYXVLZ.cjs.map +0 -1
  345. package/dist/chunk-BKRTYDVN.js +0 -312
  346. package/dist/chunk-BKRTYDVN.js.map +0 -1
  347. package/dist/chunk-CHVSMEKM.js.map +0 -1
  348. package/dist/chunk-GNPI5IWZ.js.map +0 -1
  349. package/dist/chunk-HI4ZW62S.js.map +0 -1
  350. package/dist/chunk-JJZ4NIAG.js.map +0 -1
  351. package/dist/chunk-KELIQH7K.js.map +0 -1
  352. package/dist/chunk-NACDF3PK.js.map +0 -1
  353. package/dist/chunk-QLAWEGTZ.cjs.map +0 -1
  354. package/dist/chunk-SDJYLCJK.cjs.map +0 -1
  355. package/dist/chunk-SXSPMRSV.cjs.map +0 -1
  356. package/dist/chunk-T6ZCG5AP.cjs.map +0 -1
  357. package/dist/chunk-V2EJLKGA.js.map +0 -1
  358. package/dist/chunk-W4FV7JBH.js.map +0 -1
  359. package/dist/chunk-XK54DTRF.cjs +0 -325
  360. package/dist/chunk-XK54DTRF.cjs.map +0 -1
  361. package/dist/chunk-XWCTBGYK.js.map +0 -1
  362. package/dist/chunk-YTO5BRBD.cjs.map +0 -1
  363. package/dist/chunk-ZNEE4WWQ.cjs.map +0 -1
  364. package/dist/compact-session-FBVWO6B3.cjs +0 -57
  365. package/dist/compact-session-XLXC2CZN.js +0 -20
  366. package/dist/context-4HGPCOH6.cjs +0 -22
  367. package/dist/context-DCECDKWN.js +0 -5
  368. package/dist/fs-session-store-2TF3ZWMT.js +0 -10
  369. package/dist/fs-session-store-TL4RJTXZ.cjs +0 -19
  370. package/dist/generate-object-E465DX5I.cjs +0 -20
  371. package/dist/generate-object-TVQCW2IZ.js +0 -7
  372. package/dist/index-manager-EA6FGIQG.js +0 -12
  373. package/dist/index-manager-HGGL4DD5.cjs +0 -21
  374. package/dist/judge-call-GVIJWQVE.cjs +0 -22
  375. package/dist/judge-call-QMKGC2ZK.js +0 -5
  376. package/dist/registry-GC7BQMSV.js +0 -9
  377. package/dist/registry-UBY26R4I.cjs +0 -46
  378. package/dist/session-transcript-SKIRBEJE.js +0 -5
  379. package/dist/session-transcript-TNAJ4O3M.cjs +0 -50
  380. package/dist/stream-object-QMNR3YFF.js +0 -7
  381. package/dist/stream-object-T4DAMNVB.cjs +0 -20
  382. package/dist/subagents-loader-3CXBQWWY.cjs +0 -15
  383. package/dist/subagents-loader-WN2SB6PV.js +0 -6
  384. package/docs/error-codes.md +0 -179
  385. package/docs/harness-capability-map.md +0 -304
@@ -1,3 +1,19 @@
1
+ // src/internal/env.ts
2
+ var API_KEY_ENV_VAR = "THEOKIT_API_KEY";
3
+ function readEnv(name) {
4
+ return globalThis.process?.env?.[name];
5
+ }
6
+ function resolveApiKey(explicit) {
7
+ if (explicit !== void 0 && explicit.length > 0) {
8
+ return explicit;
9
+ }
10
+ const fromEnv = readEnv(API_KEY_ENV_VAR);
11
+ if (fromEnv !== void 0 && fromEnv.length > 0) {
12
+ return fromEnv;
13
+ }
14
+ return void 0;
15
+ }
16
+
1
17
  // src/internal/diagnostics.ts
2
18
  var SINK_SLOT = /* @__PURE__ */ Symbol.for("theokit.sdk.diagnostics.sink.v1");
3
19
  function currentSink() {
@@ -18,7 +34,7 @@ function diag(message) {
18
34
  // src/internal/security/redact.ts
19
35
  var REDACT_ENABLED = readEnvOnce();
20
36
  function readEnvOnce() {
21
- const raw = process.env.THEOKIT_REDACT_SECRETS;
37
+ const raw = readEnv("THEOKIT_REDACT_SECRETS");
22
38
  if (raw === void 0) return true;
23
39
  return ["1", "true", "yes", "on"].includes(raw.toLowerCase());
24
40
  }
@@ -147,6 +163,6 @@ function redactSecrets(text, opts) {
147
163
  return s;
148
164
  }
149
165
 
150
- export { addPattern, diag, maskToken, redactSecrets, setDiagnosticsSink };
151
- //# sourceMappingURL=chunk-4X3SBHPK.js.map
152
- //# sourceMappingURL=chunk-4X3SBHPK.js.map
166
+ export { addPattern, diag, maskToken, readEnv, redactSecrets, resolveApiKey, setDiagnosticsSink };
167
+ //# sourceMappingURL=chunk-5F5NWKPN.js.map
168
+ //# sourceMappingURL=chunk-5F5NWKPN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/env.ts","../src/internal/diagnostics.ts","../src/internal/security/redact.ts"],"names":[],"mappings":";AAKO,IAAM,eAAA,GAAkB,iBAAA;AAoBxB,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,OAAO,UAAA,CAAW,OAAA,EAAS,GAAA,GAAM,IAAI,CAAA;AACvC;AAYO,SAAS,cAAc,QAAA,EAAu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AM,CAAA,GAAA,CAAK,CAAA;AAInE,IAAA,CAAA,GAAI,EAAE,OAAA,CAAQ,aAAA,EAAe,CAAC,KAAA,EAAO,QAAgB,KAAA,KAAkB;AAOrE,MAAA,IAAI,UAAA,CAAW,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AACnC,MAAA,OAAO,GAAG,MAAM,CAAA,GAAA,CAAA;AAAA,IAClB,CAAC,CAAA;AAAA,EACH;AACA,EAAA,OAAO,CAAA;AACT","file":"chunk-5F5NWKPN.js","sourcesContent":["/**\n * Environment variable used to provide the default API key.\n *\n * @internal\n */\nexport const API_KEY_ENV_VAR = \"THEOKIT_API_KEY\";\n\n/**\n * Read an environment variable without assuming `process` exists.\n *\n * Parts of this package legitimately reach a browser: `errors.ts` is imported by the client\n * bindings that framework consumers ship to the front end, and it in turn pulls in the redaction\n * and retry modules. `process` is a Node global — a bare `process.env` in any of them throws\n * `ReferenceError: process is not defined` while the module graph is still evaluating, before a\n * single component renders. The page goes blank with one console error that names no cause.\n *\n * `globalThis.process?.env?.[name]` degrades instead: on the server it reads the variable, and in\n * a browser it yields `undefined`, which every caller here already treats as \"not set\". Bundlers\n * that inline `process.env.X` at build time keep working, because they replace the expression\n * before it ever runs.\n *\n * This is the same pattern the sibling design system uses for `NODE_ENV`, for the same reason.\n *\n * @internal\n */\nexport function readEnv(name: string): string | undefined {\n return globalThis.process?.env?.[name];\n}\n\n/**\n * Resolve the API key with the documented precedence:\n *\n * 1. Explicit `apiKey` argument.\n * 2. The `THEOKIT_API_KEY` environment variable.\n *\n * Returns `undefined` when neither is set.\n *\n * @internal\n */\nexport function resolveApiKey(explicit?: string): string | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = readEnv(API_KEY_ENV_VAR);\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return undefined;\n}\n","/**\n * The library's single diagnostics channel — silent by default (#147).\n *\n * ## The problem\n *\n * The SDK wrote diagnostics straight to `process.stderr` from hot paths — 92 sites across 51\n * files under `internal/`. In a TUI host (Ink, alternate screen), those writes interleave with the\n * render and **corrupt the frame**. And the host had no way to intercept them: there was no\n * injectable logger. One consumer went as far as installing `proper-lockfile` just to silence ONE\n * of them.\n *\n * A library cannot assume `stdout`/`stderr` are free sinks. The application owns the terminal, not\n * the dependency.\n *\n * ## The contract\n *\n * - **`setDiagnosticsSink(fn)`** hands the messages to the application, which decides where to put\n * them (a status line, a file, a panel). It is what was missing for a TUI to coexist with the SDK.\n * - **With no sink, nothing is emitted.** A library does not own the host's terminal.\n *\n * ## Silent by default, and how 36 suites survived the flip\n *\n * The default WAS `stderr`, and 36 test files spy on `process.stderr.write` to assert a given\n * warning is emitted. That contract is real and had to survive; migrating all 36 by hand, across\n * four different spy styles, is how you weaken 36 suites in one commit.\n *\n * So the flip happened at the default, and `vitest.setup.ts` installs a sink that FORWARDS to\n * `stderr` for the duration of every test. Those assertions still test what they always tested —\n * \"this condition emits a diagnostic\" — through the channel a host would use, while production\n * emits nothing unless asked.\n *\n * The cost is stated rather than hidden: no test observes the production default by accident, so\n * `tests/diagnostics-public-entry.test.ts` pins it explicitly by clearing the sink first.\n *\n * ## Coverage is the whole guarantee\n *\n * The first sweep migrated the 92 sites under `internal/` and left `src/`'s own modules —\n * `event-bus.ts`, `batch.ts`, `compaction.ts`, `internal/workflow/step-branch.ts`. A host could\n * therefore install a sink and still have its frame corrupted by a batch run, which is the reported\n * defect with a smaller blast radius. Those are routed here too, and\n * `tests/lint/no-direct-terminal-write.test.ts` is what keeps the next hot path from\n * reintroducing one. \"Mostly interceptable\" is not interceptable.\n *\n * The remaining direct writers are allowlisted there with a reason, and every one of them is a seam\n * whose destination the CALLER already chooses (`opts.warn`, `opts.logger`, the Workflow logger).\n *\n * ## What this is NOT\n *\n * It is not a logger with levels, formatting or multiple destinations. It is the minimum that\n * resolves the reported blocker; a full logger here would be inventing a requirement nobody asked\n * for.\n */\n\n/** Receives each diagnostic message already formatted, with the trailing `\\n`. */\nexport type DiagnosticsSink = (message: string) => void;\n\n/**\n * The registry lives on `globalThis`, not in a module-level `let` (theokit#173).\n *\n * A module-level binding is a per-INSTANCE singleton, and a package manager will install two\n * physical copies of the same version whenever two dependents resolve different peer sets. Measured:\n * `@theokit/sdk@4.39.1` existed under two pnpm store hashes in the theokit workspace, so a sink\n * installed through `@theokit/agents` landed in a different registry than the emitter writes to.\n *\n * The failure mode is the quiet one — the re-export resolves, the function is callable, nothing\n * throws, and no diagnostic ever arrives. `Symbol.for` gives every copy in the process the same\n * slot; the `v1` suffix leaves room to change the shape without colliding with an older copy.\n */\nconst SINK_SLOT = Symbol.for(\"theokit.sdk.diagnostics.sink.v1\");\n\ntype SinkHolder = Record<symbol, DiagnosticsSink | undefined>;\n\nfunction currentSink(): DiagnosticsSink | undefined {\n return (globalThis as unknown as SinkHolder)[SINK_SLOT];\n}\n\n/**\n * Installs (or removes, by passing `undefined`) the diagnostics destination.\n *\n * When a sink is present it is the ONLY destination — `stderr` gets no copy. Duplicating\n * destinations would hand the problem back to the TUI that installed the sink precisely to get the\n * messages out of the terminal.\n */\nexport function setDiagnosticsSink(next: DiagnosticsSink | undefined): void {\n (globalThis as unknown as SinkHolder)[SINK_SLOT] = next;\n}\n\n/**\n * Emits a library diagnostic message.\n *\n * Replaces `process.stderr.write` on internal paths. Never throws: a faulty sink must not\n * must not take down the run it merely observes.\n */\nexport function diag(message: string): void {\n // Silent by default (#147): with no sink installed the message is dropped. A library must not\n // assume the host's stdout/stderr are free-form log sinks — in a TUI they are the render surface.\n const sink = currentSink();\n if (sink === undefined) return;\n try {\n sink(message);\n } catch {\n // Observability never breaks the run — same principle as `emitRunEvent`.\n }\n}\n\n/**\n * Emits a diagnostic that reports a USER-VISIBLE FAILURE, and is never silently dropped.\n *\n * `diag` is silent with no sink installed, and that is right for chatter: a library must not assume\n * the host's stderr is a free-form log, because in a TUI it is the render surface. A failure is a\n * different message. `theokit-sdk#189` is the record of the difference — an MCP server failed to\n * start, the only report went to `diag()`, the embedding UI never read it, and the user saw an\n * agent with missing tools and no reason given.\n *\n * The two failure modes are not symmetric, which is the whole decision: a corrupted frame is\n * visible and recoverable, while a silently dropped failure is neither. So this falls back to\n * stderr rather than to silence.\n *\n * A sink still takes precedence — the host installed it precisely to keep these off the terminal —\n * EXCEPT when the sink throws. A broken sink swallowing the one report of a failure is the same\n * defect one layer further in.\n *\n * @internal\n */\nexport function diagFailure(message: string): void {\n const sink = currentSink();\n if (sink !== undefined) {\n try {\n sink(message);\n return;\n } catch {\n // Fall through: the sink is broken, and this message is too important to drop with it.\n }\n }\n try {\n // `globalThis.process?.stderr` rather than a bare `process`: in a browser the bare form is a\n // ReferenceError that the catch below would swallow — working by accident, on an exception used\n // as ordinary control flow. Optional chaining states the intent: write to stderr where one\n // exists, stay silent where none does.\n globalThis.process?.stderr?.write(`${message}\\n`);\n } catch {\n // Nothing left to try. Observability never breaks the run.\n }\n}\n","import { diag } from \"../diagnostics.js\";\nimport { readEnv } from \"../env.js\";\n\n/**\n * Canonical secret redaction module (ADRs D68-D73).\n *\n * Single source of truth for credential pattern masking across the SDK.\n * Wired at output boundaries: `ErrorMetadata.raw` (mappers/shared.ts),\n * telemetry span attributes (telemetry/tracer.ts), transcript JSONL\n * appends (agent-session-store.ts), migration logger output\n * (memory/migrate-sqlite-to-lance.ts).\n *\n * - D68: central module, single source of truth (replaces 2 duplicates)\n * - D69: env snapshot at module init (prompt-injection defense)\n * - D70: ON by default, warn on opt-out\n * - D71: two-bucket masking — short fully masked, long preserves prefix+suffix\n * - D72: `codeFile` opt-out for legitimate prefix-shaped content\n * - D73: redact at OUTPUT boundaries, not at storage\n *\n * @internal\n */\n\n// D69: env snapshot captured at module load. Subsequent mutations of\n// process.env.THEOKIT_REDACT_SECRETS are ignored — defends against\n// prompt injection that tries to disable redaction mid-run.\nlet REDACT_ENABLED: boolean = readEnvOnce();\n\nfunction readEnvOnce(): boolean {\n // `readEnv` rather than `process.env`: this module reaches the browser through `errors.ts`, and\n // a bare `process` there is a ReferenceError at module scope — a blank page, not a warning.\n const raw = readEnv(\"THEOKIT_REDACT_SECRETS\");\n if (raw === undefined) return true; // D70: default ON\n return [\"1\", \"true\", \"yes\", \"on\"].includes(raw.toLowerCase());\n}\n\n// D70: warn once on opt-out so the user knows they're vulnerable.\nlet warnedOptOut = false;\nif (!REDACT_ENABLED && !warnedOptOut) {\n diag(\n \"[theokit-sdk] Secret redaction is DISABLED via THEOKIT_REDACT_SECRETS. \" +\n \"Credentials may leak into errors, telemetry, logs, transcripts.\\n\",\n );\n warnedOptOut = true;\n}\n\n/**\n * Built-in credential patterns. Order matters — more specific prefixes\n * must come before generic ones (e.g., `sk-ant-` before `sk-`). Quantifiers\n * are all bounded `{n,m}` or applied to char classes — linear time, no ReDoS.\n *\n * @internal\n */\nconst BUILTIN_PATTERNS: readonly RegExp[] = [\n // T5.4: 30+ vendor prefixes (was 12 pre-T5.4). Order matters — more\n // specific prefixes precede generic ones (e.g., sk-ant-admin01 before\n // sk-ant-, sk-proj- before sk-). PEM block deliberately first so its\n // multi-line span runs before any per-line patterns can fire.\n /-----BEGIN[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----[\\s\\S]+?-----END[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----/g,\n // JWT — exact 3-segment base64url. Dotted; the body floor of 4 chars per\n // segment matches the minimum legal payload while skipping `a.b.c` noise.\n /eyJ[A-Za-z0-9_-]{4,}\\.eyJ[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]{4,}/g,\n // Azure Storage SAS — match the sig= component (URL-encoded base64).\n /(?<=[?&]sig=)[A-Za-z0-9%+/]{20,}/g,\n // Anthropic\n /sk-ant-admin01-[A-Za-z0-9_-]{10,}/g, // Anthropic admin keys (must precede sk-ant-)\n /sk-ant-[A-Za-z0-9_-]{10,}/g, // Anthropic regular\n // OpenAI family + clones (sk- generic must come AFTER all sk-foo- variants)\n /sk-proj-[A-Za-z0-9_-]{10,}/g, // OpenAI project key (must precede sk- generic)\n /sk-[A-Za-z0-9_-]{10,}/g, // OpenAI / OpenRouter / DeepInfra / Together / DeepSeek\n // Provider prefixes (alphabetized for maintainability)\n /AIza[A-Za-z0-9_-]{35}/g, // Google API key\n /AKIA[A-Z0-9]{16}/g, // AWS access key\n /fw_[A-Za-z0-9]{20,}/g, // Fireworks\n /glpat-[A-Za-z0-9_-]{20}/g, // GitLab PAT\n /ghp_[A-Za-z0-9]{36}/g, // GitHub PAT classic\n /github_pat_[A-Za-z0-9_]{82}/g, // GitHub PAT fine-grained\n /gsk_[A-Za-z0-9]{20,}/g, // Groq\n /hf_[A-Za-z0-9]{20,}/g, // HuggingFace\n /\\bpa-[A-Za-z0-9_-]{20,}/g, // Voyage AI (word-boundary to skip CSS / kebab IDs)\n /pcsk_[A-Za-z0-9_-]{20,}/g, // Pinecone\n /pplx-[A-Za-z0-9_-]{20,}/g, // Perplexity\n /r8_[A-Za-z0-9_-]{20,}/g, // Replicate\n /rk_live_[A-Za-z0-9]{20,}/g, // Stripe restricted\n /sk_live_[A-Za-z0-9]{20,}/g, // Stripe secret\n /sntrys_[A-Za-z0-9]{40,}/g, // Sentry user auth\n /xai-[A-Za-z0-9_-]{20,}/g, // xAI (Grok)\n /xox[bpasr]-[A-Za-z0-9-]{10,}/g, //Slack tokens\n // Additional unique-prefix tokens with low false-positive risk\n /npm_[A-Za-z0-9]{36}/g, // npm access token\n /SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}/g, // SendGrid\n /\\bSK[A-Za-z0-9]{32}\\b/g, // Twilio API SID (word-boundary to skip CSS class noise)\n /\\bkey-[a-f0-9]{32}\\b/g, // Mailgun (hex-only narrows false positives)\n /MT[A-Za-z0-9_-]{23}\\.[A-Za-z0-9_-]{6}\\.[A-Za-z0-9_-]{27}/g, // Discord bot\n /\\b(?:sdk|mob)-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\b/g, // LaunchDarkly\n];\n\n// `Bearer <token>` matched as its own first-class pattern so PARAM_PATTERN\n// doesn't have to handle the unusual `Authorization: Bearer xxx` shape\n// (no `:` or `=` between \"Bearer\" and the value — bare whitespace).\nconst BEARER_PATTERN = /\\b(Bearer\\s+)([A-Za-z0-9_\\-.+/=]{8,})/g;\n\n// Parametric: matches `key=value` and `key: value` (with optional quote\n// between the key and the separator, to handle JSON: `\"api_key\": \"...\"`)\n// in URLs, query strings, JSON-like bodies, HTTP headers. Captures the\n// prefix so we keep it visible while masking the value.\n//\n// `authorization` deliberately excluded — BEARER_PATTERN handles the\n// common `Authorization: Bearer xxx` shape. Including it here causes\n// double-masking (\"Authorization: *** ***\") after Bearer fires.\n// T5.4: keyword set expanded from 6 → 16 to cover the OAuth / JWT / generic\n// credential vocabulary surfaced by DR6 finding #4. `authorization`,\n// `auth`, `bearer` stay excluded — BEARER_PATTERN handles the\n// `Authorization: Bearer xxx` shape and including these here would\n// re-catch the post-BUILTIN-masked form (D71 prefix-preservation\n// contract) and double-mask to `***`.\n//\n// Value class includes `.` so JWT / `.env` / dotted base64url values\n// match; the callback skips already-masked values (containing the\n// `...` D71 separator) to preserve the BUILTIN prefix-mask result.\nconst PARAM_PATTERN =\n /(\\b(?:access_token|api_key|api-key|client_secret|credential|credentials|id_token|jwt|password|private_key|refresh_token|secret|service_account|session_token|token|x-api-key)\\b[\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_\\-.+/]+)/gi;\n\nconst _extraPatterns: RegExp[] = [];\n\n/**\n * Add a user-defined redaction pattern. Additive — never removes builtins.\n * Throws if the regex lacks the `/g` flag (without `/g`, `.replace` only\n * substitutes the first match and the rest leaks).\n *\n * @internal — exposed publicly via `Security.addPattern` in `src/security.ts`.\n */\nexport function addPattern(re: RegExp): void {\n if (!re.global) {\n throw new Error(\"Security.addPattern: regex must have /g flag for replace-all semantics\");\n }\n _extraPatterns.push(re);\n}\n\n/**\n * Two-bucket masking (D71):\n * - tokens shorter than 18 chars → fully masked as `***`\n * - tokens >= 18 chars → keep first 6 + `...` + last 4\n *\n * Rationale: long tokens are unique per-account; prefix+suffix preserves\n * debuggability without revealing the secret middle.\n *\n * @internal\n */\nexport function maskToken(token: string): string {\n if (token.length < 18) return \"***\";\n return `${token.slice(0, 6)}...${token.slice(-4)}`;\n}\n\n// issue #117 — the EXACT shape of a `maskToken` output (`slice(0,6)+\"...\"+slice(-4)`\n// = 6 chars, literal `...`, 4 chars). Used to detect a value PARAM_PATTERN would\n// otherwise re-mask, WITHOUT skipping a raw secret that merely contains `...`.\nconst MASK_SHAPE = /^.{6}\\.\\.\\..{4}$/s;\n\n/**\n * Redact known credential patterns from `text`. Default behavior masks\n * builtins + extras + parametric `key=value` sinks.\n *\n * With `{ codeFile: true }` (D72), skips PARAM_PATTERN to avoid mangling\n * `.env.example`, schema JSON, or test fixtures that legitimately contain\n * prefix-like strings.\n *\n * Returns the redacted string. Coerces non-strings via JSON.stringify;\n * EC-7 fix (edge-case review): wraps in try/catch so circular references\n * never propagate — returns sentinel `\"[unredactable: circular]\"`.\n *\n * @internal\n */\n// Coerce arbitrary input to a string for redaction. Returns `null`\n// sentinel when the value is null/undefined/non-stringifiable, so the\n// caller can short-circuit with `\"\"`. EC-7 fix: circular refs go through\n// the try/catch and produce the sentinel marker, never throwing.\nfunction coerceToString(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n if (typeof value === \"object\") {\n try {\n const s = JSON.stringify(value);\n return s === undefined ? null : s;\n } catch {\n return \"[unredactable: circular]\";\n }\n }\n return String(value);\n}\n\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n const coerced = coerceToString(text);\n if (coerced === null) return \"\";\n if (!REDACT_ENABLED) return coerced;\n\n let s = coerced;\n for (const re of BUILTIN_PATTERNS) {\n s = s.replace(re, (m) => maskToken(m));\n }\n for (const re of _extraPatterns) {\n s = s.replace(re, (m) => maskToken(m));\n }\n if (!opts?.codeFile) {\n // Bearer first (preserves \"Bearer \" prefix, masks the token after).\n // Must run before PARAM_PATTERN so the bare-whitespace shape doesn't\n // get mis-handled as a value.\n s = s.replace(BEARER_PATTERN, (_, prefix: string) => `${prefix}***`);\n // T5.4: skip if value already contains the D71 bucket-mask separator\n // (`...`) — BUILTIN ran first and produced a prefix-preserved mask;\n // re-masking would lose the prefix and degrade debuggability.\n s = s.replace(PARAM_PATTERN, (whole, prefix: string, value: string) => {\n // issue #117 — skip ONLY when the value is already a mask that a BUILTIN\n // pattern produced (maskToken's exact `6chars...4chars` shape), so we don't\n // re-mask and lose the prefix. The old `value.includes(\"...\")` was too broad:\n // a REAL secret that happens to contain `...` (e.g. `L_-cxw-.2UI_..._`) was\n // skipped and LEAKED. The mask shape is exact (maskToken: slice(0,6)+\"...\"+\n // slice(-4)), so a raw secret with `...` elsewhere is now masked.\n if (MASK_SHAPE.test(value)) return whole;\n return `${prefix}***`;\n });\n }\n return s;\n}\n\n/**\n * Test-only helper exported for `_test-reset.ts`. NOT included in the\n * `index.ts` barrel — vitest setup imports the dedicated module via\n * explicit path to discourage production callers.\n *\n * @internal\n */\nexport function _resetForTests(opts: { enabled?: boolean; clearExtras?: boolean }): void {\n if (opts.enabled !== undefined) REDACT_ENABLED = opts.enabled;\n if (opts.clearExtras === true) _extraPatterns.length = 0;\n}\n\n/**\n * T5.4 — Test-only count of BUILTIN_PATTERNS. Exposed so the count-floor\n * assertion can run without re-deriving the array shape in test land.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__BUILTIN_PATTERN_COUNT(): number {\n return BUILTIN_PATTERNS.length;\n}\n"]}
@@ -0,0 +1,155 @@
1
+ 'use strict';
2
+
3
+ var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
4
+ var crypto = require('crypto');
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ var zod = require('zod');
8
+
9
+ function credentialHome(config, env = {}) {
10
+ const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
11
+ return override !== void 0 && override.length > 0 ? override : path.join(config.home, config.dirName);
12
+ }
13
+ function authFilePath(config, env = {}) {
14
+ return path.join(credentialHome(config, env), config.fileName);
15
+ }
16
+ var CredentialError = class extends chunkLPVIRJVF_cjs.AuthenticationError {
17
+ // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`
18
+ // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the
19
+ // suite was green with the broken assignment because the transpiler strips the type.
20
+ name = "CredentialError";
21
+ };
22
+ var apiFileSchema = zod.z.object({
23
+ type: zod.z.literal("api").optional(),
24
+ provider: zod.z.string().min(1).optional(),
25
+ api_key: zod.z.string()
26
+ }).strict();
27
+ var oauthFileSchema = zod.z.object({
28
+ type: zod.z.literal("oauth"),
29
+ provider: zod.z.string().min(1),
30
+ access: zod.z.string().min(1),
31
+ refresh: zod.z.string().min(1),
32
+ expires: zod.z.number(),
33
+ account_id: zod.z.string().optional()
34
+ }).strict();
35
+ var fileSchema = zod.z.union([oauthFileSchema, apiFileSchema]);
36
+ function assertSecureModes(dirPath, path) {
37
+ if (process.platform === "win32") return;
38
+ const dirMode = fs.statSync(dirPath).mode & 511;
39
+ if ((dirMode & 18) !== 0) {
40
+ throw new CredentialError(
41
+ `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file inside it can be replaced. Fix it with: chmod 700 ${dirPath}`
42
+ );
43
+ }
44
+ const mode = fs.statSync(path).mode & 511;
45
+ if ((mode & 63) !== 0) {
46
+ throw new CredentialError(
47
+ `${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
48
+ );
49
+ }
50
+ }
51
+ function describeUnionError(parsed, err, path) {
52
+ const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
53
+ const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
54
+ let issue;
55
+ if (!specific.success) {
56
+ issue = specific.error.issues[0];
57
+ } else if (err instanceof zod.z.ZodError) {
58
+ issue = err.issues[0];
59
+ }
60
+ return new CredentialError(
61
+ `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
62
+ );
63
+ }
64
+ function parseStoredFile(raw, path) {
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(raw);
68
+ } catch {
69
+ throw new CredentialError(
70
+ `${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
71
+ );
72
+ }
73
+ try {
74
+ return fileSchema.parse(parsed);
75
+ } catch (err) {
76
+ throw describeUnionError(parsed, err, path);
77
+ }
78
+ }
79
+ function readAuthFile(config, env = {}) {
80
+ const path = authFilePath(config, env);
81
+ let raw;
82
+ try {
83
+ raw = fs.readFileSync(path, "utf8");
84
+ } catch (err) {
85
+ if (err.code === "ENOENT") return void 0;
86
+ throw new CredentialError(`cannot read ${path}: ${err.message}`);
87
+ }
88
+ assertSecureModes(credentialHome(config, env), path);
89
+ return parseStoredFile(raw, path);
90
+ }
91
+ function readStoredOAuth(config, env = {}) {
92
+ const stored = readAuthFile(config, env);
93
+ return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
94
+ }
95
+ function isOAuthWrite(c) {
96
+ return "type" in c && c.type === "oauth";
97
+ }
98
+ function buildStorePayload(cred) {
99
+ if (isOAuthWrite(cred)) {
100
+ if (cred.access.length === 0 || cred.refresh.length === 0) {
101
+ throw new CredentialError(
102
+ "refusing to write an oauth credential with an empty access/refresh token"
103
+ );
104
+ }
105
+ return {
106
+ type: "oauth",
107
+ provider: cred.provider,
108
+ access: cred.access,
109
+ refresh: cred.refresh,
110
+ expires: cred.expires,
111
+ ...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
112
+ };
113
+ }
114
+ if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
115
+ throw new CredentialError("refusing to write an empty API key");
116
+ }
117
+ return { provider: cred.provider, api_key: cred.apiKey };
118
+ }
119
+ function writeCredential(cred, config, env = {}) {
120
+ const payload = buildStorePayload(cred);
121
+ const dir = credentialHome(config, env);
122
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
123
+ fs.chmodSync(dir, 448);
124
+ const path = authFilePath(config, env);
125
+ const tmp = `${path}.tmp-${crypto.randomBytes(8).toString("hex")}`;
126
+ try {
127
+ const fd = fs.openSync(tmp, "wx", 384);
128
+ try {
129
+ fs.writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
130
+ `);
131
+ fs.fsyncSync(fd);
132
+ } finally {
133
+ fs.closeSync(fd);
134
+ }
135
+ fs.chmodSync(tmp, 384);
136
+ fs.renameSync(tmp, path);
137
+ } catch (err) {
138
+ try {
139
+ fs.unlinkSync(tmp);
140
+ } catch {
141
+ }
142
+ throw new CredentialError(`cannot write ${path}: ${err.message}`);
143
+ }
144
+ return path;
145
+ }
146
+
147
+ exports.CredentialError = CredentialError;
148
+ exports.assertSecureModes = assertSecureModes;
149
+ exports.authFilePath = authFilePath;
150
+ exports.credentialHome = credentialHome;
151
+ exports.readAuthFile = readAuthFile;
152
+ exports.readStoredOAuth = readStoredOAuth;
153
+ exports.writeCredential = writeCredential;
154
+ //# sourceMappingURL=chunk-5YKNEMXR.cjs.map
155
+ //# sourceMappingURL=chunk-5YKNEMXR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/auth/credential-store.ts"],"names":["join","AuthenticationError","z","statSync","readFileSync","mkdirSync","chmodSync","randomBytes","openSync","writeFileSync","fsyncSync","closeSync","renameSync","unlinkSync"],"mappings":";;;;;;;;AAwCO,SAAS,cAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,MAAM,QAAA,GAAW,OAAO,UAAA,KAAe,MAAA,GAAY,IAAI,MAAA,CAAO,UAAU,CAAA,EAAG,IAAA,EAAK,GAAI,MAAA;AACpF,EAAA,OAAO,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,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AAC,YAAA,CAAU,KAAK,EAAE,SAAA,EAAW,IAAA,EAAM,IAAA,EAAM,KAAO,CAAA;AAC/C,EAAAC,YAAA,CAAU,KAAK,GAAK,CAAA;AAEpB,EAAA,MAAM,IAAA,GAAO,YAAA,CAAa,MAAA,EAAQ,GAAG,CAAA;AAIrC,EAAA,MAAM,GAAA,GAAM,GAAG,IAAI,CAAA,KAAA,EAAQC,mBAAY,CAAC,CAAA,CAAE,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,EAAA,GAAKC,WAAA,CAAS,GAAA,EAAK,IAAA,EAAM,GAAK,CAAA;AACpC,IAAA,IAAI;AACF,MAAAC,gBAAA,CAAc,IAAI,CAAA,EAAG,IAAA,CAAK,UAAU,OAAA,EAAS,IAAA,EAAM,CAAC,CAAC;AAAA,CAAI,CAAA;AACzD,MAAAC,YAAA,CAAU,EAAE,CAAA;AAAA,IACd,CAAA,SAAE;AACA,MAAAC,YAAA,CAAU,EAAE,CAAA;AAAA,IACd;AACA,IAAAL,YAAA,CAAU,KAAK,GAAK,CAAA;AACpB,IAAAM,aAAA,CAAW,KAAK,IAAI,CAAA;AAAA,EACtB,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI;AACF,MAAAC,aAAA,CAAW,GAAG,CAAA;AAAA,IAChB,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,eAAA,CAAgB,CAAA,aAAA,EAAgB,IAAI,CAAA,EAAA,EAAM,GAAA,CAAc,OAAO,CAAA,CAAE,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-5YKNEMXR.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { AuthenticationError } from \"../../errors.js\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * @internal\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/**\n * A credential problem the caller can act on. Never carries the key value.\n *\n * M78 — this used to extend bare `Error`, which quietly disabled classification for the entire auth\n * path: `isTransientError` is `err instanceof TheokitAgentError && err.isRetryable === true`\n * (`errors.ts:443`), so a credential failure could never be judged transient OR permanent. The\n * predicate was not \"forgotten\" downstream — it was unusable there by construction.\n *\n * Extending `AuthenticationError` is ADDITIVE: the class still exists, still reports\n * `name: \"CredentialError\"`, and every existing `instanceof CredentialError` stays true. It only\n * gains ancestors. `AuthenticationError` pins `isRetryable: false`, so gaining the ability to be\n * classified does NOT turn a revoked credential into a retry loop.\n *\n * The single reference does the same thing with one root type: Codex routes every domain failure\n * through `CodexErr` with `is_retryable()` as a method (`protocol/src/error.rs:176`), rather than\n * parallel classes extending the language's `Error`.\n */\nexport class CredentialError extends AuthenticationError {\n // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`\n // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the\n // suite was green with the broken assignment because the transpiler strips the type.\n override readonly name: string = \"CredentialError\";\n}\n\n/**\n * The on-disk store — a discriminated union on `type`. A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nexport function assertSecureModes(dirPath: string, path: string): void {\n // Windows has no POSIX mode bits. `statSync().mode` there is SYNTHETIC — 0666 for any writable\n // entry, whatever the ACLs actually say — so `mode & 0o022` was non-zero for every valid store and\n // this gate refused all of them, which made the credential path unreadable on that platform\n // rather than protected. A check that cannot observe the real permission system must not report a\n // verdict about it; ACL enforcement is a separate mechanism and not one this function can fake.\n if (process.platform === \"win32\") return;\n\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunk2YGIBOUH_cjs = require('./chunk-2YGIBOUH.cjs');
4
- var chunkSXSPMRSV_cjs = require('./chunk-SXSPMRSV.cjs');
3
+ var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
4
+ var chunkBM6N4KHO_cjs = require('./chunk-BM6N4KHO.cjs');
5
5
  var async_hooks = require('async_hooks');
6
6
  var fs = require('fs');
7
7
  var promises = require('fs/promises');
@@ -17,7 +17,7 @@ var warned = /* @__PURE__ */ new Set();
17
17
  function warnOnce(key, message) {
18
18
  if (warned.has(key)) return;
19
19
  warned.add(key);
20
- chunkSXSPMRSV_cjs.diag(`${message}
20
+ chunkBM6N4KHO_cjs.diag(`${message}
21
21
  `);
22
22
  }
23
23
  async function loadHookConfig(cwd) {
@@ -35,7 +35,7 @@ async function loadHookConfig(cwd) {
35
35
  try {
36
36
  raw = await promises.readFile(jsonPath, "utf8");
37
37
  } catch (cause) {
38
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {
38
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {
39
39
  code: "hooks_read_error",
40
40
  cause
41
41
  });
@@ -44,7 +44,7 @@ async function loadHookConfig(cwd) {
44
44
  try {
45
45
  parsed = JSON.parse(raw);
46
46
  } catch (cause) {
47
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {
47
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {
48
48
  code: "hooks_json_invalid",
49
49
  cause
50
50
  });
@@ -53,7 +53,7 @@ async function loadHookConfig(cwd) {
53
53
  }
54
54
  function asRecord(value, path, where) {
55
55
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
56
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {
56
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {
57
57
  code: "hooks_json_invalid"
58
58
  });
59
59
  }
@@ -61,7 +61,7 @@ function asRecord(value, path, where) {
61
61
  }
62
62
  function asArray(value, path, where) {
63
63
  if (!Array.isArray(value)) {
64
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {
64
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {
65
65
  code: "hooks_json_invalid"
66
66
  });
67
67
  }
@@ -99,13 +99,13 @@ function flattenEventGroups(groups, path, ccEvent) {
99
99
  function parseClaudeCodeCommand(raw, matcher, path, ccEvent) {
100
100
  const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);
101
101
  if (cmd.type !== "command") {
102
- throw new chunk2YGIBOUH_cjs.ConfigurationError(
102
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(
103
103
  `hooks: only { "type": "command" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,
104
104
  { code: "hooks_unsupported_type" }
105
105
  );
106
106
  }
107
107
  if (typeof cmd.command !== "string" || cmd.command.length === 0) {
108
- throw new chunk2YGIBOUH_cjs.ConfigurationError(`hooks: "command" must be a non-empty string in ${path}`, {
108
+ throw new chunkLPVIRJVF_cjs.ConfigurationError(`hooks: "command" must be a non-empty string in ${path}`, {
109
109
  code: "hooks_invalid_command"
110
110
  });
111
111
  }
@@ -137,5 +137,5 @@ exports.loadHookConfig = loadHookConfig;
137
137
  exports.warnOnce = warnOnce;
138
138
  exports.warnPersonalitySwitchInsideFork = warnPersonalitySwitchInsideFork;
139
139
  exports.withPersonalityContext = withPersonalityContext;
140
- //# sourceMappingURL=chunk-3YYDHUNH.cjs.map
141
- //# sourceMappingURL=chunk-3YYDHUNH.cjs.map
140
+ //# sourceMappingURL=chunk-665SFFFR.cjs.map
141
+ //# sourceMappingURL=chunk-665SFFFR.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","join","existsSync","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAYA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAA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M,IAAIA,oCAAA;AAAA,MACR,uDAAuD,IAAA,CAAK,SAAA,CAAU,IAAI,IAAI,CAAC,QAAQ,IAAI,CAAA,CAAA;AAAA,MAC3F,EAAE,MAAM,wBAAA;AAAyB,KACnC;AAAA,EACF;AACA,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,YAAY,GAAA,CAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,+CAAA,EAAkD,IAAI,CAAA,CAAA,EAAI;AAAA,MACrF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,MAAM,EAAA,GAAkB,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ;AAC/C,EAAA,IAAI,OAAA,KAAY,MAAA,EAAW,EAAA,CAAG,OAAA,GAAU,OAAA;AACxC,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,IAAY,GAAA,CAAI,UAAU,CAAA,EAAG;AACtD,IAAA,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAU,GAAI,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;ACrKA,IAAM,OAAA,GAAU,IAAIC,6BAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-3YYDHUNH.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","join","existsSync","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAYA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAAuB;AAC3D,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAAA,sBAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAcA,eAAsB,eAAe,GAAA,EAAkC;AACrE,EAAA,MAAM,QAAA,GAAWC,SAAA,CAAK,GAAA,EAAK,UAAA,EAAY,YAAY,CAAA;AAEnD,EAAA,IAAI,CAACC,aAAA,CAAW,QAAQ,CAAA,EAAG;AACzB,IAAA,IAAIA,cAAWD,SAAA,CAAK,GAAA,EAAK,UAAA,EAAY,OAAO,CAAC,CAAA,EAAG;AAC9C,MAAA,QAAA;AAAA,QACE,sBAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,EAAC;AAAA,EACV;AAEA,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAME,iBAAA,CAAS,QAAA,EAAU,MAAM,CAAA;AAAA,EACvC,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAIC,oCAAA,CAAmB,CAAA,6BA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,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;ACrKA,IAAM,OAAA,GAAU,IAAIC,6BAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-665SFFFR.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { diag } from './chunk-4X3SBHPK.js';
1
+ import { diag } from './chunk-5F5NWKPN.js';
2
2
  import { randomBytes } from 'crypto';
3
3
  import { open, rename, unlink, mkdir, statfs } from 'fs/promises';
4
4
  import { dirname } from 'path';
@@ -72,5 +72,5 @@ async function atomicWriteText(filePath, content) {
72
72
  }
73
73
 
74
74
  export { atomicWriteJson, atomicWriteTempTarget, atomicWriteText, replaceFileAtomic };
75
- //# sourceMappingURL=chunk-CHVSMEKM.js.map
76
- //# sourceMappingURL=chunk-CHVSMEKM.js.map
75
+ //# sourceMappingURL=chunk-6AZDM6LK.js.map
76
+ //# sourceMappingURL=chunk-6AZDM6LK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":[],"mappings":";;;;;AAUA,IAAM,gBAAA,uBAAoD,GAAA,CAAI;AAA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,IAAA,MAAM,IAAI,UAAU,6CAA6C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,OAAA,GAAU,eAAA,GAAkB,CAAA,EAAG,IAAI;AAAA,CAAA,GAAO,IAAA;AAChD,EAAA,MAAM,MAAM,OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AACpD;AASA,eAAsB,eAAA,CAAgB,UAAkB,OAAA,EAAgC;AACtF,EAAA,MAAM,MAAM,OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-6AZDM6LK.js","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { diag } from \"../diagnostics.js\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n diag(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * M107 — temp-file creation control, shared by `replaceFileAtomic`,\n * `atomicWriteJson` e `atomicWriteText`.\n *\n * Both fields are OPTIONAL and the default is byte-identical to the behavior\n * before M107. See `replaceFileAtomic` for why the mode reassertion\n * is conditional.\n *\n */\nexport interface AtomicWriteFileOptions {\n /**\n * Permission bits of the created file. Default: `0o600`, the previous fixed\n * literal — filtered by the `umask`, as it always was. When provided, the mode is\n * reasserted on the descriptor, so the `umask` cannot silently\n * clearing bits the caller asked for.\n */\n mode?: number;\n /**\n * Create the temp file with `wx` (exclusive creation) instead of `w`. Default:\n * `false` — the previous flag. With `true`, a pre-existing temp file becomes\n * `EEXIST` instead of being truncated.\n */\n exclusive?: boolean;\n}\n\n/** The one place the temp-path format is written. `atomicWriteTempTarget` reverses it. */\nfunction atomicWriteTempPath(filePath: string, pid: number, suffix: string): string {\n return `${filePath}.${String(pid)}.${suffix}.tmp`;\n}\n\n/** Reverses {@link atomicWriteTempPath}: `<file>.<pid>.<hex>.tmp` → `<file>`. */\nconst TEMP_PATTERN = /^(.+)\\.\\d+\\.[0-9a-f]{16}\\.tmp$/;\n\n/**\n * U-9 — the file a leftover temp was replacing, or `undefined` if this is not one of ours.\n *\n * A crash between the open and the rename leaves `<file>.<pid>.<hex>.tmp` behind, and nothing here\n * collects it: this module creates temps and has no opinion about sweeping them. A consumer that\n * wants to has to know the format — which lived only in the implementation, so one copied it out of\n * a compiled chunk as a regex. That copy would have gone on reporting \"nothing to collect\" the day\n * the format changed, which is the quietest possible way for a cleanup to stop working.\n *\n * Deliberately strict: the pid must be digits and the suffix exactly 16 hex characters. Matching any\n * `.tmp` would claim editors' swap files and other tools' scratch, on a path whose purpose is\n * deleting them.\n */\nexport function atomicWriteTempTarget(name: string): string | undefined {\n return TEMP_PATTERN.exec(name)?.[1];\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `reference/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * ## M107 — `options` is optional, and the default is byte-identical\n *\n * The third parameter is additive: every earlier caller still compiles and\n * writing exactly the same bytes, with the same mode, to the same path.\n *\n * The mode reassertion (`handle.chmod`) is **conditional on `mode !== undefined`**,\n * and that is not cosmetic. `open`'s mode argument is filtered by the `umask`,\n * which only CLEARS bits — measured in this codebase before the change:\n *\n * ```\n * umask 0o002 -> 0o600 umask 0o022 -> 0o600 umask 0o200 -> 0o400\n * ```\n *\n * An unconditional `chmod` would take the third case from `0o400` to `0o600` — a\n * an on-disk change for every caller that asked for nothing, including external\n * consumers. When the caller DOES ask for a mode, however, letting the `umask` decide\n * silently is the defect this parameter exists to close; hence the reassertion.\n *\n * It goes on the DESCRIPTOR, before the `rename`, never after: chmod-ing the final\n * final one would leave a window where it carries the `umask`'s mode — a known anti-pattern.\n * The chosen shape passes the mode as an `open` argument.\n *\n */\nexport async function replaceFileAtomic(\n filePath: string,\n content: string,\n options?: AtomicWriteFileOptions,\n): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = atomicWriteTempPath(filePath, process.pid, suffix);\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, options?.exclusive === true ? \"wx\" : \"w\", options?.mode ?? 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n // Conditional by measurement, not by taste — see this function's docblock.\n if (options?.mode !== undefined) await handle.chmod(options.mode);\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n */\nexport interface AtomicWriteJsonOptions extends AtomicWriteFileOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content, options);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunk2YGIBOUH_cjs = require('./chunk-2YGIBOUH.cjs');
4
- var chunkSXSPMRSV_cjs = require('./chunk-SXSPMRSV.cjs');
3
+ var chunkLPVIRJVF_cjs = require('./chunk-LPVIRJVF.cjs');
4
+ var chunkBM6N4KHO_cjs = require('./chunk-BM6N4KHO.cjs');
5
5
 
6
6
  // src/internal/runtime/compression/compression-helpers.ts
7
7
  function selectCompressionWindow(messages, preserveLast = 6) {
@@ -40,7 +40,7 @@ Anything that MUST NOT be forgotten (preserve verbatim: error messages, exact va
40
40
  File paths touched or referenced (verbatim).`;
41
41
  function assertMarker(marker) {
42
42
  if (marker === "") {
43
- throw new chunk2YGIBOUH_cjs.TheokitAgentError("compaction marker must be non-empty", {
43
+ throw new chunkLPVIRJVF_cjs.TheokitAgentError("compaction marker must be non-empty", {
44
44
  code: "invalid_argument"
45
45
  });
46
46
  }
@@ -73,8 +73,8 @@ async function runSummarize(summarize, head, template, failSafe) {
73
73
  return await summarize(head, template);
74
74
  } catch (err) {
75
75
  if (!failSafe) throw err;
76
- chunkSXSPMRSV_cjs.diag(
77
- `[compaction] summarizer failed \u2014 proceeding uncompacted: ${chunkSXSPMRSV_cjs.redactSecrets(err instanceof Error ? err.message : String(err))}
76
+ chunkBM6N4KHO_cjs.diag(
77
+ `[compaction] summarizer failed \u2014 proceeding uncompacted: ${chunkBM6N4KHO_cjs.redactSecrets(err instanceof Error ? err.message : String(err))}
78
78
  `
79
79
  );
80
80
  return FAILSAFE_ABORT;
@@ -117,9 +117,9 @@ function filterFromLatestCheckpoint(messages, options = {}) {
117
117
  return [...messages];
118
118
  }
119
119
  function isContextOverflowError(err) {
120
- return err instanceof chunk2YGIBOUH_cjs.TheokitAgentError && (err.code === "context_too_long" || err.metadata?.code === "context_too_long");
120
+ return err instanceof chunkLPVIRJVF_cjs.TheokitAgentError && (err.code === "context_too_long" || err.metadata?.code === "context_too_long");
121
121
  }
122
- var ContextWindowMarginError = class extends chunk2YGIBOUH_cjs.TheokitAgentError {
122
+ var ContextWindowMarginError = class extends chunkLPVIRJVF_cjs.TheokitAgentError {
123
123
  constructor(margin) {
124
124
  super(
125
125
  `context-window margin must be in (0, 1], got ${String(margin)}. A margin above 1 grows the assumed window and delays compaction past the real limit.`,
@@ -167,5 +167,5 @@ exports.filterFromLatestCheckpoint = filterFromLatestCheckpoint;
167
167
  exports.isContextOverflowError = isContextOverflowError;
168
168
  exports.resolveEffectiveContextWindow = resolveEffectiveContextWindow;
169
169
  exports.shouldCompact = shouldCompact;
170
- //# sourceMappingURL=chunk-AMYY3JHQ.cjs.map
171
- //# sourceMappingURL=chunk-AMYY3JHQ.cjs.map
170
+ //# sourceMappingURL=chunk-ADLLFY3H.cjs.map
171
+ //# sourceMappingURL=chunk-ADLLFY3H.cjs.map