@theokit/sdk 4.40.0 → 4.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (387) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/dist/agent-35MGOZVH.js +46 -0
  4. package/dist/{agent-MSR3DHO4.js.map → agent-35MGOZVH.js.map} +1 -1
  5. package/dist/agent-6C2ODKFU.cjs +55 -0
  6. package/dist/{agent-OOXJJD6A.cjs.map → agent-6C2ODKFU.cjs.map} +1 -1
  7. package/dist/{agent-BzZwYFiw.d.ts → agent-BiCINq25.d.ts} +2 -2
  8. package/dist/{agent-DxEL4fHh.d.cts → agent-Zta1kvGH.d.cts} +2 -2
  9. package/dist/agent-session-store-EPUERCUU.cjs +23 -0
  10. package/dist/{agent-session-store-RHTLZ5OX.cjs.map → agent-session-store-EPUERCUU.cjs.map} +1 -1
  11. package/dist/agent-session-store-TXP5ZVOD.js +6 -0
  12. package/dist/{agent-session-store-EGTTYSKS.js.map → agent-session-store-TXP5ZVOD.js.map} +1 -1
  13. package/dist/auth/index.cjs +19 -15
  14. package/dist/auth/index.d.cts +1 -1
  15. package/dist/auth/index.d.ts +1 -1
  16. package/dist/auth/index.js +4 -4
  17. package/dist/{batch-WX2HLXX2.js → batch-OUF4N2TM.js} +9 -9
  18. package/dist/{batch-WX2HLXX2.js.map → batch-OUF4N2TM.js.map} +1 -1
  19. package/dist/{batch-FO2KZN7W.cjs → batch-URTEXK77.cjs} +26 -26
  20. package/dist/{batch-FO2KZN7W.cjs.map → batch-URTEXK77.cjs.map} +1 -1
  21. package/dist/{chunk-PDOLUFGY.cjs → chunk-27DYRARU.cjs} +4 -4
  22. package/dist/{chunk-PDOLUFGY.cjs.map → chunk-27DYRARU.cjs.map} +1 -1
  23. package/dist/{chunk-LYD3ALDT.js → chunk-2S6B5B2A.js} +5 -5
  24. package/dist/{chunk-LYD3ALDT.js.map → chunk-2S6B5B2A.js.map} +1 -1
  25. package/dist/{chunk-VTDQRUAJ.js → chunk-2WB6EIYW.js} +4 -4
  26. package/dist/{chunk-VTDQRUAJ.js.map → chunk-2WB6EIYW.js.map} +1 -1
  27. package/dist/{chunk-3CAQCFVZ.js → chunk-35NFZ7QB.js} +3 -3
  28. package/dist/{chunk-3CAQCFVZ.js.map → chunk-35NFZ7QB.js.map} +1 -1
  29. package/dist/{chunk-HCRCNI7A.js → chunk-3KY7MHR4.js} +3 -3
  30. package/dist/{chunk-HCRCNI7A.js.map → chunk-3KY7MHR4.js.map} +1 -1
  31. package/dist/{chunk-BURYFNOM.cjs → chunk-4JBHSLQO.cjs} +2 -2
  32. package/dist/chunk-4JBHSLQO.cjs.map +1 -0
  33. package/dist/{chunk-V7CA3CX5.cjs → chunk-4JRRFRV4.cjs} +5 -4
  34. package/dist/chunk-4JRRFRV4.cjs.map +1 -0
  35. package/dist/{chunk-5KOW3GLE.js → chunk-4QEC4CCS.js} +2 -2
  36. package/dist/chunk-4QEC4CCS.js.map +1 -0
  37. package/dist/{chunk-ALDFVGQQ.cjs → chunk-57KX5WTP.cjs} +9 -9
  38. package/dist/{chunk-ALDFVGQQ.cjs.map → chunk-57KX5WTP.cjs.map} +1 -1
  39. package/dist/{chunk-CJHBSSAF.cjs → chunk-64TJCXY5.cjs} +15 -15
  40. package/dist/{chunk-CJHBSSAF.cjs.map → chunk-64TJCXY5.cjs.map} +1 -1
  41. package/dist/{chunk-IEKSEAIV.js → chunk-6FSQ3CHQ.js} +3 -3
  42. package/dist/{chunk-IEKSEAIV.js.map → chunk-6FSQ3CHQ.js.map} +1 -1
  43. package/dist/{chunk-ZVQJHY4Y.cjs → chunk-6W4U2G3J.cjs} +5 -5
  44. package/dist/{chunk-ZVQJHY4Y.cjs.map → chunk-6W4U2G3J.cjs.map} +1 -1
  45. package/dist/{chunk-FMDZZRYE.cjs → chunk-6X2HUT4A.cjs} +8 -8
  46. package/dist/{chunk-FMDZZRYE.cjs.map → chunk-6X2HUT4A.cjs.map} +1 -1
  47. package/dist/{chunk-X2LDDKFM.cjs → chunk-7PESI6YD.cjs} +10 -10
  48. package/dist/{chunk-X2LDDKFM.cjs.map → chunk-7PESI6YD.cjs.map} +1 -1
  49. package/dist/{chunk-EYUZZXHZ.js → chunk-AF4BBKIF.js} +4 -4
  50. package/dist/chunk-AF4BBKIF.js.map +1 -0
  51. package/dist/{chunk-7GFX45DD.js → chunk-AM2CNBKE.js} +2 -2
  52. package/dist/chunk-AM2CNBKE.js.map +1 -0
  53. package/dist/{chunk-XKGOIGTJ.js → chunk-AZ6FKDQR.js} +3 -3
  54. package/dist/{chunk-XKGOIGTJ.js.map → chunk-AZ6FKDQR.js.map} +1 -1
  55. package/dist/{chunk-WPZTYOUX.cjs → chunk-BBZYXVLZ.cjs} +2 -2
  56. package/dist/chunk-BBZYXVLZ.cjs.map +1 -0
  57. package/dist/{chunk-2UBBO2MD.js → chunk-BHWHE453.js} +5 -5
  58. package/dist/{chunk-2UBBO2MD.js.map → chunk-BHWHE453.js.map} +1 -1
  59. package/dist/{chunk-LY4KEOOY.cjs → chunk-BRHRQOJA.cjs} +4 -4
  60. package/dist/{chunk-LY4KEOOY.cjs.map → chunk-BRHRQOJA.cjs.map} +1 -1
  61. package/dist/{chunk-4H2QARXM.cjs → chunk-BV42CCRP.cjs} +7 -7
  62. package/dist/{chunk-4H2QARXM.cjs.map → chunk-BV42CCRP.cjs.map} +1 -1
  63. package/dist/{chunk-ZRQZOJ3N.js → chunk-DCKIS53K.js} +52 -51
  64. package/dist/chunk-DCKIS53K.js.map +1 -0
  65. package/dist/{chunk-SKWVAQAY.js → chunk-DEZ75ET5.js} +3 -3
  66. package/dist/{chunk-SKWVAQAY.js.map → chunk-DEZ75ET5.js.map} +1 -1
  67. package/dist/{chunk-WJOLIPEM.js → chunk-EON4YTR6.js} +8 -8
  68. package/dist/{chunk-WJOLIPEM.js.map → chunk-EON4YTR6.js.map} +1 -1
  69. package/dist/{chunk-MI3OKONE.js → chunk-F4RUADRC.js} +3 -3
  70. package/dist/{chunk-MI3OKONE.js.map → chunk-F4RUADRC.js.map} +1 -1
  71. package/dist/{chunk-BVGJXMSB.cjs → chunk-F5DSDDBY.cjs} +312 -311
  72. package/dist/chunk-F5DSDDBY.cjs.map +1 -0
  73. package/dist/{chunk-SEWAPWAF.cjs → chunk-FMIKUGF2.cjs} +124 -124
  74. package/dist/chunk-FMIKUGF2.cjs.map +1 -0
  75. package/dist/{chunk-XZ7PO2FM.js → chunk-FRQ6F44U.js} +4 -4
  76. package/dist/{chunk-XZ7PO2FM.js.map → chunk-FRQ6F44U.js.map} +1 -1
  77. package/dist/{chunk-3LK3ZDL5.cjs → chunk-FZ4YMZA3.cjs} +5 -5
  78. package/dist/{chunk-3LK3ZDL5.cjs.map → chunk-FZ4YMZA3.cjs.map} +1 -1
  79. package/dist/{chunk-MM2JKFQV.cjs → chunk-GC44RATP.cjs} +10 -10
  80. package/dist/{chunk-MM2JKFQV.cjs.map → chunk-GC44RATP.cjs.map} +1 -1
  81. package/dist/{chunk-LNTQRD23.cjs → chunk-GH52NOCL.cjs} +26 -26
  82. package/dist/chunk-GH52NOCL.cjs.map +1 -0
  83. package/dist/{chunk-T6KFGMNY.cjs → chunk-GLEKLAUW.cjs} +12 -12
  84. package/dist/chunk-GLEKLAUW.cjs.map +1 -0
  85. package/dist/{chunk-UIPTINIF.js → chunk-GNMPCZNN.js} +6 -6
  86. package/dist/chunk-GNMPCZNN.js.map +1 -0
  87. package/dist/{chunk-K6TWHNT4.cjs → chunk-HECR7KF5.cjs} +11 -11
  88. package/dist/{chunk-K6TWHNT4.cjs.map → chunk-HECR7KF5.cjs.map} +1 -1
  89. package/dist/{chunk-NHXPQN44.js → chunk-HK4HRLWE.js} +3 -3
  90. package/dist/{chunk-NHXPQN44.js.map → chunk-HK4HRLWE.js.map} +1 -1
  91. package/dist/{chunk-LWVKI75U.js → chunk-HKSSM5RK.js} +3 -3
  92. package/dist/{chunk-LWVKI75U.js.map → chunk-HKSSM5RK.js.map} +1 -1
  93. package/dist/{chunk-ELYGL52R.cjs → chunk-HLNLYLNN.cjs} +4 -4
  94. package/dist/{chunk-ELYGL52R.cjs.map → chunk-HLNLYLNN.cjs.map} +1 -1
  95. package/dist/{chunk-ONVIALVV.js → chunk-IMX5YODO.js} +15 -15
  96. package/dist/chunk-IMX5YODO.js.map +1 -0
  97. package/dist/{chunk-C64E2EJS.js → chunk-J5RW43IR.js} +4 -4
  98. package/dist/{chunk-C64E2EJS.js.map → chunk-J5RW43IR.js.map} +1 -1
  99. package/dist/{chunk-4E3HLSYE.cjs → chunk-JA4FEA5Z.cjs} +4 -4
  100. package/dist/{chunk-4E3HLSYE.cjs.map → chunk-JA4FEA5Z.cjs.map} +1 -1
  101. package/dist/{chunk-EJNFZET4.cjs → chunk-JO76RWCA.cjs} +11 -11
  102. package/dist/{chunk-EJNFZET4.cjs.map → chunk-JO76RWCA.cjs.map} +1 -1
  103. package/dist/{chunk-QMIG7TKG.cjs → chunk-KCQUYQ3V.cjs} +17 -17
  104. package/dist/chunk-KCQUYQ3V.cjs.map +1 -0
  105. package/dist/{chunk-AKMPQJPX.js → chunk-L4JFQCG4.js} +5 -5
  106. package/dist/chunk-L4JFQCG4.js.map +1 -0
  107. package/dist/{chunk-HJMFPIRM.js → chunk-LLE7HPRI.js} +5 -5
  108. package/dist/{chunk-HJMFPIRM.js.map → chunk-LLE7HPRI.js.map} +1 -1
  109. package/dist/{chunk-4H2DCO6P.js → chunk-LXKNENHK.js} +3 -3
  110. package/dist/{chunk-4H2DCO6P.js.map → chunk-LXKNENHK.js.map} +1 -1
  111. package/dist/{chunk-PY7G7YWK.cjs → chunk-MMZX557L.cjs} +5 -5
  112. package/dist/{chunk-PY7G7YWK.cjs.map → chunk-MMZX557L.cjs.map} +1 -1
  113. package/dist/{chunk-VQ33XLC6.js → chunk-MRKSSN36.js} +3 -3
  114. package/dist/{chunk-VQ33XLC6.js.map → chunk-MRKSSN36.js.map} +1 -1
  115. package/dist/{chunk-33B2BSME.cjs → chunk-NETYW4V3.cjs} +13 -5
  116. package/dist/chunk-NETYW4V3.cjs.map +1 -0
  117. package/dist/{chunk-OVGNXGCK.cjs → chunk-NNNUQELM.cjs} +9 -9
  118. package/dist/{chunk-OVGNXGCK.cjs.map → chunk-NNNUQELM.cjs.map} +1 -1
  119. package/dist/{chunk-BM7VYZED.js → chunk-NOM2YWFP.js} +5 -5
  120. package/dist/{chunk-BM7VYZED.js.map → chunk-NOM2YWFP.js.map} +1 -1
  121. package/dist/{chunk-WMWZAJMJ.cjs → chunk-NRA36JKG.cjs} +11 -11
  122. package/dist/{chunk-WMWZAJMJ.cjs.map → chunk-NRA36JKG.cjs.map} +1 -1
  123. package/dist/{chunk-4HKAZRTC.js → chunk-O3IZ7JEL.js} +3 -3
  124. package/dist/{chunk-4HKAZRTC.js.map → chunk-O3IZ7JEL.js.map} +1 -1
  125. package/dist/{chunk-RHQJX3EI.cjs → chunk-OEFFPR2S.cjs} +4 -4
  126. package/dist/{chunk-RHQJX3EI.cjs.map → chunk-OEFFPR2S.cjs.map} +1 -1
  127. package/dist/{chunk-4GGXF7YM.js → chunk-OLLOUAUJ.js} +3 -3
  128. package/dist/{chunk-4GGXF7YM.js.map → chunk-OLLOUAUJ.js.map} +1 -1
  129. package/dist/{chunk-RA2UZBYP.js → chunk-PAV4ZPSW.js} +3 -3
  130. package/dist/{chunk-RA2UZBYP.js.map → chunk-PAV4ZPSW.js.map} +1 -1
  131. package/dist/{chunk-RNCN2TTP.js → chunk-PBML2FHN.js} +2 -2
  132. package/dist/{chunk-A76OFN2B.cjs.map → chunk-PBML2FHN.js.map} +1 -1
  133. package/dist/{chunk-XRKFWV7K.js → chunk-PYM5OUL4.js} +5 -5
  134. package/dist/{chunk-XRKFWV7K.js.map → chunk-PYM5OUL4.js.map} +1 -1
  135. package/dist/{chunk-F4SQTWVR.js → chunk-Q4DTGCSD.js} +3 -3
  136. package/dist/{chunk-F4SQTWVR.js.map → chunk-Q4DTGCSD.js.map} +1 -1
  137. package/dist/{chunk-S7OEXQMI.cjs → chunk-R3CKCRK3.cjs} +4 -4
  138. package/dist/{chunk-S7OEXQMI.cjs.map → chunk-R3CKCRK3.cjs.map} +1 -1
  139. package/dist/{chunk-5COPO3H4.cjs → chunk-RBQYHEZD.cjs} +4 -4
  140. package/dist/{chunk-5COPO3H4.cjs.map → chunk-RBQYHEZD.cjs.map} +1 -1
  141. package/dist/{chunk-KRPEPZQY.js → chunk-RJBHWM6D.js} +7 -7
  142. package/dist/chunk-RJBHWM6D.js.map +1 -0
  143. package/dist/{chunk-U53AYSHS.cjs → chunk-S4Q5OMIK.cjs} +11 -11
  144. package/dist/{chunk-U53AYSHS.cjs.map → chunk-S4Q5OMIK.cjs.map} +1 -1
  145. package/dist/{chunk-FUP3ZA5T.js → chunk-SNKY3C2L.js} +4 -4
  146. package/dist/{chunk-FUP3ZA5T.js.map → chunk-SNKY3C2L.js.map} +1 -1
  147. package/dist/{chunk-BBMN4O6E.js → chunk-TJRPNBY5.js} +4 -4
  148. package/dist/{chunk-BBMN4O6E.js.map → chunk-TJRPNBY5.js.map} +1 -1
  149. package/dist/{chunk-27E4EMR6.cjs → chunk-UJMEWGO6.cjs} +4 -4
  150. package/dist/{chunk-27E4EMR6.cjs.map → chunk-UJMEWGO6.cjs.map} +1 -1
  151. package/dist/{chunk-X627TO3A.js → chunk-UTYCG4RB.js} +12 -12
  152. package/dist/chunk-UTYCG4RB.js.map +1 -0
  153. package/dist/{chunk-5XPKYDK7.js → chunk-VQFSEKU5.js} +12 -5
  154. package/dist/chunk-VQFSEKU5.js.map +1 -0
  155. package/dist/{chunk-NJVV5OAV.cjs → chunk-WCXOKGOQ.cjs} +8 -8
  156. package/dist/chunk-WCXOKGOQ.cjs.map +1 -0
  157. package/dist/{chunk-PIBXDEZM.cjs → chunk-WIGJGFH4.cjs} +5 -5
  158. package/dist/{chunk-PIBXDEZM.cjs.map → chunk-WIGJGFH4.cjs.map} +1 -1
  159. package/dist/{chunk-LOTWA65Z.cjs → chunk-X2YQP452.cjs} +11 -11
  160. package/dist/{chunk-LOTWA65Z.cjs.map → chunk-X2YQP452.cjs.map} +1 -1
  161. package/dist/{chunk-ZAKTZ5B4.cjs → chunk-XA3TSBAH.cjs} +8 -8
  162. package/dist/{chunk-ZAKTZ5B4.cjs.map → chunk-XA3TSBAH.cjs.map} +1 -1
  163. package/dist/{chunk-H2V6CXM7.cjs → chunk-XR4LPBXH.cjs} +9 -9
  164. package/dist/{chunk-H2V6CXM7.cjs.map → chunk-XR4LPBXH.cjs.map} +1 -1
  165. package/dist/{chunk-6AE4QTSF.cjs → chunk-Y33IGXCJ.cjs} +24 -24
  166. package/dist/{chunk-6AE4QTSF.cjs.map → chunk-Y33IGXCJ.cjs.map} +1 -1
  167. package/dist/{chunk-E7WWIX34.cjs → chunk-YULF6FPB.cjs} +8 -8
  168. package/dist/{chunk-E7WWIX34.cjs.map → chunk-YULF6FPB.cjs.map} +1 -1
  169. package/dist/{chunk-23HI77BZ.js → chunk-Z6N6SDNR.js} +4 -4
  170. package/dist/chunk-Z6N6SDNR.js.map +1 -0
  171. package/dist/{chunk-A76OFN2B.cjs → chunk-ZHPET3LZ.cjs} +2 -2
  172. package/dist/chunk-ZHPET3LZ.cjs.map +1 -0
  173. package/dist/{chunk-5VKUZ26Q.js → chunk-ZNW2TXLO.js} +3 -3
  174. package/dist/{chunk-5VKUZ26Q.js.map → chunk-ZNW2TXLO.js.map} +1 -1
  175. package/dist/{chunk-N4JNY5DT.cjs → chunk-ZO2L5U6F.cjs} +32 -32
  176. package/dist/chunk-ZO2L5U6F.cjs.map +1 -0
  177. package/dist/{chunk-RMCHJZNZ.js → chunk-ZS6SLELQ.js} +4 -4
  178. package/dist/{chunk-RMCHJZNZ.js.map → chunk-ZS6SLELQ.js.map} +1 -1
  179. package/dist/{chunk-7PBAJ2WA.js → chunk-ZTEAJAE6.js} +3 -3
  180. package/dist/{chunk-7PBAJ2WA.js.map → chunk-ZTEAJAE6.js.map} +1 -1
  181. package/dist/compact-session-65XCKO6H.js +18 -0
  182. package/dist/{compact-session-AZU2LEAE.js.map → compact-session-65XCKO6H.js.map} +1 -1
  183. package/dist/compact-session-OU6SRPVJ.cjs +55 -0
  184. package/dist/{compact-session-TRCEYCPG.cjs.map → compact-session-OU6SRPVJ.cjs.map} +1 -1
  185. package/dist/compaction.cjs +16 -16
  186. package/dist/compaction.js +3 -3
  187. package/dist/concurrency.cjs +6 -6
  188. package/dist/concurrency.js +4 -4
  189. package/dist/context-2G4375BZ.cjs +22 -0
  190. package/dist/{context-DNFT4B5D.cjs.map → context-2G4375BZ.cjs.map} +1 -1
  191. package/dist/context-GSQYVVMJ.js +5 -0
  192. package/dist/{context-LYE6TJL5.js.map → context-GSQYVVMJ.js.map} +1 -1
  193. package/dist/{cron-BGR0HOz9.d.cts → cron-DgHJnMAK.d.cts} +2 -2
  194. package/dist/{cron-CDAIWCrL.d.ts → cron-DyWQsEG6.d.ts} +2 -2
  195. package/dist/cron.cjs +33 -33
  196. package/dist/cron.d.cts +3 -3
  197. package/dist/cron.d.ts +3 -3
  198. package/dist/cron.js +32 -32
  199. package/dist/{errors-DxQe4_Qy.d.ts → errors-BSoXcl3F.d.cts} +3 -3
  200. package/dist/{errors-L1bxHHO0.d.cts → errors-CHllybaU.d.ts} +3 -3
  201. package/dist/errors.cjs +21 -21
  202. package/dist/errors.d.cts +2 -2
  203. package/dist/errors.d.ts +2 -2
  204. package/dist/errors.js +2 -2
  205. package/dist/eval.cjs +43 -43
  206. package/dist/eval.cjs.map +1 -1
  207. package/dist/eval.js +33 -33
  208. package/dist/eval.js.map +1 -1
  209. package/dist/{executor-TQ3FSZ7F.cjs → executor-CB75B5BH.cjs} +24 -24
  210. package/dist/{executor-TQ3FSZ7F.cjs.map → executor-CB75B5BH.cjs.map} +1 -1
  211. package/dist/{executor-PCRX3533.js → executor-VQLTQY53.js} +7 -7
  212. package/dist/{executor-PCRX3533.js.map → executor-VQLTQY53.js.map} +1 -1
  213. package/dist/filesystem/index.cjs +7 -7
  214. package/dist/filesystem/index.js +3 -3
  215. package/dist/fs-session-store-MAZV5FXJ.cjs +19 -0
  216. package/dist/{fs-session-store-KRZZIG3O.cjs.map → fs-session-store-MAZV5FXJ.cjs.map} +1 -1
  217. package/dist/fs-session-store-ZNUYZHYI.js +10 -0
  218. package/dist/{fs-session-store-I6GUIFRO.js.map → fs-session-store-ZNUYZHYI.js.map} +1 -1
  219. package/dist/generate-object-6PWGH5DZ.cjs +20 -0
  220. package/dist/{generate-object-QILSGTEJ.cjs.map → generate-object-6PWGH5DZ.cjs.map} +1 -1
  221. package/dist/generate-object-IXMJ7FUX.js +7 -0
  222. package/dist/{generate-object-DLHT5RXH.js.map → generate-object-IXMJ7FUX.js.map} +1 -1
  223. package/dist/index-manager-X5IPG2JL.js +11 -0
  224. package/dist/{index-manager-SXF3FAQV.js.map → index-manager-X5IPG2JL.js.map} +1 -1
  225. package/dist/index-manager-YFFEPISE.cjs +20 -0
  226. package/dist/{index-manager-LEMQ73A7.cjs.map → index-manager-YFFEPISE.cjs.map} +1 -1
  227. package/dist/index.cjs +139 -139
  228. package/dist/index.cjs.map +1 -1
  229. package/dist/index.d.cts +13 -13
  230. package/dist/index.d.ts +13 -13
  231. package/dist/index.js +53 -53
  232. package/dist/index.js.map +1 -1
  233. package/dist/{inject-session-BVSERZCI.cjs → inject-session-DDC36KKP.cjs} +11 -11
  234. package/dist/{inject-session-BVSERZCI.cjs.map → inject-session-DDC36KKP.cjs.map} +1 -1
  235. package/dist/{inject-session-E75EP3LL.js → inject-session-UBM4KVSV.js} +8 -8
  236. package/dist/{inject-session-E75EP3LL.js.map → inject-session-UBM4KVSV.js.map} +1 -1
  237. package/dist/internal/auth/credential-store.d.ts +13 -0
  238. package/dist/internal/diagnostics.d.ts +2 -2
  239. package/dist/internal/error-mappers/anthropic.d.ts +1 -1
  240. package/dist/internal/eval/code-runner.d.ts +1 -1
  241. package/dist/internal/global-singleton.d.ts +1 -1
  242. package/dist/internal/judge/judge-call.d.ts +1 -1
  243. package/dist/internal/memory/adapters/index.cjs +8 -8
  244. package/dist/internal/memory/adapters/index.js +7 -7
  245. package/dist/internal/memory/embedding-adapter.d.ts +1 -1
  246. package/dist/internal/memory/memory-index.d.ts +1 -1
  247. package/dist/internal/persistence/atomic-write.d.cts +14 -1
  248. package/dist/internal/persistence/atomic-write.d.ts +14 -1
  249. package/dist/internal/persistence/index.cjs +25 -25
  250. package/dist/internal/persistence/index.js +6 -6
  251. package/dist/internal/persistence/jsonl.d.cts +2 -2
  252. package/dist/internal/persistence/jsonl.d.ts +2 -2
  253. package/dist/internal/persistence/session-artifacts.d.cts +27 -0
  254. package/dist/internal/persistence/session-artifacts.d.ts +27 -0
  255. package/dist/internal/persistence/session-transcript.d.cts +1 -1
  256. package/dist/internal/persistence/session-transcript.d.ts +1 -1
  257. package/dist/internal/runtime/lifecycle/env-policy.d.ts +1 -1
  258. package/dist/internal/security/index.cjs +13 -13
  259. package/dist/internal/security/index.js +3 -3
  260. package/dist/internal/session/agent-session.d.ts +1 -1
  261. package/dist/internal/session/compact-session.d.ts +1 -1
  262. package/dist/internal/session/session-cache.d.ts +1 -1
  263. package/dist/judge-call-3QZO5H5N.js +5 -0
  264. package/dist/{judge-call-NPRU7JIQ.js.map → judge-call-3QZO5H5N.js.map} +1 -1
  265. package/dist/judge-call-J5EETJL3.cjs +22 -0
  266. package/dist/{judge-call-AIT3EULV.cjs.map → judge-call-J5EETJL3.cjs.map} +1 -1
  267. package/dist/models.cjs +20 -20
  268. package/dist/models.cjs.map +1 -1
  269. package/dist/models.js +5 -5
  270. package/dist/models.js.map +1 -1
  271. package/dist/path-safety.cjs +10 -10
  272. package/dist/path-safety.js +3 -3
  273. package/dist/persistence.cjs +44 -30
  274. package/dist/persistence.cjs.map +1 -1
  275. package/dist/persistence.d.cts +4 -3
  276. package/dist/persistence.d.ts +4 -3
  277. package/dist/persistence.js +22 -12
  278. package/dist/persistence.js.map +1 -1
  279. package/dist/project.cjs +5 -5
  280. package/dist/project.js +3 -3
  281. package/dist/registry-KB3TS6BM.cjs +46 -0
  282. package/dist/{registry-VKDFTK6L.cjs.map → registry-KB3TS6BM.cjs.map} +1 -1
  283. package/dist/registry-PPFMCM4A.js +9 -0
  284. package/dist/{registry-AXQXPLFH.js.map → registry-PPFMCM4A.js.map} +1 -1
  285. package/dist/retry.cjs +4 -4
  286. package/dist/retry.js +3 -3
  287. package/dist/{run-XXnwwGOT.d.ts → run-C8FBAC8o.d.cts} +21 -2
  288. package/dist/{run-XXnwwGOT.d.cts → run-C8FBAC8o.d.ts} +21 -2
  289. package/dist/{run-until-BK56WG4P.js → run-until-HEQOUVU6.js} +2 -2
  290. package/dist/run-until-HEQOUVU6.js.map +1 -0
  291. package/dist/{run-until-L5KQD3PV.cjs → run-until-U2B5FJJI.cjs} +2 -2
  292. package/dist/run-until-U2B5FJJI.cjs.map +1 -0
  293. package/dist/sandbox/bwrap.d.cts +15 -1
  294. package/dist/sandbox/bwrap.d.ts +15 -1
  295. package/dist/sandbox/index.cjs +39 -24
  296. package/dist/sandbox/index.cjs.map +1 -1
  297. package/dist/sandbox/index.d.cts +1 -1
  298. package/dist/sandbox/index.d.ts +1 -1
  299. package/dist/sandbox/index.js +24 -10
  300. package/dist/sandbox/index.js.map +1 -1
  301. package/dist/sandbox/provision.d.cts +1 -1
  302. package/dist/sandbox/provision.d.ts +1 -1
  303. package/dist/server/errors-envelope.cjs +14 -14
  304. package/dist/server/errors-envelope.d.cts +3 -3
  305. package/dist/server/errors-envelope.d.ts +3 -3
  306. package/dist/server/errors-envelope.js +3 -3
  307. package/dist/session-transcript-7FWTO4BK.js +5 -0
  308. package/dist/{session-transcript-X3UMSVL2.js.map → session-transcript-7FWTO4BK.js.map} +1 -1
  309. package/dist/session-transcript-FYRKWRWV.cjs +50 -0
  310. package/dist/{session-transcript-SLQRKQ72.cjs.map → session-transcript-FYRKWRWV.cjs.map} +1 -1
  311. package/dist/skills.cjs +7 -7
  312. package/dist/skills.js +5 -5
  313. package/dist/stream-object-3R3HZPQN.cjs +20 -0
  314. package/dist/{stream-object-3HEUGMQY.cjs.map → stream-object-3R3HZPQN.cjs.map} +1 -1
  315. package/dist/stream-object-NPJXDZXO.js +7 -0
  316. package/dist/{stream-object-VWYW7FJ2.js.map → stream-object-NPJXDZXO.js.map} +1 -1
  317. package/dist/subagents-loader-5KQVYUNS.js +6 -0
  318. package/dist/{subagents-loader-QUIK6GMV.js.map → subagents-loader-5KQVYUNS.js.map} +1 -1
  319. package/dist/subagents-loader-FDXPBBRA.cjs +15 -0
  320. package/dist/{subagents-loader-F52ARQ62.cjs.map → subagents-loader-FDXPBBRA.cjs.map} +1 -1
  321. package/dist/subagents-loader.cjs +15 -15
  322. package/dist/subagents-loader.cjs.map +1 -1
  323. package/dist/subagents-loader.d.cts +2 -2
  324. package/dist/subagents-loader.d.ts +2 -2
  325. package/dist/subagents-loader.js +14 -14
  326. package/dist/subagents-loader.js.map +1 -1
  327. package/dist/subscription/index.cjs +3 -3
  328. package/dist/subscription/index.js +2 -2
  329. package/dist/task-store.cjs +7 -7
  330. package/dist/task-store.js +4 -4
  331. package/dist/types/run-events.d.ts +20 -1
  332. package/dist/types/session-record.d.ts +1 -1
  333. package/dist/types/usage.d.ts +1 -1
  334. package/dist/workflow.cjs +27 -27
  335. package/dist/workflow.js +6 -6
  336. package/docs/error-codes.md +22 -0
  337. package/docs/harness-capability-map.md +22 -0
  338. package/package.json +1 -1
  339. package/dist/agent-MSR3DHO4.js +0 -46
  340. package/dist/agent-OOXJJD6A.cjs +0 -55
  341. package/dist/agent-session-store-EGTTYSKS.js +0 -6
  342. package/dist/agent-session-store-RHTLZ5OX.cjs +0 -23
  343. package/dist/chunk-23HI77BZ.js.map +0 -1
  344. package/dist/chunk-33B2BSME.cjs.map +0 -1
  345. package/dist/chunk-5KOW3GLE.js.map +0 -1
  346. package/dist/chunk-5XPKYDK7.js.map +0 -1
  347. package/dist/chunk-7GFX45DD.js.map +0 -1
  348. package/dist/chunk-AKMPQJPX.js.map +0 -1
  349. package/dist/chunk-BURYFNOM.cjs.map +0 -1
  350. package/dist/chunk-BVGJXMSB.cjs.map +0 -1
  351. package/dist/chunk-EYUZZXHZ.js.map +0 -1
  352. package/dist/chunk-KRPEPZQY.js.map +0 -1
  353. package/dist/chunk-LNTQRD23.cjs.map +0 -1
  354. package/dist/chunk-N4JNY5DT.cjs.map +0 -1
  355. package/dist/chunk-NJVV5OAV.cjs.map +0 -1
  356. package/dist/chunk-ONVIALVV.js.map +0 -1
  357. package/dist/chunk-QMIG7TKG.cjs.map +0 -1
  358. package/dist/chunk-RNCN2TTP.js.map +0 -1
  359. package/dist/chunk-SEWAPWAF.cjs.map +0 -1
  360. package/dist/chunk-T6KFGMNY.cjs.map +0 -1
  361. package/dist/chunk-UIPTINIF.js.map +0 -1
  362. package/dist/chunk-V7CA3CX5.cjs.map +0 -1
  363. package/dist/chunk-WPZTYOUX.cjs.map +0 -1
  364. package/dist/chunk-X627TO3A.js.map +0 -1
  365. package/dist/chunk-ZRQZOJ3N.js.map +0 -1
  366. package/dist/compact-session-AZU2LEAE.js +0 -18
  367. package/dist/compact-session-TRCEYCPG.cjs +0 -55
  368. package/dist/context-DNFT4B5D.cjs +0 -22
  369. package/dist/context-LYE6TJL5.js +0 -5
  370. package/dist/fs-session-store-I6GUIFRO.js +0 -10
  371. package/dist/fs-session-store-KRZZIG3O.cjs +0 -19
  372. package/dist/generate-object-DLHT5RXH.js +0 -7
  373. package/dist/generate-object-QILSGTEJ.cjs +0 -20
  374. package/dist/index-manager-LEMQ73A7.cjs +0 -20
  375. package/dist/index-manager-SXF3FAQV.js +0 -11
  376. package/dist/judge-call-AIT3EULV.cjs +0 -22
  377. package/dist/judge-call-NPRU7JIQ.js +0 -5
  378. package/dist/registry-AXQXPLFH.js +0 -9
  379. package/dist/registry-VKDFTK6L.cjs +0 -46
  380. package/dist/run-until-BK56WG4P.js.map +0 -1
  381. package/dist/run-until-L5KQD3PV.cjs.map +0 -1
  382. package/dist/session-transcript-SLQRKQ72.cjs +0 -50
  383. package/dist/session-transcript-X3UMSVL2.js +0 -5
  384. package/dist/stream-object-3HEUGMQY.cjs +0 -20
  385. package/dist/stream-object-VWYW7FJ2.js +0 -7
  386. package/dist/subagents-loader-F52ARQ62.cjs +0 -15
  387. package/dist/subagents-loader-QUIK6GMV.js +0 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AAchB,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,MAAM,IAAA,GAAO,KAAK,MAAA,IAAU,eAAA;AAC5B,EAAA,MAAM,GAAA,GAAM,KAAK,KAAA,IAAS,cAAA;AAC1B,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,IAAA,CAAK,MAAA;AAC7B,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,IAAa,IAAA,CAAK,gBAAgB,CAAA,EAAG;AAC7D,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAM,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,YAAY,CAAC,CAAA;AAAA,EACxD;AACA,EAAA,MAAM,UAAU,IAAA,CAAK,GAAA,CAAI,KAAK,IAAA,GAAO,CAAA,IAAK,KAAK,OAAO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AAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAIC,6BAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-ELYGL52R.cjs","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,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,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,UAAU,KAAA,CAAM,gBAAA;AACtB,MAAA,IAAI,OAAA,KAAY,MAAA,IAAa,GAAA,IAAO,OAAA,EAAS;AAC3C,QAAA,KAAA,CAAM,UAAA,GAAa,IAAA;AACnB,QAAA,KAAA,CAAM,YAAA,GAAe,MAAA;AACrB,QAAA,KAAA,CAAM,aAAA,GAAgB,MAAA;AACtB,QAAA,KAAA,CAAM,gBAAA,GAAmB,MAAA;AACzB,QAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;AAMA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAA0B,EAAC;AACjC,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAIC,6BAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-HLNLYLNN.cjs","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { sessions, transcriptKey, hydratedKeys } from './chunk-5KOW3GLE.js';
2
- import { persistTurn, readSessionMessages } from './chunk-7PBAJ2WA.js';
3
- import { diag } from './chunk-RNCN2TTP.js';
1
+ import { sessions, transcriptKey, hydratedKeys } from './chunk-4QEC4CCS.js';
2
+ import { persistTurn, readSessionMessages } from './chunk-ZTEAJAE6.js';
3
+ import { diag } from './chunk-PBML2FHN.js';
4
4
 
5
5
  // src/internal/session/agent-session.ts
6
6
  var pendingWrites = /* @__PURE__ */ new Map();
@@ -15,17 +15,17 @@ function appendSessionMessage(agentId, message) {
15
15
  var MAX_CACHED_SESSIONS = 32;
16
16
  function enforceCeiling() {
17
17
  while (sessions.size > MAX_CACHED_SESSIONS) {
18
- const maisAntiga = sessions.keys().next().value;
19
- if (maisAntiga === void 0) return;
20
- sessions.delete(maisAntiga);
21
- esquecerEscrituracao(maisAntiga);
18
+ const oldest = sessions.keys().next().value;
19
+ if (oldest === void 0) return;
20
+ sessions.delete(oldest);
21
+ forgetBookkeeping(oldest);
22
22
  }
23
23
  }
24
- function esquecerEscrituracao(agentId) {
25
- const sufixo = transcriptKey("", agentId).slice(0 - agentId.length - 2);
26
- for (const k of [...hydratedKeys]) if (k.endsWith(sufixo)) hydratedKeys.delete(k);
27
- for (const k of [...pendingWrites.keys()]) if (k.endsWith(sufixo)) pendingWrites.delete(k);
28
- for (const k of [...recordCounts.keys()]) if (k.endsWith(sufixo)) recordCounts.delete(k);
24
+ function forgetBookkeeping(agentId) {
25
+ const suffix = transcriptKey("", agentId).slice(0 - agentId.length - 2);
26
+ for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);
27
+ for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);
28
+ for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);
29
29
  }
30
30
  function discardSession(cwd, agentId) {
31
31
  const key = transcriptKey(cwd, agentId);
@@ -46,7 +46,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
46
46
  const count = (recordCounts.get(key) ?? 0) + 1;
47
47
  recordCounts.set(key, count);
48
48
  if (turn.autoCompact !== void 0) {
49
- const { autoCompactIfNeeded } = await import('./compact-session-AZU2LEAE.js');
49
+ const { autoCompactIfNeeded } = await import('./compact-session-65XCKO6H.js');
50
50
  const fired = await autoCompactIfNeeded({
51
51
  store,
52
52
  loc,
@@ -105,5 +105,5 @@ function enqueueSessionWrite(cwd, agentId, fn) {
105
105
  }
106
106
 
107
107
  export { appendSessionMessage, clearSession, discardSession, enqueueSessionWrite, flushSessionWrites, getSessionMessages, hydrateSession, persistTurnToTranscript };
108
- //# sourceMappingURL=chunk-ONVIALVV.js.map
109
- //# sourceMappingURL=chunk-ONVIALVV.js.map
108
+ //# sourceMappingURL=chunk-IMX5YODO.js.map
109
+ //# sourceMappingURL=chunk-IMX5YODO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":[],"mappings":";;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,QAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,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IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-IMX5YODO.js","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // risky. Tracked in usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { ConfigurationError } from './chunk-VQ33XLC6.js';
2
- import { diag } from './chunk-RNCN2TTP.js';
1
+ import { ConfigurationError } from './chunk-MRKSSN36.js';
2
+ import { diag } from './chunk-PBML2FHN.js';
3
3
  import { AsyncLocalStorage } from 'async_hooks';
4
4
  import { existsSync } from 'fs';
5
5
  import { readFile } from 'fs/promises';
@@ -131,5 +131,5 @@ function warnPersonalitySwitchInsideFork(agentId) {
131
131
  }
132
132
 
133
133
  export { currentPersonalityContext, loadHookConfig, warnOnce, warnPersonalitySwitchInsideFork, withPersonalityContext };
134
- //# sourceMappingURL=chunk-C64E2EJS.js.map
135
- //# sourceMappingURL=chunk-C64E2EJS.js.map
134
+ //# sourceMappingURL=chunk-J5RW43IR.js.map
135
+ //# sourceMappingURL=chunk-J5RW43IR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":[],"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,EAAA,IAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAcA,eAAsB,eAAe,GAAA,EAAkC;AACrE,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,EAAK,UAAA,EAAY,YAAY,CAAA;AAEnD,EAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EAAG;AACzB,IAAA,IAAI,WAAW,IAAA,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,MAAM,QAAA,CAAS,QAAA,EAAU,MA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tD,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,IAAI,iBAAA,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-C64E2EJS.js","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":[],"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,EAAA,IAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;A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I,OAAO,GAAA,CAAI,OAAA,KAAY,YAAY,GAAA,CAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAI,kBAAA,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,IAAI,iBAAA,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-J5RW43IR.js","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,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkE7WWIX34_cjs = require('./chunk-E7WWIX34.cjs');
3
+ var chunkYULF6FPB_cjs = require('./chunk-YULF6FPB.cjs');
4
4
  var fs = require('fs');
5
5
  var os = require('os');
6
6
 
7
- var SessionBusyError = class extends chunkE7WWIX34_cjs.TheokitAgentError {
7
+ var SessionBusyError = class extends chunkYULF6FPB_cjs.TheokitAgentError {
8
8
  constructor(sessionPath) {
9
9
  super(
10
10
  `another process is already writing this session: ${sessionPath}. Fork it to a new id instead of appending \u2014 two writers interleave lines into a sequence that parses but is not what either process wrote.`,
@@ -107,5 +107,5 @@ function createLease(sessionPath, lockPath) {
107
107
  exports.SessionBusyError = SessionBusyError;
108
108
  exports.acquireSessionWriter = acquireSessionWriter;
109
109
  exports.sessionHasWriter = sessionHasWriter;
110
- //# sourceMappingURL=chunk-4E3HLSYE.cjs.map
111
- //# sourceMappingURL=chunk-4E3HLSYE.cjs.map
110
+ //# sourceMappingURL=chunk-JA4FEA5Z.cjs.map
111
+ //# sourceMappingURL=chunk-JA4FEA5Z.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAiDO,IAAM,mBAAA,GAAsB,GAAA;AAUnC,SAAS,QAAA,GAAsB;AAC7B,EAAA,OAAO,EAAE,GAAA,EA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IAAA,KAAS,QAAA,EAAU,MAAM,GAAA;AAI5D,IAAA,IAAI,CAAC,YAAY,SAAA,CAAU,QAAQ,CAAC,CAAA,EAAG,MAAM,IAAI,gBAAA,CAAiB,WAAW,CAAA;AAC7E,IAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AACzB,IAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAAA,EAC1C;AACA,EAAAG,YAAA,CAAU,EAAE,CAAA;AACZ,EAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AAEzB,EAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAC1C;AAGA,SAAS,WAAA,CAAY,aAAqB,QAAA,EAAsC;AAC9E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAAG,SAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC,CAAA;AAAA,IACA,OAAO,MAAY;AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-4E3HLSYE.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n * @internal\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","hostname","openSync","writeSync","fchmodSync","closeSync","readFileSync","existsSync","rmSync"],"mappings":";;;;;;AAmDO,IAAM,gBAAA,GAAN,cAA+BA,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**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n * @internal\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var chunk5COPO3H4_cjs = require('./chunk-5COPO3H4.cjs');
3
+ var chunkRBQYHEZD_cjs = require('./chunk-RBQYHEZD.cjs');
4
4
  var chunkPNVDQL5Y_cjs = require('./chunk-PNVDQL5Y.cjs');
5
5
  var chunkWJVHMTKB_cjs = require('./chunk-WJVHMTKB.cjs');
6
- var chunkZAKTZ5B4_cjs = require('./chunk-ZAKTZ5B4.cjs');
6
+ var chunkXA3TSBAH_cjs = require('./chunk-XA3TSBAH.cjs');
7
7
  var zod = require('zod');
8
8
 
9
9
  // src/internal/workflow/event-stream.ts
@@ -248,10 +248,10 @@ var Workflow = class {
248
248
  * `run.status === "failed"`.
249
249
  */
250
250
  async run(input, opts) {
251
- const { executeWorkflow } = await import('./executor-TQ3FSZ7F.cjs');
251
+ const { executeWorkflow } = await import('./executor-CB75B5BH.cjs');
252
252
  const result = await executeWorkflow(this._options, this._steps, input, opts);
253
253
  if (opts?.task !== void 0) {
254
- const { submit: taskSubmit } = await import('./registry-VKDFTK6L.cjs');
254
+ const { submit: taskSubmit } = await import('./registry-KB3TS6BM.cjs');
255
255
  const taskOpts = opts.task === true ? {} : opts.task;
256
256
  const id = taskOpts.id ?? `wf-${result.id}`;
257
257
  await taskSubmit({
@@ -290,7 +290,7 @@ var Workflow = class {
290
290
  stream(input, opts) {
291
291
  const queue = createEventStream();
292
292
  const result = (async () => {
293
- const { executeWorkflow } = await import('./executor-TQ3FSZ7F.cjs');
293
+ const { executeWorkflow } = await import('./executor-CB75B5BH.cjs');
294
294
  try {
295
295
  return await executeWorkflow(this._options, this._steps, input, {
296
296
  ...opts,
@@ -307,7 +307,7 @@ var Workflow = class {
307
307
  * `WorkflowSnapshotNotFoundError` if `runId` is unknown.
308
308
  */
309
309
  static async resume(opts) {
310
- const { resumeWorkflow } = await import('./executor-TQ3FSZ7F.cjs');
310
+ const { resumeWorkflow } = await import('./executor-CB75B5BH.cjs');
311
311
  return resumeWorkflow(opts);
312
312
  }
313
313
  };
@@ -345,7 +345,7 @@ function workflowStep(child, opts) {
345
345
  fn: async (input, ctx) => {
346
346
  const run = await child.run(input, { signal: ctx.signal });
347
347
  if (run.status === "completed") return run.output;
348
- throw new chunk5COPO3H4_cjs.WorkflowNestedError(id, child.__options.name, run.status, run.error);
348
+ throw new chunkRBQYHEZD_cjs.WorkflowNestedError(id, child.__options.name, run.status, run.error);
349
349
  }
350
350
  };
351
351
  }
@@ -388,7 +388,7 @@ function workflowAsTool(workflow, spec) {
388
388
  };
389
389
  }
390
390
  function validateStepId(id) {
391
- chunkZAKTZ5B4_cjs.sanitizeIdentifier(id, { maxLen: 64 });
391
+ chunkXA3TSBAH_cjs.sanitizeIdentifier(id, { maxLen: 64 });
392
392
  }
393
393
  function mintShortId() {
394
394
  return globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 8);
@@ -404,7 +404,7 @@ function nestedStepsOf(s) {
404
404
  }
405
405
  function walkStepsValidating(steps, seen) {
406
406
  for (const s of steps) {
407
- if (seen.has(s.id)) throw new chunk5COPO3H4_cjs.WorkflowDuplicateStepIdError(s.id);
407
+ if (seen.has(s.id)) throw new chunkRBQYHEZD_cjs.WorkflowDuplicateStepIdError(s.id);
408
408
  seen.add(s.id);
409
409
  for (const nested of nestedStepsOf(s)) {
410
410
  walkStepsValidating(nested, seen);
@@ -420,5 +420,5 @@ exports.cloneWorkflow = cloneWorkflow;
420
420
  exports.fn = fn;
421
421
  exports.workflowAsTool = workflowAsTool;
422
422
  exports.workflowStep = workflowStep;
423
- //# sourceMappingURL=chunk-EJNFZET4.cjs.map
424
- //# sourceMappingURL=chunk-EJNFZET4.cjs.map
423
+ //# sourceMappingURL=chunk-JO76RWCA.cjs.map
424
+ //# sourceMappingURL=chunk-JO76RWCA.cjs.map