@theokit/sdk 5.6.0 → 5.8.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 (367) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/dist/a2a/index.cjs +6 -6
  3. package/dist/a2a/index.js +2 -2
  4. package/dist/{agent-82d_DrCL.d.cts → agent-3RcPVGMo.d.cts} +22 -4
  5. package/dist/agent-7ERQNV66.js +59 -0
  6. package/dist/{agent-JJZM2VIK.js.map → agent-7ERQNV66.js.map} +1 -1
  7. package/dist/agent-LNTR4QH5.cjs +68 -0
  8. package/dist/{agent-47NS6ZVL.cjs.map → agent-LNTR4QH5.cjs.map} +1 -1
  9. package/dist/{agent-G6g-uwcB.d.ts → agent-lS68mYIL.d.ts} +22 -4
  10. package/dist/agent.d.ts +11 -0
  11. package/dist/auth/index.cjs +32 -32
  12. package/dist/auth/index.js +5 -5
  13. package/dist/{batch-US4F6WPK.js → batch-427O54FQ.js} +7 -7
  14. package/dist/{batch-US4F6WPK.js.map → batch-427O54FQ.js.map} +1 -1
  15. package/dist/{batch-I6T6MXZO.cjs → batch-U4SO4RLX.cjs} +24 -24
  16. package/dist/{batch-I6T6MXZO.cjs.map → batch-U4SO4RLX.cjs.map} +1 -1
  17. package/dist/{chunk-44I6UYVH.js → chunk-26NEAJ6T.js} +4 -4
  18. package/dist/{chunk-44I6UYVH.js.map → chunk-26NEAJ6T.js.map} +1 -1
  19. package/dist/{chunk-GCHZMH42.cjs → chunk-2STSX2SY.cjs} +264 -260
  20. package/dist/chunk-2STSX2SY.cjs.map +1 -0
  21. package/dist/{chunk-2UXQASTX.js → chunk-3CU5J7V3.js} +38 -34
  22. package/dist/chunk-3CU5J7V3.js.map +1 -0
  23. package/dist/{chunk-5NELQ6LB.js → chunk-4QCJAJAG.js} +12 -3
  24. package/dist/chunk-4QCJAJAG.js.map +1 -0
  25. package/dist/{chunk-XYFGKVZ7.js → chunk-53RDNK3H.js} +3 -3
  26. package/dist/{chunk-XYFGKVZ7.js.map → chunk-53RDNK3H.js.map} +1 -1
  27. package/dist/{chunk-2QKV4CGK.js → chunk-5522X223.js} +3 -3
  28. package/dist/{chunk-2QKV4CGK.js.map → chunk-5522X223.js.map} +1 -1
  29. package/dist/{chunk-EH6XD3FY.js → chunk-5DD4NJN3.js} +3 -3
  30. package/dist/{chunk-EH6XD3FY.js.map → chunk-5DD4NJN3.js.map} +1 -1
  31. package/dist/{chunk-V22DZIXO.js → chunk-5Q4RTLMP.js} +3 -3
  32. package/dist/{chunk-V22DZIXO.js.map → chunk-5Q4RTLMP.js.map} +1 -1
  33. package/dist/{chunk-4A3SKJ53.cjs → chunk-6PB5AQCY.cjs} +14 -14
  34. package/dist/{chunk-4A3SKJ53.cjs.map → chunk-6PB5AQCY.cjs.map} +1 -1
  35. package/dist/{chunk-PRZ3BES7.cjs → chunk-72CPLZPC.cjs} +5 -5
  36. package/dist/{chunk-PRZ3BES7.cjs.map → chunk-72CPLZPC.cjs.map} +1 -1
  37. package/dist/{chunk-GFFBXSQT.cjs → chunk-76PIKR4P.cjs} +22 -22
  38. package/dist/{chunk-GFFBXSQT.cjs.map → chunk-76PIKR4P.cjs.map} +1 -1
  39. package/dist/{chunk-EFMFILPG.js → chunk-7F7XE6CM.js} +3 -3
  40. package/dist/{chunk-EFMFILPG.js.map → chunk-7F7XE6CM.js.map} +1 -1
  41. package/dist/{chunk-N2KAIZ5D.js → chunk-7GDHFV2M.js} +4 -20
  42. package/dist/chunk-7GDHFV2M.js.map +1 -0
  43. package/dist/{chunk-CA5VUAP3.js → chunk-7HUCU3KK.js} +5 -5
  44. package/dist/{chunk-CA5VUAP3.js.map → chunk-7HUCU3KK.js.map} +1 -1
  45. package/dist/{chunk-4MMWFSCD.js → chunk-7JAKO3NM.js} +3 -3
  46. package/dist/{chunk-4MMWFSCD.js.map → chunk-7JAKO3NM.js.map} +1 -1
  47. package/dist/{chunk-UADQJBHR.cjs → chunk-7NQ7HJ3E.cjs} +6 -6
  48. package/dist/{chunk-UADQJBHR.cjs.map → chunk-7NQ7HJ3E.cjs.map} +1 -1
  49. package/dist/{chunk-HG4UN4MN.cjs → chunk-AOHRKGAA.cjs} +22 -22
  50. package/dist/{chunk-HG4UN4MN.cjs.map → chunk-AOHRKGAA.cjs.map} +1 -1
  51. package/dist/{chunk-C4ZQPWXJ.cjs → chunk-ARMFXTY6.cjs} +143 -190
  52. package/dist/chunk-ARMFXTY6.cjs.map +1 -0
  53. package/dist/{chunk-5WKQDIGO.js → chunk-AY43232P.js} +4 -4
  54. package/dist/{chunk-5WKQDIGO.js.map → chunk-AY43232P.js.map} +1 -1
  55. package/dist/{chunk-7FDKWDA2.cjs → chunk-B3XXQX6L.cjs} +7 -7
  56. package/dist/{chunk-7FDKWDA2.cjs.map → chunk-B3XXQX6L.cjs.map} +1 -1
  57. package/dist/{chunk-ALUN2B4W.js → chunk-B5MHRQJZ.js} +9 -3
  58. package/dist/chunk-B5MHRQJZ.js.map +1 -0
  59. package/dist/{chunk-TA3K7SBK.js → chunk-BKMDRBJ7.js} +3 -3
  60. package/dist/{chunk-TA3K7SBK.js.map → chunk-BKMDRBJ7.js.map} +1 -1
  61. package/dist/{chunk-FUSDYC2B.cjs → chunk-CQYBJOB2.cjs} +4 -4
  62. package/dist/{chunk-FUSDYC2B.cjs.map → chunk-CQYBJOB2.cjs.map} +1 -1
  63. package/dist/{chunk-7JJ3A6AT.cjs → chunk-D5KXKBEN.cjs} +5 -5
  64. package/dist/{chunk-7JJ3A6AT.cjs.map → chunk-D5KXKBEN.cjs.map} +1 -1
  65. package/dist/{chunk-HUDNLFY4.js → chunk-DDRX4LYS.js} +13 -4
  66. package/dist/chunk-DDRX4LYS.js.map +1 -0
  67. package/dist/{chunk-QDM3OHUT.cjs → chunk-ECD6ER3E.cjs} +4 -4
  68. package/dist/{chunk-QDM3OHUT.cjs.map → chunk-ECD6ER3E.cjs.map} +1 -1
  69. package/dist/{chunk-JMDDYA22.js → chunk-EJROML3Q.js} +4 -4
  70. package/dist/{chunk-JMDDYA22.js.map → chunk-EJROML3Q.js.map} +1 -1
  71. package/dist/{chunk-FPIY5CLV.js → chunk-FRL35MFN.js} +5 -5
  72. package/dist/{chunk-FPIY5CLV.js.map → chunk-FRL35MFN.js.map} +1 -1
  73. package/dist/{chunk-EIQFAOFD.js → chunk-GGRPAQ3B.js} +3 -3
  74. package/dist/{chunk-EIQFAOFD.js.map → chunk-GGRPAQ3B.js.map} +1 -1
  75. package/dist/{chunk-HCT4HPCL.cjs → chunk-GHHIJEFX.cjs} +4 -4
  76. package/dist/{chunk-HCT4HPCL.cjs.map → chunk-GHHIJEFX.cjs.map} +1 -1
  77. package/dist/{chunk-7A6535RA.cjs → chunk-GM54F4FE.cjs} +9 -9
  78. package/dist/{chunk-7A6535RA.cjs.map → chunk-GM54F4FE.cjs.map} +1 -1
  79. package/dist/{chunk-6M2OIS4Y.js → chunk-GMRFAX4I.js} +74 -4
  80. package/dist/chunk-GMRFAX4I.js.map +1 -0
  81. package/dist/{chunk-O6USDERH.js → chunk-GMSRRJ53.js} +3 -3
  82. package/dist/{chunk-O6USDERH.js.map → chunk-GMSRRJ53.js.map} +1 -1
  83. package/dist/{chunk-VE6DFSKU.js → chunk-GTX6FEDP.js} +3 -3
  84. package/dist/{chunk-VE6DFSKU.js.map → chunk-GTX6FEDP.js.map} +1 -1
  85. package/dist/{chunk-NJWYQWDL.js → chunk-H3CVJSFC.js} +3 -3
  86. package/dist/{chunk-NJWYQWDL.js.map → chunk-H3CVJSFC.js.map} +1 -1
  87. package/dist/{chunk-MYJGWS2J.cjs → chunk-HG5LKFG7.cjs} +16 -16
  88. package/dist/{chunk-MYJGWS2J.cjs.map → chunk-HG5LKFG7.cjs.map} +1 -1
  89. package/dist/{chunk-55GB6JYQ.js → chunk-HOHR75KF.js} +5 -5
  90. package/dist/{chunk-55GB6JYQ.js.map → chunk-HOHR75KF.js.map} +1 -1
  91. package/dist/{chunk-GBCVPKHE.js → chunk-HV4V63CO.js} +3 -3
  92. package/dist/{chunk-GBCVPKHE.js.map → chunk-HV4V63CO.js.map} +1 -1
  93. package/dist/{chunk-I2PWY7VM.cjs → chunk-IIYJMXYW.cjs} +4 -4
  94. package/dist/{chunk-I2PWY7VM.cjs.map → chunk-IIYJMXYW.cjs.map} +1 -1
  95. package/dist/chunk-J4SA2ZEJ.cjs +24 -0
  96. package/dist/chunk-J4SA2ZEJ.cjs.map +1 -0
  97. package/dist/{chunk-ATT276RD.cjs → chunk-J5623RIV.cjs} +78 -6
  98. package/dist/chunk-J5623RIV.cjs.map +1 -0
  99. package/dist/{chunk-KVSAY6NZ.cjs → chunk-J6GXS5A2.cjs} +13 -13
  100. package/dist/{chunk-KVSAY6NZ.cjs.map → chunk-J6GXS5A2.cjs.map} +1 -1
  101. package/dist/{chunk-NQTD6QOW.cjs → chunk-JW3GVLM6.cjs} +4 -4
  102. package/dist/{chunk-NQTD6QOW.cjs.map → chunk-JW3GVLM6.cjs.map} +1 -1
  103. package/dist/{chunk-TFG5IBZS.cjs → chunk-KGZ66JVZ.cjs} +14 -14
  104. package/dist/{chunk-TFG5IBZS.cjs.map → chunk-KGZ66JVZ.cjs.map} +1 -1
  105. package/dist/{chunk-47TF32NQ.js → chunk-KO6SHCEH.js} +3 -3
  106. package/dist/{chunk-47TF32NQ.js.map → chunk-KO6SHCEH.js.map} +1 -1
  107. package/dist/{chunk-EIOMN5VA.cjs → chunk-KTA7YTZQ.cjs} +17 -8
  108. package/dist/chunk-KTA7YTZQ.cjs.map +1 -0
  109. package/dist/{chunk-D6POWE7E.cjs → chunk-MEUBLCM4.cjs} +11 -11
  110. package/dist/{chunk-D6POWE7E.cjs.map → chunk-MEUBLCM4.cjs.map} +1 -1
  111. package/dist/{chunk-VWUXIVEI.js → chunk-MFZODA5Y.js} +5 -5
  112. package/dist/{chunk-VWUXIVEI.js.map → chunk-MFZODA5Y.js.map} +1 -1
  113. package/dist/{chunk-4HS6FFGL.cjs → chunk-MPQJE3G4.cjs} +15 -15
  114. package/dist/{chunk-4HS6FFGL.cjs.map → chunk-MPQJE3G4.cjs.map} +1 -1
  115. package/dist/{chunk-QRVS2PRE.cjs → chunk-MPR2ISL2.cjs} +4 -4
  116. package/dist/{chunk-QRVS2PRE.cjs.map → chunk-MPR2ISL2.cjs.map} +1 -1
  117. package/dist/{chunk-UOLBAPDM.js → chunk-MQGSOKR3.js} +3 -3
  118. package/dist/{chunk-UOLBAPDM.js.map → chunk-MQGSOKR3.js.map} +1 -1
  119. package/dist/{chunk-HFEJE7AC.js → chunk-MU7IAA7G.js} +9 -9
  120. package/dist/{chunk-HFEJE7AC.js.map → chunk-MU7IAA7G.js.map} +1 -1
  121. package/dist/{chunk-EXTRW7GW.cjs → chunk-NAGPKWOD.cjs} +4 -4
  122. package/dist/{chunk-EXTRW7GW.cjs.map → chunk-NAGPKWOD.cjs.map} +1 -1
  123. package/dist/{chunk-KTTHHYEW.cjs → chunk-NJSIAJEK.cjs} +4 -4
  124. package/dist/{chunk-KTTHHYEW.cjs.map → chunk-NJSIAJEK.cjs.map} +1 -1
  125. package/dist/{chunk-Z3NTRKIC.cjs → chunk-NKIQTLFA.cjs} +4 -4
  126. package/dist/{chunk-Z3NTRKIC.cjs.map → chunk-NKIQTLFA.cjs.map} +1 -1
  127. package/dist/{chunk-KZSKIUXZ.js → chunk-NOO6GZTZ.js} +37 -85
  128. package/dist/chunk-NOO6GZTZ.js.map +1 -0
  129. package/dist/{chunk-7IZKTQ5G.cjs → chunk-OCEQ6DW2.cjs} +10 -29
  130. package/dist/chunk-OCEQ6DW2.cjs.map +1 -0
  131. package/dist/{chunk-BJUJT5ED.cjs → chunk-OF2CLCTH.cjs} +4 -4
  132. package/dist/{chunk-BJUJT5ED.cjs.map → chunk-OF2CLCTH.cjs.map} +1 -1
  133. package/dist/{chunk-HUFSABUZ.cjs → chunk-OLSEWLK5.cjs} +6 -6
  134. package/dist/{chunk-HUFSABUZ.cjs.map → chunk-OLSEWLK5.cjs.map} +1 -1
  135. package/dist/{chunk-DQZU7JK6.cjs → chunk-P22BZE7G.cjs} +4 -4
  136. package/dist/{chunk-DQZU7JK6.cjs.map → chunk-P22BZE7G.cjs.map} +1 -1
  137. package/dist/{chunk-QWD3CZWE.cjs → chunk-P7NNKEWO.cjs} +4 -4
  138. package/dist/{chunk-QWD3CZWE.cjs.map → chunk-P7NNKEWO.cjs.map} +1 -1
  139. package/dist/chunk-PQCTDMUI.js +20 -0
  140. package/dist/chunk-PQCTDMUI.js.map +1 -0
  141. package/dist/{chunk-DZG77WU7.cjs → chunk-PSLCVSCS.cjs} +3 -3
  142. package/dist/{chunk-DZG77WU7.cjs.map → chunk-PSLCVSCS.cjs.map} +1 -1
  143. package/dist/{chunk-STGSMJMJ.js → chunk-QDQQYRJI.js} +4 -4
  144. package/dist/{chunk-STGSMJMJ.js.map → chunk-QDQQYRJI.js.map} +1 -1
  145. package/dist/{chunk-7MMTZBTT.js → chunk-R2C3HXR3.js} +4 -4
  146. package/dist/{chunk-7MMTZBTT.js.map → chunk-R2C3HXR3.js.map} +1 -1
  147. package/dist/chunk-R3ZQBPA5.cjs +18 -0
  148. package/dist/{chunk-ANMJJD6D.cjs.map → chunk-R3ZQBPA5.cjs.map} +1 -1
  149. package/dist/{chunk-4NLCWGH7.cjs → chunk-RA7IE4NK.cjs} +15 -15
  150. package/dist/{chunk-4NLCWGH7.cjs.map → chunk-RA7IE4NK.cjs.map} +1 -1
  151. package/dist/{chunk-UBR5PWD7.js → chunk-SUVCHX4L.js} +3 -3
  152. package/dist/{chunk-UBR5PWD7.js.map → chunk-SUVCHX4L.js.map} +1 -1
  153. package/dist/{chunk-LD6HASA5.cjs → chunk-SWALPLFQ.cjs} +12 -2
  154. package/dist/chunk-SWALPLFQ.cjs.map +1 -0
  155. package/dist/{chunk-52FDUJSV.cjs → chunk-T5KOSR5Y.cjs} +11 -11
  156. package/dist/{chunk-52FDUJSV.cjs.map → chunk-T5KOSR5Y.cjs.map} +1 -1
  157. package/dist/{chunk-BZ3YMAMP.js → chunk-TC4RWP3Y.js} +6 -6
  158. package/dist/{chunk-BZ3YMAMP.js.map → chunk-TC4RWP3Y.js.map} +1 -1
  159. package/dist/{chunk-XB4GI5RZ.js → chunk-TE6XVTOA.js} +3 -3
  160. package/dist/{chunk-XB4GI5RZ.js.map → chunk-TE6XVTOA.js.map} +1 -1
  161. package/dist/{chunk-VUHXC74Q.cjs → chunk-TTBIQTO5.cjs} +19 -19
  162. package/dist/{chunk-VUHXC74Q.cjs.map → chunk-TTBIQTO5.cjs.map} +1 -1
  163. package/dist/{chunk-J7J7J2GN.cjs → chunk-UNFBHV46.cjs} +9 -2
  164. package/dist/chunk-UNFBHV46.cjs.map +1 -0
  165. package/dist/{chunk-AAEZSPTC.js → chunk-UNZOJVVC.js} +4 -4
  166. package/dist/{chunk-AAEZSPTC.js.map → chunk-UNZOJVVC.js.map} +1 -1
  167. package/dist/{chunk-T3ZDEYTJ.js → chunk-W4VQMXBZ.js} +4 -4
  168. package/dist/{chunk-T3ZDEYTJ.js.map → chunk-W4VQMXBZ.js.map} +1 -1
  169. package/dist/{chunk-24SYBZPL.cjs → chunk-WPO3VCY4.cjs} +9 -9
  170. package/dist/{chunk-24SYBZPL.cjs.map → chunk-WPO3VCY4.cjs.map} +1 -1
  171. package/dist/{chunk-IUMAQURF.js → chunk-X6DUEDAF.js} +3 -3
  172. package/dist/{chunk-IUMAQURF.js.map → chunk-X6DUEDAF.js.map} +1 -1
  173. package/dist/{chunk-CFE6QF2Q.js → chunk-XCQ432OX.js} +3 -3
  174. package/dist/{chunk-CFE6QF2Q.js.map → chunk-XCQ432OX.js.map} +1 -1
  175. package/dist/{chunk-QWD4RDZ3.cjs → chunk-XDUGSTYJ.cjs} +15 -15
  176. package/dist/{chunk-QWD4RDZ3.cjs.map → chunk-XDUGSTYJ.cjs.map} +1 -1
  177. package/dist/{chunk-K2VMFZQ5.js → chunk-XKMVJ443.js} +5 -5
  178. package/dist/{chunk-K2VMFZQ5.js.map → chunk-XKMVJ443.js.map} +1 -1
  179. package/dist/{chunk-RWPLWMCZ.cjs → chunk-XW4POZ6V.cjs} +11 -11
  180. package/dist/{chunk-RWPLWMCZ.cjs.map → chunk-XW4POZ6V.cjs.map} +1 -1
  181. package/dist/{chunk-6PWOWXMC.js → chunk-XZHJYSPB.js} +3 -3
  182. package/dist/{chunk-6PWOWXMC.js.map → chunk-XZHJYSPB.js.map} +1 -1
  183. package/dist/{chunk-QC55H6RJ.cjs → chunk-YRJA2POB.cjs} +9 -9
  184. package/dist/{chunk-QC55H6RJ.cjs.map → chunk-YRJA2POB.cjs.map} +1 -1
  185. package/dist/{chunk-DMRT67Y6.js → chunk-ZJZ7LV3A.js} +3 -3
  186. package/dist/{chunk-DMRT67Y6.js.map → chunk-ZJZ7LV3A.js.map} +1 -1
  187. package/dist/{chunk-G7BLGBRN.js → chunk-ZWFTECOE.js} +3 -3
  188. package/dist/{chunk-G7BLGBRN.js.map → chunk-ZWFTECOE.js.map} +1 -1
  189. package/dist/compact-session-2N3ZYJTW.js +24 -0
  190. package/dist/{compact-session-YSEK7NQF.js.map → compact-session-2N3ZYJTW.js.map} +1 -1
  191. package/dist/compact-session-RBPLUPCK.cjs +65 -0
  192. package/dist/{compact-session-7FMYJXQ7.cjs.map → compact-session-RBPLUPCK.cjs.map} +1 -1
  193. package/dist/compaction.cjs +20 -16
  194. package/dist/compaction.d.cts +2 -0
  195. package/dist/compaction.d.ts +2 -0
  196. package/dist/compaction.js +2 -2
  197. package/dist/concurrency.cjs +5 -5
  198. package/dist/concurrency.js +3 -3
  199. package/dist/context/index.cjs +15 -7
  200. package/dist/context/index.cjs.map +1 -1
  201. package/dist/context/index.d.cts +2 -0
  202. package/dist/context/index.d.ts +2 -0
  203. package/dist/context/index.js +7 -3
  204. package/dist/context/index.js.map +1 -1
  205. package/dist/context-SXR2HLHT.js +7 -0
  206. package/dist/{context-J5BJ3LBS.js.map → context-SXR2HLHT.js.map} +1 -1
  207. package/dist/context-ZOULM2RB.cjs +24 -0
  208. package/dist/{context-HR4KMXMA.cjs.map → context-ZOULM2RB.cjs.map} +1 -1
  209. package/dist/{cron-DWv69ZSD.d.cts → cron-CGxoEKlx.d.cts} +2 -2
  210. package/dist/{cron-GynWtAax.d.ts → cron-DJv8zMa3.d.ts} +2 -2
  211. package/dist/cron.cjs +34 -33
  212. package/dist/cron.d.cts +4 -4
  213. package/dist/cron.d.ts +4 -4
  214. package/dist/cron.js +33 -32
  215. package/dist/{errors-DrDEgyz1.d.cts → errors-BWOJeWTZ.d.cts} +25 -2
  216. package/dist/{errors-CLOAyuiv.d.ts → errors-DDvG18IB.d.ts} +25 -2
  217. package/dist/errors.cjs +25 -21
  218. package/dist/errors.d.cts +2 -2
  219. package/dist/errors.d.ts +2 -2
  220. package/dist/errors.js +1 -1
  221. package/dist/eval.cjs +44 -43
  222. package/dist/eval.cjs.map +1 -1
  223. package/dist/eval.js +34 -33
  224. package/dist/eval.js.map +1 -1
  225. package/dist/{executor-XQAOQOHD.cjs → executor-2SUGI3ZT.cjs} +21 -21
  226. package/dist/{executor-XQAOQOHD.cjs.map → executor-2SUGI3ZT.cjs.map} +1 -1
  227. package/dist/{executor-ZNDQDX6Q.js → executor-3NI7KNL4.js} +6 -6
  228. package/dist/{executor-ZNDQDX6Q.js.map → executor-3NI7KNL4.js.map} +1 -1
  229. package/dist/filesystem/index.cjs +11 -11
  230. package/dist/filesystem/index.js +2 -2
  231. package/dist/fs-session-store-JHBJFKVV.cjs +19 -0
  232. package/dist/{fs-session-store-E4U3P56L.cjs.map → fs-session-store-JHBJFKVV.cjs.map} +1 -1
  233. package/dist/fs-session-store-STZZFXH2.js +10 -0
  234. package/dist/{fs-session-store-77JU46UZ.js.map → fs-session-store-STZZFXH2.js.map} +1 -1
  235. package/dist/generate-object-NTKAWE7D.js +7 -0
  236. package/dist/{generate-object-BXV7BZRP.js.map → generate-object-NTKAWE7D.js.map} +1 -1
  237. package/dist/generate-object-YHTWG5DB.cjs +20 -0
  238. package/dist/{generate-object-YBI2TDJ3.cjs.map → generate-object-YHTWG5DB.cjs.map} +1 -1
  239. package/dist/index-manager-ONQJSWX5.js +17 -0
  240. package/dist/{index-manager-27WLNQEE.js.map → index-manager-ONQJSWX5.js.map} +1 -1
  241. package/dist/{index-manager-BBHDKMQS.cjs → index-manager-ZGJN25FD.cjs} +9 -9
  242. package/dist/{index-manager-BBHDKMQS.cjs.map → index-manager-ZGJN25FD.cjs.map} +1 -1
  243. package/dist/index.cjs +148 -145
  244. package/dist/index.cjs.map +1 -1
  245. package/dist/index.d.cts +57 -10
  246. package/dist/index.d.ts +57 -10
  247. package/dist/index.js +49 -48
  248. package/dist/index.js.map +1 -1
  249. package/dist/{inject-session-PC73TMP2.cjs → inject-session-3FPXJDJP.cjs} +4 -4
  250. package/dist/{inject-session-PC73TMP2.cjs.map → inject-session-3FPXJDJP.cjs.map} +1 -1
  251. package/dist/{inject-session-J4LBWAPH.js → inject-session-YNNOE3O6.js} +3 -3
  252. package/dist/{inject-session-J4LBWAPH.js.map → inject-session-YNNOE3O6.js.map} +1 -1
  253. package/dist/interactive/index.cjs +3 -3
  254. package/dist/interactive/index.js +1 -1
  255. package/dist/internal/memory/adapters/index.cjs +7 -7
  256. package/dist/internal/memory/adapters/index.js +6 -6
  257. package/dist/internal/memory/storage/index.cjs +35 -35
  258. package/dist/internal/memory/storage/index.js +6 -6
  259. package/dist/internal/persistence/index.cjs +11 -11
  260. package/dist/internal/persistence/index.js +3 -3
  261. package/dist/internal/runtime/compression/compression-model-registry.d.ts +1 -0
  262. package/dist/internal/runtime/compression/compression-summarizer.d.ts +0 -14
  263. package/dist/internal/runtime/context/context-discovery.d.ts +42 -0
  264. package/dist/internal/runtime/context/context-loaders.d.ts +5 -1
  265. package/dist/internal/security/index.cjs +9 -9
  266. package/dist/internal/security/index.js +2 -2
  267. package/dist/internal/session/compact-session.d.ts +36 -0
  268. package/dist/judge-call-AQQYK6VT.cjs +22 -0
  269. package/dist/{judge-call-46M2E5FA.cjs.map → judge-call-AQQYK6VT.cjs.map} +1 -1
  270. package/dist/judge-call-LOL5FQEX.js +5 -0
  271. package/dist/{judge-call-FGUNNWEI.js.map → judge-call-LOL5FQEX.js.map} +1 -1
  272. package/dist/mcp-auth.cjs +9 -9
  273. package/dist/mcp-auth.js +2 -2
  274. package/dist/models.cjs +15 -15
  275. package/dist/models.js +6 -6
  276. package/dist/oauth-transaction-store-NP2YHZ6D.js +5 -0
  277. package/dist/{oauth-transaction-store-5RIR6D5C.js.map → oauth-transaction-store-NP2YHZ6D.js.map} +1 -1
  278. package/dist/oauth-transaction-store-ZINDV7AF.cjs +38 -0
  279. package/dist/{oauth-transaction-store-SXIE57OD.cjs.map → oauth-transaction-store-ZINDV7AF.cjs.map} +1 -1
  280. package/dist/path-safety.cjs +9 -9
  281. package/dist/path-safety.js +2 -2
  282. package/dist/persistence.cjs +16 -16
  283. package/dist/persistence.js +4 -4
  284. package/dist/project.cjs +5 -5
  285. package/dist/project.js +2 -2
  286. package/dist/providers.cjs +8 -8
  287. package/dist/providers.js +6 -6
  288. package/dist/{registry-DMWCJKRF.js → registry-5FK42CRV.js} +6 -6
  289. package/dist/{registry-DMWCJKRF.js.map → registry-5FK42CRV.js.map} +1 -1
  290. package/dist/{registry-BZQFYRTL.cjs → registry-BVTNO73E.cjs} +14 -14
  291. package/dist/{registry-BZQFYRTL.cjs.map → registry-BVTNO73E.cjs.map} +1 -1
  292. package/dist/retry.cjs +3 -3
  293. package/dist/retry.js +2 -2
  294. package/dist/{run-CTAdRU3U.d.cts → run-DsA5Ip2i.d.cts} +1 -1
  295. package/dist/{run-CTAdRU3U.d.ts → run-DsA5Ip2i.d.ts} +1 -1
  296. package/dist/sandbox/index.cjs +18 -18
  297. package/dist/sandbox/index.js +3 -3
  298. package/dist/{sdk-agent-BOiKqOgL.d.cts → sdk-agent-dNwjwCt5.d.cts} +2 -2
  299. package/dist/{sdk-agent-D4a_BR_6.d.ts → sdk-agent-wEOLXD3F.d.ts} +2 -2
  300. package/dist/server/auth/index.cjs +21 -21
  301. package/dist/server/auth/index.js +6 -6
  302. package/dist/server/errors-envelope.cjs +13 -13
  303. package/dist/server/errors-envelope.d.cts +2 -2
  304. package/dist/server/errors-envelope.d.ts +2 -2
  305. package/dist/server/errors-envelope.js +2 -2
  306. package/dist/skills.cjs +7 -7
  307. package/dist/skills.js +4 -4
  308. package/dist/stream-object-QAEHG4YO.js +7 -0
  309. package/dist/{stream-object-HBFMIZLD.js.map → stream-object-QAEHG4YO.js.map} +1 -1
  310. package/dist/stream-object-TKVGGA54.cjs +20 -0
  311. package/dist/{stream-object-QSKHISDJ.cjs.map → stream-object-TKVGGA54.cjs.map} +1 -1
  312. package/dist/subagents-loader-7GE7YUDI.cjs +16 -0
  313. package/dist/{subagents-loader-MOO7DC4E.cjs.map → subagents-loader-7GE7YUDI.cjs.map} +1 -1
  314. package/dist/subagents-loader-S2PMZY7J.js +7 -0
  315. package/dist/{subagents-loader-CJFYQQU2.js.map → subagents-loader-S2PMZY7J.js.map} +1 -1
  316. package/dist/subagents-loader.cjs +5 -5
  317. package/dist/subagents-loader.d.cts +3 -3
  318. package/dist/subagents-loader.d.ts +3 -3
  319. package/dist/subagents-loader.js +3 -3
  320. package/dist/subscription/index.cjs +3 -2
  321. package/dist/subscription/index.d.cts +1 -1
  322. package/dist/subscription/index.d.ts +1 -1
  323. package/dist/subscription/index.js +2 -2
  324. package/dist/task-store.cjs +5 -5
  325. package/dist/task-store.js +2 -2
  326. package/dist/types/agent.d.ts +1 -1
  327. package/dist/workflow.cjs +25 -25
  328. package/dist/workflow.d.cts +2 -2
  329. package/dist/workflow.d.ts +2 -2
  330. package/dist/workflow.js +4 -4
  331. package/docs/error-codes.md +1 -1
  332. package/docs/harness-capability-map.md +17 -1
  333. package/package.json +1 -1
  334. package/dist/agent-47NS6ZVL.cjs +0 -67
  335. package/dist/agent-JJZM2VIK.js +0 -58
  336. package/dist/chunk-2UXQASTX.js.map +0 -1
  337. package/dist/chunk-5NELQ6LB.js.map +0 -1
  338. package/dist/chunk-6M2OIS4Y.js.map +0 -1
  339. package/dist/chunk-7IZKTQ5G.cjs.map +0 -1
  340. package/dist/chunk-ALUN2B4W.js.map +0 -1
  341. package/dist/chunk-ANMJJD6D.cjs +0 -18
  342. package/dist/chunk-ATT276RD.cjs.map +0 -1
  343. package/dist/chunk-C4ZQPWXJ.cjs.map +0 -1
  344. package/dist/chunk-EIOMN5VA.cjs.map +0 -1
  345. package/dist/chunk-GCHZMH42.cjs.map +0 -1
  346. package/dist/chunk-HUDNLFY4.js.map +0 -1
  347. package/dist/chunk-J7J7J2GN.cjs.map +0 -1
  348. package/dist/chunk-KZSKIUXZ.js.map +0 -1
  349. package/dist/chunk-LD6HASA5.cjs.map +0 -1
  350. package/dist/chunk-N2KAIZ5D.js.map +0 -1
  351. package/dist/compact-session-7FMYJXQ7.cjs +0 -61
  352. package/dist/compact-session-YSEK7NQF.js +0 -24
  353. package/dist/context-HR4KMXMA.cjs +0 -23
  354. package/dist/context-J5BJ3LBS.js +0 -6
  355. package/dist/fs-session-store-77JU46UZ.js +0 -10
  356. package/dist/fs-session-store-E4U3P56L.cjs +0 -19
  357. package/dist/generate-object-BXV7BZRP.js +0 -7
  358. package/dist/generate-object-YBI2TDJ3.cjs +0 -20
  359. package/dist/index-manager-27WLNQEE.js +0 -17
  360. package/dist/judge-call-46M2E5FA.cjs +0 -22
  361. package/dist/judge-call-FGUNNWEI.js +0 -5
  362. package/dist/oauth-transaction-store-5RIR6D5C.js +0 -5
  363. package/dist/oauth-transaction-store-SXIE57OD.cjs +0 -38
  364. package/dist/stream-object-HBFMIZLD.js +0 -7
  365. package/dist/stream-object-QSKHISDJ.cjs +0 -20
  366. package/dist/subagents-loader-CJFYQQU2.js +0 -7
  367. package/dist/subagents-loader-MOO7DC4E.cjs +0 -16
@@ -1,4 +1,4 @@
1
- import { ConfigurationError, isTransientError } from './chunk-ALUN2B4W.js';
1
+ import { ConfigurationError, isTransientError } from './chunk-B5MHRQJZ.js';
2
2
 
3
3
  // src/internal/retry/with-retry.ts
4
4
  function defaultSleep(ms, signal) {
@@ -73,5 +73,5 @@ var Retry = class _Retry {
73
73
  };
74
74
 
75
75
  export { Retry };
76
- //# sourceMappingURL=chunk-EFMFILPG.js.map
77
- //# sourceMappingURL=chunk-EFMFILPG.js.map
76
+ //# sourceMappingURL=chunk-7F7XE6CM.js.map
77
+ //# sourceMappingURL=chunk-7F7XE6CM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/retry/with-retry.ts","../src/retry.ts"],"names":[],"mappings":";;;AAkCA,SAAS,YAAA,CAAa,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC5C,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,MAAA,CAAO,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AACvF,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,MAAA,OAAA,EAAQ;AAAA,IACV,GAAG,EAAE,CAAA;AACL,IAAA,SAAS,OAAA,GAAgB;AACvB,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,CAAO,MAAA,EAAQ,kBAAkB,KAAA,GAAQ,MAAA,CAAO,SAAS,IAAI,KAAA,CAAM,oBAAoB,CAAC,CAAA;AAAA,IAC1F;AACA,IAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EAC3D,CAAC,CAAA;AACH;AAaA,SAAS,oBAAoB,OAAA,EAAuC;AAClE,EAAA,MAAM,OAAA,GAAU,SAAS,OAAA,IAAW,CAAA;AACpC,EAAA,IAAI,CAAC,MAAA,CAAO,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AG,IAAI,MAAM,CAAA;AACnD,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF;AACF;;;AClFO,IAAM,KAAA,GAAN,MAAM,MAAA,CAAM;AAAA,EACT,WAAA,GAAc;AAAA,EAAC;AAAA;AAAA,EAGvB,OAAO,GAAA,CAAO,EAAA,EAAsB,OAAA,EAAoC;AACtE,IAAA,OAAO,SAAA,CAAU,IAAI,OAAO,CAAA;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,MAAA,CAAU,EAAA,EAAsB,OAAA,EAAoC;AACzE,IAAA,OAAO,MAAA,CAAM,GAAA,CAAI,EAAA,EAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-EFMFILPG.js","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — replaces `withRetry` (ADR 0015 / ADR-P2).\n *\n * `Retry` is a static NAMESPACE, not a factory: the uniformity mandate spells every public entry\n * point `X.create(...)` so callers learn one verb, and twelve classes in this package follow it.\n *\n * This is the one place the mandate produced a false name, and it is fixed here rather than by\n * unwinding the mandate — consistency across a published API is worth more than the indirection.\n * `withRetry` is an EXECUTOR: it RUNS `fn` and resolves to `fn`'s result, so `create` named a\n * construction that never happens. `run` is the honest spelling and `create` is a deprecated alias,\n * because removing a published member is a major-version decision and the alias is what carries the\n * correction to a caller's editor in the meantime.\n *\n * @public\n */\nexport class Retry {\n private constructor() {}\n\n /** Run `fn`, retrying per `options`. Resolves to `fn`'s result. */\n static run<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n\n /**\n * @deprecated Renamed to {@link Retry.run}. This never created anything — it runs `fn` and\n * resolves to its result — and the name said otherwise. Still honoured; removed in the next major.\n */\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return Retry.run(fn, options);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/retry/with-retry.ts","../src/retry.ts"],"names":[],"mappings":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OAAA,EAAoC;AACzE,IAAA,OAAO,MAAA,CAAM,GAAA,CAAI,EAAA,EAAI,OAAO,CAAA;AAAA,EAC9B;AACF","file":"chunk-7F7XE6CM.js","sourcesContent":["/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — replaces `withRetry` (ADR 0015 / ADR-P2).\n *\n * `Retry` is a static NAMESPACE, not a factory: the uniformity mandate spells every public entry\n * point `X.create(...)` so callers learn one verb, and twelve classes in this package follow it.\n *\n * This is the one place the mandate produced a false name, and it is fixed here rather than by\n * unwinding the mandate — consistency across a published API is worth more than the indirection.\n * `withRetry` is an EXECUTOR: it RUNS `fn` and resolves to `fn`'s result, so `create` named a\n * construction that never happens. `run` is the honest spelling and `create` is a deprecated alias,\n * because removing a published member is a major-version decision and the alias is what carries the\n * correction to a caller's editor in the meantime.\n *\n * @public\n */\nexport class Retry {\n private constructor() {}\n\n /** Run `fn`, retrying per `options`. Resolves to `fn`'s result. */\n static run<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n\n /**\n * @deprecated Renamed to {@link Retry.run}. This never created anything — it runs `fn` and\n * resolves to its result — and the name said otherwise. Still honoured; removed in the next major.\n */\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return Retry.run(fn, options);\n }\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { theokitConfigRoot, projectConfigRoots } from './chunk-X7EUUHXU.js';
2
- import { ConfigurationError } from './chunk-ALUN2B4W.js';
2
+ import { ConfigurationError } from './chunk-B5MHRQJZ.js';
3
3
  import { diag, diagFailure } from './chunk-CZJ6Q7CW.js';
4
- import { AsyncLocalStorage } from 'async_hooks';
5
4
  import { existsSync } from 'fs';
6
5
  import { readFile } from 'fs/promises';
7
6
  import { join } from 'path';
@@ -175,21 +174,6 @@ function parseClaudeCodeCommand(raw, matcher, path, ccEvent) {
175
174
  return hc;
176
175
  }
177
176
 
178
- // src/internal/personality/context.ts
179
- var storage = new AsyncLocalStorage();
180
- function withPersonalityContext(ctx, fn) {
181
- return storage.run(ctx, fn);
182
- }
183
- function currentPersonalityContext() {
184
- return storage.getStore();
185
- }
186
- function warnPersonalitySwitchInsideFork(agentId) {
187
- warnOnce(
188
- `personality-switch-in-fork-${agentId}`,
189
- `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`
190
- );
191
- }
192
-
193
- export { currentPersonalityContext, loadHookConfig, warnFailureOnce, warnOnce, warnPersonalitySwitchInsideFork, withPersonalityContext };
194
- //# sourceMappingURL=chunk-N2KAIZ5D.js.map
195
- //# sourceMappingURL=chunk-N2KAIZ5D.js.map
177
+ export { loadHookConfig, warnFailureOnce, warnOnce };
178
+ //# sourceMappingURL=chunk-7GDHFV2M.js.map
179
+ //# sourceMappingURL=chunk-7GDHFV2M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts"],"names":[],"mappings":";;;;;;;AA8DO,IAAM,qBAAA,GAA6D;AAAA,EACxE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AA+BA,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;AAoBO,SAAS,eAAA,CAAgB,KAAa,OAAA,EAAuB;AAClE,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAA,WAAA,CAAY,GAAG,OAAO;AAAA,CAAI,CAAA;AAC5B;AAcA,eAAsB,cA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AAW;AAC1B,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,uDAAuD,IAAA,CAAK,SAAA,CAAU,IAAI,IAAI,CAAC,QAAQ,IAAI,CAAA,CAAA;AAAA,MAC3F,EAAE,MAAM,wBAAA;AAAyB,KACnC;AAAA,EACF;AACA,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,YAAY,GAAA,CAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,+CAAA,EAAkD,IAAI,CAAA,CAAA,EAAI;AAAA,MACrF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAGA,EAAA,sBAAA,CAAuB,GAAA,EAAK,MAAM,OAAO,CAAA;AACzC,EAAA,MAAM,KAAkB,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAS,aAAa,OAAA,EAAQ;AACrE,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","file":"chunk-7GDHFV2M.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 is Claude Code's `settings.json` hooks:\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * The shape, not the event COVERAGE. Four of the thirty-three documented events are fired by this\n * runtime — see {@link CLAUDE_CODE_EVENT_MAP} for which, why the rest are refused rather than\n * mapped, and the order in which they should be added. An event outside the set is reported to the\n * operator rather than skipped in silence.\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag, diagFailure } from \"../../diagnostics.js\";\nimport { projectConfigRoots, theokitConfigRoot } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * The Claude Code event names this runtime actually FIRES, and the internal event each becomes.\n *\n * Exported so the supported set is stated rather than implied. It used to be private, and the\n * docblock above claimed a shape \"identical to Claude Code's `settings.json` hooks\" while accepting\n * four of the thirty-three documented events — a claim nothing could contradict.\n *\n * A Claude Code event with no firing point here — `SessionStart`, `SubagentStop`, `PreCompact`,\n * `Notification`, `SessionEnd` among them — is skipped with a report rather than silently accepted,\n * because it would never run.\n *\n * ## Why this map is not simply grown\n *\n * Mapping a name the runtime does not fire is strictly WORSE than refusing it. An operator declaring\n * `PreCompact` today gets a report saying it will not fire; with the name mapped they would get\n * silence and a guard that never runs — a declared veto that does not exist. The map grows when the\n * seam exists, one event at a time.\n *\n * ## Priority, when it does grow\n *\n * The blocking events first. An unwired veto loses a CAPABILITY; an unwired observer loses a\n * SIGNAL. Thirteen of the sixteen the spec marks \"Can block? Yes\" are unwired, and\n * `tests/internal/runtime/hooks/the-supported-event-set-is-stated.test.ts` lists them in the order\n * they should be taken, so the next person does not re-derive which is which.\n *\n * `postRun` is reachable through this SDK's own config and has no entry here on purpose: it fires\n * per RUN, and no documented Claude Code event means that. `SessionEnd` is the near miss, and a\n * session is not a run.\n */\nexport const 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 * #637 — the event key as written in the config file (`PreToolUse`), carried so the approval\n * gate can report the vocabulary the consumer's stored fingerprint was taken against.\n *\n * REQUIRED, not optional: `parseClaudeCodeCommand` is the only producer of a `HookCommand` in\n * this package, so every command has one. An optional field would hand every reader a fallback\n * branch for a case that cannot occur — and if an in-memory producer is added later, required is\n * what forces it to supply a value instead of inheriting a silent `undefined`.\n */\n sourceEvent: string;\n /**\n * The config file this command was declared in.\n *\n * Carried so the executor can supply the runtime contract the declaring DIALECT presumes — a\n * command from `.claude/settings.json` is written against Claude Code's runtime and expects\n * `$CLAUDE_PROJECT_DIR` to exist (#522). Absent for a command built in memory, which is native by\n * construction.\n */\n sourcePath?: string;\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/**\n * A warn-once that is NOT dropped when the host installed no diagnostics sink.\n *\n * `diag` is silent by default and that is right for chatter — a library must not assume the host's\n * stderr is a free-form log, because in a TUI it is the render surface. A configuration the operator\n * WROTE and this runtime will not honour is not chatter. `diagFailure`'s own docblock records the\n * precedent, `theokit-sdk#189`: an MCP server failed to start, the only report went to `diag()`, the\n * embedding UI never read it, and \"the user saw an agent with missing tools and no reason given\".\n *\n * A dropped hook is that shape with a sharper edge, because the missing thing is a guard: the\n * operator declared a refusal, it silently does not exist, and nothing distinguishes that from a\n * refusal that ran and approved.\n *\n * The asymmetry that decides it is quoted from the same place: a corrupted frame is visible and\n * recoverable, while a silently dropped failure is neither.\n *\n * @internal\n */\nexport function warnFailureOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diagFailure(`${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(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<HookConfig> {\n const merged: HookConfig = {};\n let sawAny = false;\n for (const path of hookConfigCandidates(cwd, compatSources)) {\n if (!existsSync(path)) continue;\n sawAny = true;\n // Stamped at merge, where the file is still known. One line later the commands are pooled per\n // event and every trace of which dialect declared them is gone — which is how a Claude Code\n // command came to be run without Claude Code's runtime (#522).\n mergeInto(merged, stampSource(await readHookFile(path), path));\n }\n if (!sawAny && existsSync(join(theokitConfigRoot(cwd), \"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 merged;\n}\n\n/**\n * Every file that may declare hooks, in precedence order.\n *\n * `hooks.json` under each project config root, then the Claude Code CLI's own settings files — which\n * is where the CLI actually keeps hooks, so a repository set up for it presents its hooks here\n * without being converted. `settings.local.json` is the CLI's personal-override file and sits beside\n * the shared one rather than replacing it.\n *\n * The shape never needed translating: `parseClaudeCodeConfig` reads the `hooks` key off whatever\n * object it is given, and a settings file is that same object with other keys alongside.\n */\nfunction hookConfigCandidates(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): string[] {\n const roots = projectConfigRoots(cwd, compatSources, \"hooks\");\n return [\n ...roots.map((root) => join(root, \"hooks.json\")),\n ...roots.map((root) => join(root, \"settings.json\")),\n ...roots.map((root) => join(root, \"settings.local.json\")),\n ];\n}\n\n/**\n * Record which file each command came from.\n *\n * A command already carrying a `sourcePath` keeps it: nothing produces that today, and a nested\n * config that declared its own origin would be describing something this function cannot see.\n */\nfunction stampSource(config: HookConfig, sourcePath: string): HookConfig {\n if (config.hooks === undefined) return config;\n const hooks: NonNullable<HookConfig[\"hooks\"]> = {};\n for (const [event, commands] of Object.entries(config.hooks) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined) continue;\n hooks[event] = commands.map((c) => ({ sourcePath, ...c }));\n }\n return { hooks };\n}\n\n/**\n * Append one source's commands onto the accumulator, per event.\n *\n * MERGED, not first-wins, and the distinction is deliberate. An agent or a skill is a NAMED\n * declaration: two files claiming one name collide, and the explicit namespace should win. Hooks are\n * unnamed lists — two files declaring `PreToolUse` are two sets of commands an operator wrote, and\n * keeping only one drops the other in silence, which is the failure class this package guards\n * against everywhere else.\n */\nfunction mergeInto(target: HookConfig, source: HookConfig): void {\n for (const [event, commands] of Object.entries(source.hooks ?? {}) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined || commands.length === 0) continue;\n target.hooks ??= {};\n target.hooks[event] = [...(target.hooks[event] ?? []), ...commands];\n }\n}\n\nasync function readHookFile(jsonPath: string): Promise<HookConfig> {\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/**\n * Narrow an unknown to a record, or throw a typed config error.\n *\n * `hint` names the shape that WOULD be accepted, and exists because the message without it names\n * only the validator's expectation. Measured on a consumer in 2026-09: a flat `hooks` array in a\n * `.theokit/settings.json` made this throw on every turn, and `expected an object at \"hooks\"` gave\n * the operator nothing to act on — the file parses fine for the product that wrote it, and it is\n * this independent read of the same path that fails. An error on a refusal path should carry the\n * fix, not the diagnosis.\n */\nfunction asRecord(\n value: unknown,\n path: string,\n where: string,\n hint?: string,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(\n `hooks: expected an object at ${where} in ${path}${hint === undefined ? \"\" : ` — ${hint}`}`,\n { code: \"hooks_json_invalid\" },\n );\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * The shape this loader accepts, quoted back on the one refusal an operator is most likely to hit:\n * `hooks` keyed by event, each event an array of matcher groups.\n */\nconst HOOKS_SHAPE_HINT =\n 'hooks are keyed by event, e.g. { \"hooks\": { \"PreToolUse\": [ { \"hooks\": ' +\n '[ { \"type\": \"command\", \"command\": \"…\" } ] } ] } }';\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\"`, HOOKS_SHAPE_HINT);\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 // The operator wrote this event and it will not fire. Reported through the channel that\n // survives an absent sink — see `warnFailureOnce`.\n warnFailureOnce(\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/**\n * Fields a Claude Code hook entry may declare that this runtime does not implement.\n *\n * Listed rather than lumped into \"unknown\" because the two are different facts to the operator\n * reading the error: a typo is theirs to fix, and a field written for another runtime is a tree\n * that was never going to work here. The same split is made for subagent frontmatter, for the same\n * reason — an operator migrating a `.claude/` tree learned one key per round trip otherwise.\n *\n * `if` is the one that made refusal the right answer rather than a warning. Dropped, it fails OPEN:\n * a deny hook narrowed to one dangerous command shape silently becomes a deny hook over every call\n * of that tool. Every other field in this set loses a convenience; this one inverts the intent.\n */\nconst UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS = new Set([\n \"if\",\n \"args\",\n \"statusMessage\",\n \"once\",\n \"async\",\n \"asyncRewake\",\n \"shell\",\n]);\n\n/** What `parseClaudeCodeCommand` reads. Anything else is refused. */\nconst ACCEPTED_HOOK_FIELDS = new Set([\"type\", \"command\", \"timeout\"]);\n\n/**\n * Refuse a hook entry that declares a field this parser does not read.\n *\n * The parser used to take `type`, `command` and `timeout` and discard the rest in silence, while\n * `packages/agents` — reading the same file one layer up — already refused an unknown key loudly\n * through a `.strict()` schema. Two layers disagreeing about whether a field is an error is bad on\n * its own; the permissive one being the layer that actually runs the hook is the defect.\n */\nfunction rejectUnreadHookFields(cmd: Record<string, unknown>, path: string, ccEvent: string): void {\n for (const key of Object.keys(cmd)) {\n if (ACCEPTED_HOOK_FIELDS.has(key)) continue;\n const origin = UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS.has(key)\n ? ` — \"${key}\" is a Claude Code hook field that this runtime does not implement. The same ` +\n `applies to: ${[...UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS].filter((f) => f !== key).join(\", \")}`\n : \"\";\n throw new ConfigurationError(\n `hooks.${ccEvent}: unsupported field \"${key}\" (accepted: ${[...ACCEPTED_HOOK_FIELDS].join(\", \")}) in ${path}${origin}`,\n { code: \"hooks_unsupported_field\" },\n );\n }\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 // After the type/command checks, so a `{ type: \"http\", url }` entry still fails for its own\n // reason rather than for its `url`.\n rejectUnreadHookFields(cmd, path, ccEvent);\n const hc: HookCommand = { command: cmd.command, sourceEvent: ccEvent };\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"]}
@@ -1,6 +1,6 @@
1
- import { safePathJoin, assertNoSymlinkEscape } from './chunk-EH6XD3FY.js';
2
- import { readWorkspaceDir, parseSimpleYaml } from './chunk-UOLBAPDM.js';
3
- import { ConfigurationError } from './chunk-ALUN2B4W.js';
1
+ import { safePathJoin, assertNoSymlinkEscape } from './chunk-5DD4NJN3.js';
2
+ import { readWorkspaceDir, parseSimpleYaml } from './chunk-MQGSOKR3.js';
3
+ import { ConfigurationError } from './chunk-B5MHRQJZ.js';
4
4
  import { readFile } from 'fs/promises';
5
5
  import { join } from 'path';
6
6
 
@@ -166,5 +166,5 @@ ${lines.join("\n")}
166
166
  }
167
167
 
168
168
  export { buildSkillsBlock, discoverSkills, escapeBlockBody, loadSkillInstructions, stripSkillFrontmatter };
169
- //# sourceMappingURL=chunk-CA5VUAP3.js.map
170
- //# sourceMappingURL=chunk-CA5VUAP3.js.map
169
+ //# sourceMappingURL=chunk-7HUCU3KK.js.map
170
+ //# sourceMappingURL=chunk-7HUCU3KK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/skills/skill-frontmatter.ts","../src/internal/runtime/skills/discover-skills.ts","../src/internal/runtime/system-prompt/escape.ts","../src/internal/runtime/skills/skills-block.ts"],"names":[],"mappings":";;;;;;;AAMA,SAAS,SAAS,CAAA,EAAqD;AACrE,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;AAGA,SAAS,eAAe,GAAA,EAAiE;AACvF,EAAA,MAAM,MAAoB,EAAC;AAC3B,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG,GAAA,CAAI,CAAC,CAAA,GAAI,QAAA,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AAA;AAChC,EAAA,MAAM,QAAQ,MAAA,CAAO,GAAA;AAAA,IACnB,CAAC,KAAA,KAAU,CAAA,IAAA,EAAO,eAAA,CAAgB,KAAA,CAAM,IAAI,CAAC,CAAA,EAAA,EAAK,eAAA,CAAgB,KAAA,CAAM,WAAW,CAAC,CAAA;AAAA,GACtF;AACA,EAAA,OAAO,CAAA;AAAA,EAAa,KAAA,CAAM,IAAA,CAAK,IAAI,CAAC;AAAA,SAAA,CAAA;AACtC","file":"chunk-CA5VUAP3.js","sourcesContent":["import { ConfigurationError } from \"../../../errors.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\n\ntype StringFields = Record<string, string | undefined>;\n\n/** Narrow a FrontmatterValue to string; non-strings + undefined → undefined. */\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/** Coerce parser output to legacy string-only shape (skill schema is all-string). */\nfunction toStringFields(raw: Record<string, FrontmatterValue | undefined>): StringFields {\n const out: StringFields = {};\n for (const [k, v] of Object.entries(raw)) out[k] = asString(v);\n return out;\n}\n\n/**\n * Strict skill frontmatter schema (ADR D10).\n *\n * Required: `name`, `description`.\n * Optional: `category`, `dependencies` (comma-separated string in the\n * simple-YAML dialect — parsed to `string[]`).\n *\n * Unknown fields are ignored (forward-compat). Malformed YAML or missing\n * required fields surface as `ConfigurationError` with one of the typed\n * codes below.\n *\n * @internal\n */\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n category?: string;\n dependencies?: string[];\n /**\n * `disable-model-invocation: true` — the model is not told this skill exists.\n *\n * The SDK owns this boundary: a skill reaches the model through exactly one place,\n * `buildSystemPromptContext`, so the declaration is enforceable here. It is a DISCLOSURE rule,\n * not an execution rule — `skills.get(name)` still resolves it, because a caller naming a skill\n * has already made the decision the field exists to keep away from the model.\n */\n disableModelInvocation?: boolean;\n /**\n * `user-invocable: false` — carried, deliberately not enforced here.\n *\n * This SDK has no user-facing invocation surface for skills; there is no slash command. Reading\n * `agent.skills.list()` as \"the user\" would be a guess — a host may call it to build a picker or\n * to introspect, and the two want opposite answers. So the declaration travels to the host that\n * does know, instead of being discarded (the defect) or enforced against an invented boundary.\n */\n userInvocable?: boolean;\n}\n\n/**\n * Parse a SKILL.md file body into validated frontmatter.\n *\n * @throws ConfigurationError(code: \"missing_frontmatter\") — no `---` block at file head.\n * @throws ConfigurationError(code: \"schema_invalid\") — YAML malformed OR required field missing.\n *\n * @internal\n */\nexport function parseSkillFrontmatter(raw: string, fallbackName: string): SkillFrontmatter {\n const parsed = extractAndParseFrontmatter(raw, fallbackName);\n const fields = toStringFields(parsed);\n const name = resolveName(fields, fallbackName);\n ensureRequiredFields(fields, name);\n return buildFrontmatter(fields, parsed, name);\n}\n\n/**\n * SE20 — return a SKILL.md's BODY (everything after the frontmatter block), trimmed.\n * When there is no frontmatter block, the whole file is the body. Reuses the same\n * frontmatter regex as {@link parseSkillFrontmatter} (DRY).\n */\nexport function stripSkillFrontmatter(raw: string): string {\n const match = /^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n/.exec(raw);\n return (match === null ? raw : raw.slice(match[0].length)).trim();\n}\n\nfunction extractAndParseFrontmatter(\n raw: string,\n fallbackName: string,\n): Record<string, FrontmatterValue | undefined> {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Skill ${fallbackName} is missing frontmatter`, {\n code: \"missing_frontmatter\",\n });\n }\n const frontmatter = match[1] ?? \"\";\n // EC-5: guard against syntactically invalid frontmatter so the loader\n // surfaces schema_invalid rather than crashing.\n try {\n return parseSimpleYaml(frontmatter);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `Skill ${fallbackName} has malformed YAML frontmatter: ${detail}`,\n { code: \"schema_invalid\", cause },\n );\n }\n}\n\nfunction resolveName(fields: StringFields, fallbackName: string): string {\n if (hasContent(fields.name)) return fields.name;\n if (hasContent(fallbackName)) return fallbackName;\n throw new ConfigurationError(\"Skill at unknown path is missing required field: name\", {\n code: \"schema_invalid\",\n });\n}\n\nfunction ensureRequiredFields(fields: StringFields, name: string): void {\n if (!hasContent(fields.description)) {\n throw new ConfigurationError(`Skill ${name} is missing required field: description`, {\n code: \"schema_invalid\",\n });\n }\n}\n\nfunction buildFrontmatter(\n fields: StringFields,\n parsed: Record<string, FrontmatterValue | undefined>,\n name: string,\n): SkillFrontmatter {\n const description = fields.description;\n if (description === undefined) {\n // ensureRequiredFields already threw; this is unreachable but satisfies TS\n throw new ConfigurationError(`Skill ${name} missing description`, { code: \"schema_invalid\" });\n }\n const result: SkillFrontmatter = { name, description };\n if (hasContent(fields.category)) result.category = fields.category;\n const deps = parseDependencies(fields.dependencies);\n if (deps !== undefined) result.dependencies = deps;\n const disable = readAuthorizationFlag(parsed, \"disable-model-invocation\", name);\n if (disable !== undefined) result.disableModelInvocation = disable;\n const invocable = readAuthorizationFlag(parsed, \"user-invocable\", name);\n if (invocable !== undefined) result.userInvocable = invocable;\n return result;\n}\n\n/**\n * Read one boolean authorization flag, refusing a value this parser cannot represent.\n *\n * Unknown frontmatter keys are ignored here for forward compatibility, and that is right for\n * metadata. It is wrong for these two: the simple-YAML dialect coerces only the literals `true`\n * and `false`, so `disable-model-invocation: yes` — a valid YAML boolean — arrives as the STRING\n * `\"yes\"`, compares unequal to `true`, and the skill is disclosed to the model. The author wrote a\n * restriction and got the default.\n *\n * A restriction that fails open is worse than one that is absent, because the author stops looking.\n * So the value is refused and named, and the run stops on the line that caused it.\n */\nfunction readAuthorizationFlag(\n parsed: Record<string, FrontmatterValue | undefined>,\n key: string,\n name: string,\n): boolean | undefined {\n const value = parsed[key];\n if (value === undefined) return undefined;\n if (typeof value === \"boolean\") return value;\n throw new ConfigurationError(\n `Skill ${name}: \"${key}\" must be true or false (got ${JSON.stringify(value)}) — ` +\n `this dialect reads only the literals \\`true\\` and \\`false\\`, and a value it cannot read ` +\n `would leave the skill disclosed`,\n { code: \"schema_invalid\" },\n );\n}\n\nfunction parseDependencies(raw: string | undefined): string[] | undefined {\n if (!hasContent(raw)) return undefined;\n const deps = (raw as string)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return deps.length > 0 ? deps : undefined;\n}\n\nfunction hasContent(value: string | undefined): value is string {\n return value !== undefined && value.trim().length > 0;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { assertNoSymlinkEscape, safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { parseSkillFrontmatter, stripSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * A discovered skill's metadata. The skill BODY is never included — only the\n * strict frontmatter fields plus the resolved `source` path.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport interface Skill {\n name: string;\n description: string;\n /** Absolute path to the discovered `SKILL.md`. */\n source: string;\n category?: string;\n dependencies?: string[];\n /** `disable-model-invocation: true` — the model is never told this skill exists. */\n disableModelInvocation?: boolean;\n /** `user-invocable: false` — carried for a host that has a picker; this SDK has no such surface. */\n userInvocable?: boolean;\n}\n\n/**\n * Information passed to `onInvalidSkill` when a `SKILL.md` is present but its\n * frontmatter is malformed (missing required field or invalid YAML).\n *\n * @public\n */\nexport interface InvalidSkillInfo {\n /** The skill directory name (used as the fallback skill name). */\n name: string;\n /** Absolute path to the offending `SKILL.md`. */\n source: string;\n /** Typed reason: `missing_frontmatter` or `schema_invalid`. */\n code: string;\n message: string;\n}\n\n/**\n * Options for {@link discoverSkills}.\n *\n * @public\n */\nexport interface DiscoverSkillsOptions {\n /**\n * Called once per directory that contains a `SKILL.md` with malformed\n * frontmatter. The skill is excluded from the result; discovery continues\n * (strict-frontmatter ADR / EC-5). A directory WITHOUT a `SKILL.md` is NOT a\n * malformed skill and does not trigger this callback.\n *\n * Default: no-op (a library primitive must not write to the consumer's\n * stderr by default).\n */\n onInvalidSkill?: (info: InvalidSkillInfo) => void;\n}\n\n/**\n * Discover `SKILL.md` skills under an arbitrary directory.\n *\n * For each immediate subdirectory `<dir>/<name>/` containing a `SKILL.md`, the\n * file's strict YAML frontmatter is parsed (`name`/`description` required;\n * `category`/`dependencies` optional). Malformed skills are skipped (optionally\n * reported via {@link DiscoverSkillsOptions.onInvalidSkill}); a subdirectory\n * whose realpath escapes `dir` (via symlink) is skipped (symlink-escape guard,\n * reusing `@theokit/sdk/path-safety`).\n *\n * NEVER throws: a missing, unreadable, or non-directory `dir` yields `[]`.\n *\n * Discovery order follows the filesystem `readdir` order (OS-dependent). Sort\n * the result before {@link buildSkillsBlock} if a stable block order matters.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport async function discoverSkills(\n dir: string,\n options?: DiscoverSkillsOptions,\n): Promise<Skill[]> {\n let entries: Awaited<ReturnType<typeof readWorkspaceDir>>;\n try {\n entries = await readWorkspaceDir(dir, \"skills_read_error\", \"skills directory\");\n } catch {\n // never-throw contract: unreadable / not-a-directory → no skills (EC-1)\n return [];\n }\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n let skillDir: string;\n try {\n skillDir = safePathJoin(dir, entry.name);\n assertNoSymlinkEscape(skillDir, dir);\n } catch {\n continue;\n }\n const skillPath = join(skillDir, \"SKILL.md\");\n let raw: string;\n try {\n raw = await readFile(skillPath, \"utf8\");\n } catch {\n // no SKILL.md in this subdir → not a skill, not an error (EC-2)\n continue;\n }\n const skill = tryParseSkill(raw, entry.name, skillPath, options);\n if (skill !== undefined) skills.push(skill);\n }\n return skills;\n}\n\nfunction tryParseSkill(\n raw: string,\n fallbackName: string,\n source: string,\n options: DiscoverSkillsOptions | undefined,\n): Skill | undefined {\n try {\n const frontmatter = parseSkillFrontmatter(raw, fallbackName);\n const skill: Skill = {\n name: frontmatter.name,\n description: frontmatter.description,\n source,\n };\n if (frontmatter.category !== undefined) skill.category = frontmatter.category;\n if (frontmatter.dependencies !== undefined) skill.dependencies = frontmatter.dependencies;\n // The authorization flags travel with the record. Dropping them here would reproduce the defect\n // one layer down: the parser would read the declaration and the discovery result would not\n // carry it, which is indistinguishable from never having parsed it.\n if (frontmatter.disableModelInvocation !== undefined) {\n skill.disableModelInvocation = frontmatter.disableModelInvocation;\n }\n if (frontmatter.userInvocable !== undefined) skill.userInvocable = frontmatter.userInvocable;\n return skill;\n } catch (cause) {\n if (cause instanceof ConfigurationError) {\n options?.onInvalidSkill?.({\n name: fallbackName,\n source,\n code: cause.code ?? \"unknown\",\n message: cause.message,\n });\n return undefined;\n }\n throw cause;\n }\n}\n\n/**\n * Read the BODY of a discovered skill — everything after its frontmatter.\n *\n * A thin selector over {@link discoverSkills} rather than a second reader, which is the same\n * relationship `loadSubagentDefinition` has to `discoverSubagents` in the sibling domain: one\n * parser is the point.\n *\n * ## Why this exists rather than a field on `Skill`\n *\n * `Skill` documents that *\"the skill BODY is never included\"*. That is a written contract with no\n * written reason, and widening it on a guess about the reason is not a trade worth making — a\n * catalog you can put in a prompt without carrying every body is the likely intent, and this keeps\n * that shape intact for whoever relied on it.\n *\n * The body was never expensive to obtain: `discoverSkills` already reads each file in full and\n * discards everything but the frontmatter. What was missing was a door that hands it over.\n *\n * ## What it is for\n *\n * Turning a discovered skill into an inline one — `SkillsSettings.inline` requires `instructions`,\n * and without this the only route was to open `source` and split the frontmatter by hand. That is a\n * second implementation of this module's own convention, and it would fail SILENTLY if the format\n * moved: the frontmatter would land inside the instructions and nothing would say so.\n *\n * Reported by the `theocode` session, which needed exactly that to give an operator's\n * `~/.theokit/skills/` to an agent through the SDK's own parser.\n *\n * @param skill - a record returned by {@link discoverSkills}; its `source` is read.\n * @returns the trimmed body. A file that is all frontmatter yields an empty string.\n * @throws if `source` is unreadable — unlike discovery, which skips what it cannot read, a caller\n * naming ONE skill has asked about that skill and an empty string would answer a question it did\n * not ask.\n * @public\n */\nexport async function loadSkillInstructions(skill: Skill): Promise<string> {\n return stripSkillFrontmatter(await readFile(skill.source, \"utf8\"));\n}\n","/**\n * Block-body XML escape (ADR D9 — prompt-injection defence).\n *\n * Order matters: `&` MUST be escaped first so subsequent `<`/`>` replacements\n * do not double-encode the `&` characters they introduce.\n *\n * @internal\n */\nexport const escapeBlockBody = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n","import { escapeBlockBody } from \"../system-prompt/escape.js\";\n\n/**\n * Render the `<skills>` system-prompt block from a skill list.\n *\n * Input is the structural subset `{ name, description }` — the skill BODY is\n * NOT in the type, so it cannot leak into the prompt. Both fields are passed\n * through `escapeBlockBody` to neutralise prompt-injection vectors hidden in\n * user-controlled SKILL.md frontmatter (injection-escape ADR).\n *\n * Returns `undefined` for an empty list so the caller can omit the block.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport function buildSkillsBlock(\n skills: ReadonlyArray<{ name: string; description: string }>,\n): string | undefined {\n if (skills.length === 0) return undefined;\n const lines = skills.map(\n (skill) => ` - ${escapeBlockBody(skill.name)}: ${escapeBlockBody(skill.description)}`,\n );\n return `<skills>\\n${lines.join(\"\\n\")}\\n</skills>`;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/skills/skill-frontmatter.ts","../src/internal/runtime/skills/discover-skills.ts","../src/internal/runtime/system-prompt/escape.ts","../src/internal/runtime/skills/skills-block.ts"],"names":[],"mappings":";;;;;;;AAMA,SAAS,SAAS,CAAA,EAAqD;AACrE,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;AAGA,SAAS,eAAe,GAAA,EAAiE;AACvF,EAAA,MAAM,MAAoB,EAAC;AAC3B,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG,GAAA,CAAI,CAAC,CAAA,GAAI,QAAA,CAAS,CAAC,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AAA,MAAM,QAAQ,MAAA,CAAO,GAAA;AAAA,IACnB,CAAC,KAAA,KAAU,CAAA,IAAA,EAAO,eAAA,CAAgB,KAAA,CAAM,IAAI,CAAC,CAAA,EAAA,EAAK,eAAA,CAAgB,KAAA,CAAM,WAAW,CAAC,CAAA;AAAA,GACtF;AACA,EAAA,OAAO,CAAA;AAAA,EAAa,KAAA,CAAM,IAAA,CAAK,IAAI,CAAC;AAAA,SAAA,CAAA;AACtC","file":"chunk-7HUCU3KK.js","sourcesContent":["import { ConfigurationError } from \"../../../errors.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\n\ntype StringFields = Record<string, string | undefined>;\n\n/** Narrow a FrontmatterValue to string; non-strings + undefined → undefined. */\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/** Coerce parser output to legacy string-only shape (skill schema is all-string). */\nfunction toStringFields(raw: Record<string, FrontmatterValue | undefined>): StringFields {\n const out: StringFields = {};\n for (const [k, v] of Object.entries(raw)) out[k] = asString(v);\n return out;\n}\n\n/**\n * Strict skill frontmatter schema (ADR D10).\n *\n * Required: `name`, `description`.\n * Optional: `category`, `dependencies` (comma-separated string in the\n * simple-YAML dialect — parsed to `string[]`).\n *\n * Unknown fields are ignored (forward-compat). Malformed YAML or missing\n * required fields surface as `ConfigurationError` with one of the typed\n * codes below.\n *\n * @internal\n */\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n category?: string;\n dependencies?: string[];\n /**\n * `disable-model-invocation: true` — the model is not told this skill exists.\n *\n * The SDK owns this boundary: a skill reaches the model through exactly one place,\n * `buildSystemPromptContext`, so the declaration is enforceable here. It is a DISCLOSURE rule,\n * not an execution rule — `skills.get(name)` still resolves it, because a caller naming a skill\n * has already made the decision the field exists to keep away from the model.\n */\n disableModelInvocation?: boolean;\n /**\n * `user-invocable: false` — carried, deliberately not enforced here.\n *\n * This SDK has no user-facing invocation surface for skills; there is no slash command. Reading\n * `agent.skills.list()` as \"the user\" would be a guess — a host may call it to build a picker or\n * to introspect, and the two want opposite answers. So the declaration travels to the host that\n * does know, instead of being discarded (the defect) or enforced against an invented boundary.\n */\n userInvocable?: boolean;\n}\n\n/**\n * Parse a SKILL.md file body into validated frontmatter.\n *\n * @throws ConfigurationError(code: \"missing_frontmatter\") — no `---` block at file head.\n * @throws ConfigurationError(code: \"schema_invalid\") — YAML malformed OR required field missing.\n *\n * @internal\n */\nexport function parseSkillFrontmatter(raw: string, fallbackName: string): SkillFrontmatter {\n const parsed = extractAndParseFrontmatter(raw, fallbackName);\n const fields = toStringFields(parsed);\n const name = resolveName(fields, fallbackName);\n ensureRequiredFields(fields, name);\n return buildFrontmatter(fields, parsed, name);\n}\n\n/**\n * SE20 — return a SKILL.md's BODY (everything after the frontmatter block), trimmed.\n * When there is no frontmatter block, the whole file is the body. Reuses the same\n * frontmatter regex as {@link parseSkillFrontmatter} (DRY).\n */\nexport function stripSkillFrontmatter(raw: string): string {\n const match = /^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n/.exec(raw);\n return (match === null ? raw : raw.slice(match[0].length)).trim();\n}\n\nfunction extractAndParseFrontmatter(\n raw: string,\n fallbackName: string,\n): Record<string, FrontmatterValue | undefined> {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Skill ${fallbackName} is missing frontmatter`, {\n code: \"missing_frontmatter\",\n });\n }\n const frontmatter = match[1] ?? \"\";\n // EC-5: guard against syntactically invalid frontmatter so the loader\n // surfaces schema_invalid rather than crashing.\n try {\n return parseSimpleYaml(frontmatter);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `Skill ${fallbackName} has malformed YAML frontmatter: ${detail}`,\n { code: \"schema_invalid\", cause },\n );\n }\n}\n\nfunction resolveName(fields: StringFields, fallbackName: string): string {\n if (hasContent(fields.name)) return fields.name;\n if (hasContent(fallbackName)) return fallbackName;\n throw new ConfigurationError(\"Skill at unknown path is missing required field: name\", {\n code: \"schema_invalid\",\n });\n}\n\nfunction ensureRequiredFields(fields: StringFields, name: string): void {\n if (!hasContent(fields.description)) {\n throw new ConfigurationError(`Skill ${name} is missing required field: description`, {\n code: \"schema_invalid\",\n });\n }\n}\n\nfunction buildFrontmatter(\n fields: StringFields,\n parsed: Record<string, FrontmatterValue | undefined>,\n name: string,\n): SkillFrontmatter {\n const description = fields.description;\n if (description === undefined) {\n // ensureRequiredFields already threw; this is unreachable but satisfies TS\n throw new ConfigurationError(`Skill ${name} missing description`, { code: \"schema_invalid\" });\n }\n const result: SkillFrontmatter = { name, description };\n if (hasContent(fields.category)) result.category = fields.category;\n const deps = parseDependencies(fields.dependencies);\n if (deps !== undefined) result.dependencies = deps;\n const disable = readAuthorizationFlag(parsed, \"disable-model-invocation\", name);\n if (disable !== undefined) result.disableModelInvocation = disable;\n const invocable = readAuthorizationFlag(parsed, \"user-invocable\", name);\n if (invocable !== undefined) result.userInvocable = invocable;\n return result;\n}\n\n/**\n * Read one boolean authorization flag, refusing a value this parser cannot represent.\n *\n * Unknown frontmatter keys are ignored here for forward compatibility, and that is right for\n * metadata. It is wrong for these two: the simple-YAML dialect coerces only the literals `true`\n * and `false`, so `disable-model-invocation: yes` — a valid YAML boolean — arrives as the STRING\n * `\"yes\"`, compares unequal to `true`, and the skill is disclosed to the model. The author wrote a\n * restriction and got the default.\n *\n * A restriction that fails open is worse than one that is absent, because the author stops looking.\n * So the value is refused and named, and the run stops on the line that caused it.\n */\nfunction readAuthorizationFlag(\n parsed: Record<string, FrontmatterValue | undefined>,\n key: string,\n name: string,\n): boolean | undefined {\n const value = parsed[key];\n if (value === undefined) return undefined;\n if (typeof value === \"boolean\") return value;\n throw new ConfigurationError(\n `Skill ${name}: \"${key}\" must be true or false (got ${JSON.stringify(value)}) — ` +\n `this dialect reads only the literals \\`true\\` and \\`false\\`, and a value it cannot read ` +\n `would leave the skill disclosed`,\n { code: \"schema_invalid\" },\n );\n}\n\nfunction parseDependencies(raw: string | undefined): string[] | undefined {\n if (!hasContent(raw)) return undefined;\n const deps = (raw as string)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return deps.length > 0 ? deps : undefined;\n}\n\nfunction hasContent(value: string | undefined): value is string {\n return value !== undefined && value.trim().length > 0;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { assertNoSymlinkEscape, safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { parseSkillFrontmatter, stripSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * A discovered skill's metadata. The skill BODY is never included — only the\n * strict frontmatter fields plus the resolved `source` path.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport interface Skill {\n name: string;\n description: string;\n /** Absolute path to the discovered `SKILL.md`. */\n source: string;\n category?: string;\n dependencies?: string[];\n /** `disable-model-invocation: true` — the model is never told this skill exists. */\n disableModelInvocation?: boolean;\n /** `user-invocable: false` — carried for a host that has a picker; this SDK has no such surface. */\n userInvocable?: boolean;\n}\n\n/**\n * Information passed to `onInvalidSkill` when a `SKILL.md` is present but its\n * frontmatter is malformed (missing required field or invalid YAML).\n *\n * @public\n */\nexport interface InvalidSkillInfo {\n /** The skill directory name (used as the fallback skill name). */\n name: string;\n /** Absolute path to the offending `SKILL.md`. */\n source: string;\n /** Typed reason: `missing_frontmatter` or `schema_invalid`. */\n code: string;\n message: string;\n}\n\n/**\n * Options for {@link discoverSkills}.\n *\n * @public\n */\nexport interface DiscoverSkillsOptions {\n /**\n * Called once per directory that contains a `SKILL.md` with malformed\n * frontmatter. The skill is excluded from the result; discovery continues\n * (strict-frontmatter ADR / EC-5). A directory WITHOUT a `SKILL.md` is NOT a\n * malformed skill and does not trigger this callback.\n *\n * Default: no-op (a library primitive must not write to the consumer's\n * stderr by default).\n */\n onInvalidSkill?: (info: InvalidSkillInfo) => void;\n}\n\n/**\n * Discover `SKILL.md` skills under an arbitrary directory.\n *\n * For each immediate subdirectory `<dir>/<name>/` containing a `SKILL.md`, the\n * file's strict YAML frontmatter is parsed (`name`/`description` required;\n * `category`/`dependencies` optional). Malformed skills are skipped (optionally\n * reported via {@link DiscoverSkillsOptions.onInvalidSkill}); a subdirectory\n * whose realpath escapes `dir` (via symlink) is skipped (symlink-escape guard,\n * reusing `@theokit/sdk/path-safety`).\n *\n * NEVER throws: a missing, unreadable, or non-directory `dir` yields `[]`.\n *\n * Discovery order follows the filesystem `readdir` order (OS-dependent). Sort\n * the result before {@link buildSkillsBlock} if a stable block order matters.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport async function discoverSkills(\n dir: string,\n options?: DiscoverSkillsOptions,\n): Promise<Skill[]> {\n let entries: Awaited<ReturnType<typeof readWorkspaceDir>>;\n try {\n entries = await readWorkspaceDir(dir, \"skills_read_error\", \"skills directory\");\n } catch {\n // never-throw contract: unreadable / not-a-directory → no skills (EC-1)\n return [];\n }\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n let skillDir: string;\n try {\n skillDir = safePathJoin(dir, entry.name);\n assertNoSymlinkEscape(skillDir, dir);\n } catch {\n continue;\n }\n const skillPath = join(skillDir, \"SKILL.md\");\n let raw: string;\n try {\n raw = await readFile(skillPath, \"utf8\");\n } catch {\n // no SKILL.md in this subdir → not a skill, not an error (EC-2)\n continue;\n }\n const skill = tryParseSkill(raw, entry.name, skillPath, options);\n if (skill !== undefined) skills.push(skill);\n }\n return skills;\n}\n\nfunction tryParseSkill(\n raw: string,\n fallbackName: string,\n source: string,\n options: DiscoverSkillsOptions | undefined,\n): Skill | undefined {\n try {\n const frontmatter = parseSkillFrontmatter(raw, fallbackName);\n const skill: Skill = {\n name: frontmatter.name,\n description: frontmatter.description,\n source,\n };\n if (frontmatter.category !== undefined) skill.category = frontmatter.category;\n if (frontmatter.dependencies !== undefined) skill.dependencies = frontmatter.dependencies;\n // The authorization flags travel with the record. Dropping them here would reproduce the defect\n // one layer down: the parser would read the declaration and the discovery result would not\n // carry it, which is indistinguishable from never having parsed it.\n if (frontmatter.disableModelInvocation !== undefined) {\n skill.disableModelInvocation = frontmatter.disableModelInvocation;\n }\n if (frontmatter.userInvocable !== undefined) skill.userInvocable = frontmatter.userInvocable;\n return skill;\n } catch (cause) {\n if (cause instanceof ConfigurationError) {\n options?.onInvalidSkill?.({\n name: fallbackName,\n source,\n code: cause.code ?? \"unknown\",\n message: cause.message,\n });\n return undefined;\n }\n throw cause;\n }\n}\n\n/**\n * Read the BODY of a discovered skill — everything after its frontmatter.\n *\n * A thin selector over {@link discoverSkills} rather than a second reader, which is the same\n * relationship `loadSubagentDefinition` has to `discoverSubagents` in the sibling domain: one\n * parser is the point.\n *\n * ## Why this exists rather than a field on `Skill`\n *\n * `Skill` documents that *\"the skill BODY is never included\"*. That is a written contract with no\n * written reason, and widening it on a guess about the reason is not a trade worth making — a\n * catalog you can put in a prompt without carrying every body is the likely intent, and this keeps\n * that shape intact for whoever relied on it.\n *\n * The body was never expensive to obtain: `discoverSkills` already reads each file in full and\n * discards everything but the frontmatter. What was missing was a door that hands it over.\n *\n * ## What it is for\n *\n * Turning a discovered skill into an inline one — `SkillsSettings.inline` requires `instructions`,\n * and without this the only route was to open `source` and split the frontmatter by hand. That is a\n * second implementation of this module's own convention, and it would fail SILENTLY if the format\n * moved: the frontmatter would land inside the instructions and nothing would say so.\n *\n * Reported by the `theocode` session, which needed exactly that to give an operator's\n * `~/.theokit/skills/` to an agent through the SDK's own parser.\n *\n * @param skill - a record returned by {@link discoverSkills}; its `source` is read.\n * @returns the trimmed body. A file that is all frontmatter yields an empty string.\n * @throws if `source` is unreadable — unlike discovery, which skips what it cannot read, a caller\n * naming ONE skill has asked about that skill and an empty string would answer a question it did\n * not ask.\n * @public\n */\nexport async function loadSkillInstructions(skill: Skill): Promise<string> {\n return stripSkillFrontmatter(await readFile(skill.source, \"utf8\"));\n}\n","/**\n * Block-body XML escape (ADR D9 — prompt-injection defence).\n *\n * Order matters: `&` MUST be escaped first so subsequent `<`/`>` replacements\n * do not double-encode the `&` characters they introduce.\n *\n * @internal\n */\nexport const escapeBlockBody = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n","import { escapeBlockBody } from \"../system-prompt/escape.js\";\n\n/**\n * Render the `<skills>` system-prompt block from a skill list.\n *\n * Input is the structural subset `{ name, description }` — the skill BODY is\n * NOT in the type, so it cannot leak into the prompt. Both fields are passed\n * through `escapeBlockBody` to neutralise prompt-injection vectors hidden in\n * user-controlled SKILL.md frontmatter (injection-escape ADR).\n *\n * Returns `undefined` for an empty list so the caller can omit the block.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport function buildSkillsBlock(\n skills: ReadonlyArray<{ name: string; description: string }>,\n): string | undefined {\n if (skills.length === 0) return undefined;\n const lines = skills.map(\n (skill) => ` - ${escapeBlockBody(skill.name)}: ${escapeBlockBody(skill.description)}`,\n );\n return `<skills>\\n${lines.join(\"\\n\")}\\n</skills>`;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { createSemaphore } from './chunk-G7BLGBRN.js';
1
+ import { createSemaphore } from './chunk-ZWFTECOE.js';
2
2
 
3
3
  // src/internal/concurrency/map-with-concurrency.ts
4
4
  var NEVER_ABORT = new AbortController().signal;
@@ -21,5 +21,5 @@ async function mapWithConcurrency(items, concurrency, fn, options) {
21
21
  }
22
22
 
23
23
  export { mapWithConcurrency };
24
- //# sourceMappingURL=chunk-4MMWFSCD.js.map
25
- //# sourceMappingURL=chunk-4MMWFSCD.js.map
24
+ //# sourceMappingURL=chunk-7JAKO3NM.js.map
25
+ //# sourceMappingURL=chunk-7JAKO3NM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-4MMWFSCD.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-7JAKO3NM.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var chunk2ZPEDVLM_cjs = require('./chunk-2ZPEDVLM.cjs');
4
- var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
4
+ var chunkUNFBHV46_cjs = require('./chunk-UNFBHV46.cjs');
5
5
  var child_process = require('child_process');
6
6
  var promises = require('fs/promises');
7
7
  var path = require('path');
@@ -12,14 +12,14 @@ function shellEscapePosix(arg) {
12
12
  }
13
13
 
14
14
  // src/sandbox/types.ts
15
- var SandboxSecurityError = class extends chunkJ7J7J2GN_cjs.TheokitAgentError {
15
+ var SandboxSecurityError = class extends chunkUNFBHV46_cjs.TheokitAgentError {
16
16
  name = "SandboxSecurityError";
17
17
  code = "sandbox_security";
18
18
  constructor(message) {
19
19
  super(message, { code: "sandbox_security", isRetryable: false });
20
20
  }
21
21
  };
22
- var SandboxNotAvailableError = class extends chunkJ7J7J2GN_cjs.TheokitAgentError {
22
+ var SandboxNotAvailableError = class extends chunkUNFBHV46_cjs.TheokitAgentError {
23
23
  name = "SandboxNotAvailableError";
24
24
  code = "sandbox_not_available";
25
25
  constructor(message) {
@@ -82,7 +82,7 @@ var SandboxBackend = class {
82
82
  */
83
83
  assertCommandRan(operation, result) {
84
84
  if (result.exitCode === 0) return;
85
- throw new chunkJ7J7J2GN_cjs.ConfigurationError(
85
+ throw new chunkUNFBHV46_cjs.ConfigurationError(
86
86
  `${operation} failed (exit ${String(result.exitCode)}): ${result.stderr.trim() || "no stderr"}. The derived helpers shell out to POSIX \`cat\`/\`find\`/\`grep\`/\`ls\` \u2014 a backend whose execute() is not a POSIX shell must override them.`,
87
87
  { code: "sandbox_derived_helper_failed" }
88
88
  );
@@ -168,5 +168,5 @@ exports.SandboxNotAvailableError = SandboxNotAvailableError;
168
168
  exports.SandboxSecurityError = SandboxSecurityError;
169
169
  exports.resolveSandbox = resolveSandbox;
170
170
  exports.shellEscapePosix = shellEscapePosix;
171
- //# sourceMappingURL=chunk-UADQJBHR.cjs.map
172
- //# sourceMappingURL=chunk-UADQJBHR.cjs.map
171
+ //# sourceMappingURL=chunk-7NQ7HJ3E.cjs.map
172
+ //# sourceMappingURL=chunk-7NQ7HJ3E.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sandbox/shell-escape.ts","../src/sandbox/types.ts","../src/sandbox/local-sandbox.ts"],"names":["TheokitAgentError","ConfigurationError","execFile","resolveChildEnv","path","mkdir","dirname","fsWriteFile"],"mappings":";;;;;;;;;AASO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;;;AC2DO,IAAM,oBAAA,GAAN,cAAmCA,mCAAA,CAAkB;AAAA,EACxC,IAAA,GAAO,sBAAA;AAAA,EACP,IAAA,GAAO,kBAAA;AAAA,EACzB,YAAY,OAAA,EAAiB;AAE3B,IAAA,KAAA,CAAM,SAAS,EAAE,IAAA,EAAM,kBAAA,EAAoB,WAAA,EAAa,OAAO,CAAA;AAAA,EACjE;AACF;AAYO,IAAM,wBAAA,GAAN,cAAuCA,mCAAA,CAAkB;AAAA,EAC5C,IAAA,GAAO,0BAAA;AAAA,EACP,IAAA,GAAO,uBAAA;AAAA,EACzB,YAAY,OAAA,EAAiB;AAE3B,IAAA,KAAA,CAAM,SAAS,EAAE,IAAA,EAAM,uBAAA,EAAyB,WAAA,EAAa,OAAO,CAAA;AAAA,EACtE;AACF;AAoBO,IAAe,iBAAf,MAA8B;AAAA,EACzB,MAAA;AAAA,EAEV,WAAA,CAAY,MAAA,GAAwB,EAAC,EAAG;AACtC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,OAAA,EAAS,OAAO,OAAA,IAAW,MAAA;AAAA,MAC3B,SAAA,EAAW,OAAO,SAAA,IAAa,GAAA;AAAA,MAC/B,cAAA,EAAgB,MAAA,CAAO,cAAA,IAAkB,CAAA,GAAI,IAAA,GAAO,IAAA;AAAA;AAAA,MAEpD,GAAA,EAAK,OAAO,GAAA,IAAO;AAAA,KACrB;AAAA,EACF;AAAA,EAMA,MAAM,SAAS,I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1E;AAAA,EAEA,MAAM,UAAA,CAAWC,MAAA,EAAc,OAAA,EAAyC;AACtE,IAAA,MAAM,QAAA,GAAWA,MAAA,CAAK,UAAA,CAAW,GAAG,CAAA,GAAIA,MAAA,GAAO,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA,CAAA,EAAIA,MAAI,CAAA,CAAA;AAC7E,IAAA,MAAMC,eAAMC,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,IAAA,MAAMC,kBAAA,CAAY,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AAAA,EAC9C;AACF","file":"chunk-UADQJBHR.cjs","sourcesContent":["/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport { ConfigurationError, TheokitAgentError } from \"../errors.js\";\nimport type { EnvPolicy } from \"../types/env-policy.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\n/**\n * What a {@link SandboxBackend} returns for one command.\n *\n * `exitCode` is a coarse signal rather than the child's real exit status: the backends in this\n * package report `0` on success, `124` on timeout, and `1` for everything else — including a command\n * that exited with its own non-zero code. Read `timedOut` to tell a killed command from a failed one,\n * and `stderr` for the reason; branching on a specific exit code will not work here.\n *\n * `stdout` and `stderr` are truncated independently at `SandboxConfig.maxOutputBytes`, with a\n * trailing `...(truncated)` marker. Neither is safe to parse as a complete document without checking\n * for it.\n */\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\n/**\n * Construction-time settings shared by every {@link SandboxBackend}. All fields are optional and the\n * base constructor fills them in, so `{}` is a valid config: `workDir` `/tmp`, `timeoutMs` 30000,\n * `maxOutputBytes` 5 MiB, `env` `\"inherit-scrubbed\"`.\n *\n * `workDir` is the child process's cwd and the base a relative `uploadFile` path resolves against. It\n * is not a boundary — under `LocalSandbox` nothing stops a command, or an absolute path, from leaving\n * it. Only `LinuxSandbox` makes it enforceable.\n *\n * `timeoutMs` is the default for every call; `execute(command, { timeoutMs })` overrides it per\n * command. On expiry the child is killed and the result carries `timedOut: true` with `exitCode`\n * 124 — the partial output collected so far is still returned.\n */\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n /**\n * #54 — env inherit/scrub policy for the executed command's child process.\n * Defaults to `\"inherit-scrubbed\"` (drop secret-like vars: `*KEY*`, `*SECRET*`,\n * `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Pass `\"all\"` to restore full inheritance\n * or `\"core\"` for a minimal safe allowlist.\n */\n env?: EnvPolicy;\n}\n\n/**\n * A backend refused a command on policy grounds — the environment works, and it said no. Carries a\n * stable `code: \"sandbox_security\"` for callers that prefer not to match on the class.\n *\n * Nothing in this package throws it, which is worth knowing before you write a `catch` for it:\n * `LocalSandbox` and `LinuxSandbox` report a refusal through {@link ExecuteResult} (non-zero\n * `exitCode`, reason on `stderr`), and a write blocked under confinement surfaces as a plain `Error`\n * from `uploadFile`. This type exists so a custom backend that must reject a command BEFORE spawning\n * anything — a container or VM runner enforcing its own policy — can do so in the protocol's\n * vocabulary instead of inventing an error of its own.\n */\nexport class SandboxSecurityError extends TheokitAgentError {\n override readonly name = \"SandboxSecurityError\";\n override readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n // not retryable: a refused command is refused every time; retrying re-asks the same question\n super(message, { code: \"sandbox_security\", isRetryable: false });\n }\n}\n\n/**\n * A backend cannot be used at all: its runtime is missing or unusable. The distinction from\n * {@link SandboxSecurityError} is which side failed — there the sandbox worked and denied the\n * command, here there is no sandbox. Carries `code: \"sandbox_not_available\"`.\n *\n * Nothing in this package throws it either, and that is a position rather than an oversight:\n * `createSandboxBackend` treats a missing bubblewrap as a degradation, warns once, and hands back an\n * unconfined `LocalSandbox`. Throw this instead from a backend that must never silently run outside\n * its isolation.\n */\nexport class SandboxNotAvailableError extends TheokitAgentError {\n override readonly name = \"SandboxNotAvailableError\";\n override readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n // not retryable: a missing runtime does not appear on a second attempt\n super(message, { code: \"sandbox_not_available\", isRetryable: false });\n }\n}\n\n/**\n * The execution capability handed to an agent tool, and the extension point for new environments.\n *\n * A backend implements exactly two methods, `execute` and `uploadFile`. Everything else here —\n * `readFile`, `glob`, `grep`, `listDir` — is derived from `execute` by shelling out `cat`, `find`,\n * `grep` and `ls`, so a subclass that overrides `execute` alone inherits confined reads, searches and\n * listings for free. It does not inherit confined writes: `writeFile` delegates to `uploadFile`, and\n * that is the second override `LinuxSandbox` needs.\n *\n * Choosing one: `LocalSandbox` runs the command on the host with no isolation and suits code you\n * already trust; `LinuxSandbox` adds kernel confinement where bubblewrap is available;\n * `createSandboxBackend` probes and picks between them, and is the right entry point unless you have\n * a reason to pin one. For genuinely untrusted code you want a container or VM backend, which this\n * package does not ship — write it against these two methods.\n *\n * Because the derived helpers assemble shell command lines (arguments escaped for POSIX `sh`), a\n * backend whose `execute` is not a POSIX shell must override them as well.\n */\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n // #54 — preserve the env policy so backends can scrub secrets.\n env: config.env ?? \"inherit-scrubbed\",\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n this.assertCommandRan(\"glob\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n // `grep` exits 1 for NO MATCH and >= 2 for an error, so a 1 is an answer and is not asserted on.\n if (result.exitCode !== 1) this.assertCommandRan(\"grep\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n this.assertCommandRan(\"listDir\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n /**\n * Turns \"the command did not run\" into an error instead of an empty array.\n *\n * `glob`, `grep` and `listDir` used to `return []` on any non-zero exit, so a search that could not\n * run reported the same thing as a search that found nothing — opposite facts, one normal and one\n * meaning the agent is looking at a filesystem it cannot read. That is the failure mode a backend\n * whose `execute` is not a POSIX shell hits, which this class's own docblock warns about in prose\n * and could not enforce.\n *\n * A genuine no-match is still `[]`: `find` exits 0 with empty output, and `grep`'s exit 1 is\n * checked by its caller before this is reached.\n */\n private assertCommandRan(operation: string, result: ExecuteResult): void {\n if (result.exitCode === 0) return;\n throw new ConfigurationError(\n `${operation} failed (exit ${String(result.exitCode)}): ${result.stderr.trim() || \"no stderr\"}. ` +\n `The derived helpers shell out to POSIX \\`cat\\`/\\`find\\`/\\`grep\\`/\\`ls\\` — a backend whose ` +\n `execute() is not a POSIX shell must override them.`,\n { code: \"sandbox_derived_helper_failed\" },\n );\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n\n/**\n * A backend OR a per-request resolver of one — mirrors `FilesystemProvider` / `InteractiveProvider`.\n * A resolver runs at tool-execution time (request scope), so a multi-tenant / multi-role agent gets a\n * distinct sandbox per request without a shared mutable one. This is how a tool takes execution as an\n * INJECTED capability: the same tool runs on a local sandbox, a container/E2B backend (cluster/web), or\n * any future backend, with no direct `child_process` import.\n *\n * @public\n */\nexport type SandboxProvider<Ctx = unknown> =\n | SandboxBackend\n | ((ctx: Ctx) => SandboxBackend | Promise<SandboxBackend>);\n\n/** Resolve a {@link SandboxProvider} to a concrete backend for `ctx`. */\nexport async function resolveSandbox<Ctx>(\n provider: SandboxProvider<Ctx>,\n ctx: Ctx,\n): Promise<SandboxBackend> {\n return provider instanceof SandboxBackend ? provider : provider(ctx);\n}\n","/**\n * LocalSandbox — subprocess-based execution. **This is NOT an isolation\n * boundary.** It runs the command via `/bin/sh -c` in the SAME OS as the host\n * with the host's filesystem and network fully reachable — it provides NO\n * process, filesystem, or network isolation. Its only safety affordances are:\n * - a wall-clock timeout (kills a runaway command),\n * - an output-size cap (bounds memory), and\n * - env scrubbing (#54): secret-like parent env vars (`*KEY*`/`*SECRET*`/\n * `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`) are dropped from the child by default\n * (`SandboxConfig.env`), so a shell tool cannot exfiltrate host secrets via\n * the environment.\n *\n * For real isolation (untrusted code), use a container/VM backend — NOT this.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { resolveChildEnv } from \"../internal/runtime/lifecycle/env-policy.js\";\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\n/**\n * Runs a command with `/bin/sh -c` on the host. NOT an isolation boundary — the\n * module note above states exactly what it does and does not protect.\n *\n * const sandbox = new LocalSandbox({ workDir: \"/srv/repo\", timeoutMs: 10_000 });\n * const { stdout, exitCode, timedOut } = await sandbox.execute(\"ls -1\");\n *\n * Needs a POSIX host with `/bin/sh`. Every helper inherited from\n * {@link SandboxBackend} — `readFile`, `glob`, `grep`, `listDir` — is built on\n * this `execute`, so they inherit that requirement too.\n *\n * How it fails: `execute` NEVER rejects. Every outcome, including a failure to\n * spawn, comes back as an {@link ExecuteResult}; read `timedOut` first\n * (`true` implies `exitCode` 124) and `stderr` for the reason. `uploadFile` DOES\n * reject, with the raw `node:fs` error, on a bad path or missing permission.\n *\n * Traps:\n * - `exitCode` is not the child's exit code. It is 0, 124 (timed out) or 1 — a\n * command that exits 3 is reported as 1, so branching on a specific code does\n * not work here.\n * - Output beyond `maxOutputBytes` (default 5 MiB) makes Node kill the child.\n * The result is `exitCode: 1` and `timedOut: false`, with the cut stream\n * carrying the `...(truncated)` marker described on `ExecuteResult` (#363).\n * Since `exitCode` is 1 either way, that marker is what tells a lost-output\n * result from a command that genuinely failed.\n * - `uploadFile` resolves a relative path against `workDir` but does not contain\n * it: an absolute path, or one containing `..`, writes wherever the process\n * can. `workDir` is a starting directory, not a jail.\n * - Secret-like parent env vars are dropped by default. Passing\n * `env: \"all\"` in {@link SandboxConfig} puts the host's API keys back within\n * reach of any command the agent runs.\n */\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n // #54 — scrub secret-like host env vars from the child by default.\n env: resolveChildEnv({ policy: this.config.env }),\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n // #363 — the ONLY reliable signal that output was lost. Node caps the buffer AT `maxBuffer`, so\n // for ASCII output the string comes back exactly at the cap and `truncateOutput`'s `> max` test\n // never fires; a length comparison cannot tell a cut document from a complete one that happens\n // to be that long. The child being killed for overflow can.\n const overflowed =\n error !== null && (error as { code?: unknown }).code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\";\n return {\n stdout: this.markIfCut(this.truncateOutput(stdout), overflowed),\n stderr: this.markIfCut(this.truncateOutput(stderr), overflowed),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n /**\n * Append the `...(truncated)` marker `ExecuteResult` tells callers to branch on, when the child\n * was killed for exceeding `maxOutputBytes` and this stream is the one sitting at the cap.\n *\n * `truncateOutput` has already run, so an output it marked is left alone rather than marked\n * twice. Node does not say WHICH stream overflowed, so the stream at the cap is the one that\n * lost data — the other, being shorter, is complete.\n */\n private markIfCut(output: string, overflowed: boolean): string {\n if (!overflowed) return output;\n if (output.endsWith(\"...(truncated)\")) return output;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n return Buffer.byteLength(output) >= max ? `${output}\\n...(truncated)` : output;\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/sandbox/shell-escape.ts","../src/sandbox/types.ts","../src/sandbox/local-sandbox.ts"],"names":["TheokitAgentError","ConfigurationError","execFile","resolveChildEnv","path","mkdir","dirname","fsWriteFile"],"mappings":";;;;;;;;;AASO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;;;AC2DO,IAAM,oBAAA,GAAN,cAAmCA,mCAAA,CAAkB;AAAA,EACxC,IAAA,GAAO,sBAAA;AAAA,EACP,IAAA,GAAO,kBAAA;AAAA,EACzB,YAAY,OAAA,EAAiB;AAE3B,IAAA,KAAA,CAAM,SAAS,EAAE,IAAA,EAAM,kBAAA,EAAoB,WAAA,EAAa,OAAO,CAAA;AAAA,EACjE;AACF;AAYO,IAAM,wBAAA,GAAN,cAAuCA,mCAAA,CAAkB;AAAA,EAC5C,IAAA,GAAO,0BAAA;AAAA,EACP,IAAA,GAAO,uBAAA;AAAA,EACzB,YAAY,OAAA,EAAiB;AAE3B,IAAA,KAAA,CAAM,SAAS,EAAE,IAAA,EAAM,uBAAA,EAAyB,WAAA,EAAa,OAAO,CAAA;AAAA,EACtE;AACF;AAoBO,IAAe,iBAAf,MAA8B;AAAA,EACzB,MAAA;AAAA,EAEV,WAAA,CAAY,MAAA,GAAwB,EAAC,EAAG;AACtC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,OAAA,EAAS,OAAO,OAAA,IAAW,MAAA;AAAA,MAC3B,SAAA,EAAW,OAAO,SAAA,IAAa,GAAA;AAAA,MAC/B,cAAA,EAAgB,MAAA,CAAO,cAAA,IAAkB,CAAA,GAAI,IAAA,GAAO,IAAA;AAAA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AA,CAAW,MAAM,CAAA,IAAK,GAAA,GAAM,GAAG,MAAM;AAAA,cAAA,CAAA,GAAqB,MAAA;AAAA,EAC1E;AAAA,EAEA,MAAM,UAAA,CAAWC,MAAA,EAAc,OAAA,EAAyC;AACtE,IAAA,MAAM,QAAA,GAAWA,MAAA,CAAK,UAAA,CAAW,GAAG,CAAA,GAAIA,MAAA,GAAO,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA,CAAA,EAAIA,MAAI,CAAA,CAAA;AAC7E,IAAA,MAAMC,eAAMC,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,IAAA,MAAMC,kBAAA,CAAY,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AAAA,EAC9C;AACF","file":"chunk-7NQ7HJ3E.cjs","sourcesContent":["/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport { ConfigurationError, TheokitAgentError } from \"../errors.js\";\nimport type { EnvPolicy } from \"../types/env-policy.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\n/**\n * What a {@link SandboxBackend} returns for one command.\n *\n * `exitCode` is a coarse signal rather than the child's real exit status: the backends in this\n * package report `0` on success, `124` on timeout, and `1` for everything else — including a command\n * that exited with its own non-zero code. Read `timedOut` to tell a killed command from a failed one,\n * and `stderr` for the reason; branching on a specific exit code will not work here.\n *\n * `stdout` and `stderr` are truncated independently at `SandboxConfig.maxOutputBytes`, with a\n * trailing `...(truncated)` marker. Neither is safe to parse as a complete document without checking\n * for it.\n */\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\n/**\n * Construction-time settings shared by every {@link SandboxBackend}. All fields are optional and the\n * base constructor fills them in, so `{}` is a valid config: `workDir` `/tmp`, `timeoutMs` 30000,\n * `maxOutputBytes` 5 MiB, `env` `\"inherit-scrubbed\"`.\n *\n * `workDir` is the child process's cwd and the base a relative `uploadFile` path resolves against. It\n * is not a boundary — under `LocalSandbox` nothing stops a command, or an absolute path, from leaving\n * it. Only `LinuxSandbox` makes it enforceable.\n *\n * `timeoutMs` is the default for every call; `execute(command, { timeoutMs })` overrides it per\n * command. On expiry the child is killed and the result carries `timedOut: true` with `exitCode`\n * 124 — the partial output collected so far is still returned.\n */\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n /**\n * #54 — env inherit/scrub policy for the executed command's child process.\n * Defaults to `\"inherit-scrubbed\"` (drop secret-like vars: `*KEY*`, `*SECRET*`,\n * `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Pass `\"all\"` to restore full inheritance\n * or `\"core\"` for a minimal safe allowlist.\n */\n env?: EnvPolicy;\n}\n\n/**\n * A backend refused a command on policy grounds — the environment works, and it said no. Carries a\n * stable `code: \"sandbox_security\"` for callers that prefer not to match on the class.\n *\n * Nothing in this package throws it, which is worth knowing before you write a `catch` for it:\n * `LocalSandbox` and `LinuxSandbox` report a refusal through {@link ExecuteResult} (non-zero\n * `exitCode`, reason on `stderr`), and a write blocked under confinement surfaces as a plain `Error`\n * from `uploadFile`. This type exists so a custom backend that must reject a command BEFORE spawning\n * anything — a container or VM runner enforcing its own policy — can do so in the protocol's\n * vocabulary instead of inventing an error of its own.\n */\nexport class SandboxSecurityError extends TheokitAgentError {\n override readonly name = \"SandboxSecurityError\";\n override readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n // not retryable: a refused command is refused every time; retrying re-asks the same question\n super(message, { code: \"sandbox_security\", isRetryable: false });\n }\n}\n\n/**\n * A backend cannot be used at all: its runtime is missing or unusable. The distinction from\n * {@link SandboxSecurityError} is which side failed — there the sandbox worked and denied the\n * command, here there is no sandbox. Carries `code: \"sandbox_not_available\"`.\n *\n * Nothing in this package throws it either, and that is a position rather than an oversight:\n * `createSandboxBackend` treats a missing bubblewrap as a degradation, warns once, and hands back an\n * unconfined `LocalSandbox`. Throw this instead from a backend that must never silently run outside\n * its isolation.\n */\nexport class SandboxNotAvailableError extends TheokitAgentError {\n override readonly name = \"SandboxNotAvailableError\";\n override readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n // not retryable: a missing runtime does not appear on a second attempt\n super(message, { code: \"sandbox_not_available\", isRetryable: false });\n }\n}\n\n/**\n * The execution capability handed to an agent tool, and the extension point for new environments.\n *\n * A backend implements exactly two methods, `execute` and `uploadFile`. Everything else here —\n * `readFile`, `glob`, `grep`, `listDir` — is derived from `execute` by shelling out `cat`, `find`,\n * `grep` and `ls`, so a subclass that overrides `execute` alone inherits confined reads, searches and\n * listings for free. It does not inherit confined writes: `writeFile` delegates to `uploadFile`, and\n * that is the second override `LinuxSandbox` needs.\n *\n * Choosing one: `LocalSandbox` runs the command on the host with no isolation and suits code you\n * already trust; `LinuxSandbox` adds kernel confinement where bubblewrap is available;\n * `createSandboxBackend` probes and picks between them, and is the right entry point unless you have\n * a reason to pin one. For genuinely untrusted code you want a container or VM backend, which this\n * package does not ship — write it against these two methods.\n *\n * Because the derived helpers assemble shell command lines (arguments escaped for POSIX `sh`), a\n * backend whose `execute` is not a POSIX shell must override them as well.\n */\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n // #54 — preserve the env policy so backends can scrub secrets.\n env: config.env ?? \"inherit-scrubbed\",\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n this.assertCommandRan(\"glob\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n // `grep` exits 1 for NO MATCH and >= 2 for an error, so a 1 is an answer and is not asserted on.\n if (result.exitCode !== 1) this.assertCommandRan(\"grep\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n this.assertCommandRan(\"listDir\", result);\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n /**\n * Turns \"the command did not run\" into an error instead of an empty array.\n *\n * `glob`, `grep` and `listDir` used to `return []` on any non-zero exit, so a search that could not\n * run reported the same thing as a search that found nothing — opposite facts, one normal and one\n * meaning the agent is looking at a filesystem it cannot read. That is the failure mode a backend\n * whose `execute` is not a POSIX shell hits, which this class's own docblock warns about in prose\n * and could not enforce.\n *\n * A genuine no-match is still `[]`: `find` exits 0 with empty output, and `grep`'s exit 1 is\n * checked by its caller before this is reached.\n */\n private assertCommandRan(operation: string, result: ExecuteResult): void {\n if (result.exitCode === 0) return;\n throw new ConfigurationError(\n `${operation} failed (exit ${String(result.exitCode)}): ${result.stderr.trim() || \"no stderr\"}. ` +\n `The derived helpers shell out to POSIX \\`cat\\`/\\`find\\`/\\`grep\\`/\\`ls\\` — a backend whose ` +\n `execute() is not a POSIX shell must override them.`,\n { code: \"sandbox_derived_helper_failed\" },\n );\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n\n/**\n * A backend OR a per-request resolver of one — mirrors `FilesystemProvider` / `InteractiveProvider`.\n * A resolver runs at tool-execution time (request scope), so a multi-tenant / multi-role agent gets a\n * distinct sandbox per request without a shared mutable one. This is how a tool takes execution as an\n * INJECTED capability: the same tool runs on a local sandbox, a container/E2B backend (cluster/web), or\n * any future backend, with no direct `child_process` import.\n *\n * @public\n */\nexport type SandboxProvider<Ctx = unknown> =\n | SandboxBackend\n | ((ctx: Ctx) => SandboxBackend | Promise<SandboxBackend>);\n\n/** Resolve a {@link SandboxProvider} to a concrete backend for `ctx`. */\nexport async function resolveSandbox<Ctx>(\n provider: SandboxProvider<Ctx>,\n ctx: Ctx,\n): Promise<SandboxBackend> {\n return provider instanceof SandboxBackend ? provider : provider(ctx);\n}\n","/**\n * LocalSandbox — subprocess-based execution. **This is NOT an isolation\n * boundary.** It runs the command via `/bin/sh -c` in the SAME OS as the host\n * with the host's filesystem and network fully reachable — it provides NO\n * process, filesystem, or network isolation. Its only safety affordances are:\n * - a wall-clock timeout (kills a runaway command),\n * - an output-size cap (bounds memory), and\n * - env scrubbing (#54): secret-like parent env vars (`*KEY*`/`*SECRET*`/\n * `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`) are dropped from the child by default\n * (`SandboxConfig.env`), so a shell tool cannot exfiltrate host secrets via\n * the environment.\n *\n * For real isolation (untrusted code), use a container/VM backend — NOT this.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { resolveChildEnv } from \"../internal/runtime/lifecycle/env-policy.js\";\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\n/**\n * Runs a command with `/bin/sh -c` on the host. NOT an isolation boundary — the\n * module note above states exactly what it does and does not protect.\n *\n * const sandbox = new LocalSandbox({ workDir: \"/srv/repo\", timeoutMs: 10_000 });\n * const { stdout, exitCode, timedOut } = await sandbox.execute(\"ls -1\");\n *\n * Needs a POSIX host with `/bin/sh`. Every helper inherited from\n * {@link SandboxBackend} — `readFile`, `glob`, `grep`, `listDir` — is built on\n * this `execute`, so they inherit that requirement too.\n *\n * How it fails: `execute` NEVER rejects. Every outcome, including a failure to\n * spawn, comes back as an {@link ExecuteResult}; read `timedOut` first\n * (`true` implies `exitCode` 124) and `stderr` for the reason. `uploadFile` DOES\n * reject, with the raw `node:fs` error, on a bad path or missing permission.\n *\n * Traps:\n * - `exitCode` is not the child's exit code. It is 0, 124 (timed out) or 1 — a\n * command that exits 3 is reported as 1, so branching on a specific code does\n * not work here.\n * - Output beyond `maxOutputBytes` (default 5 MiB) makes Node kill the child.\n * The result is `exitCode: 1` and `timedOut: false`, with the cut stream\n * carrying the `...(truncated)` marker described on `ExecuteResult` (#363).\n * Since `exitCode` is 1 either way, that marker is what tells a lost-output\n * result from a command that genuinely failed.\n * - `uploadFile` resolves a relative path against `workDir` but does not contain\n * it: an absolute path, or one containing `..`, writes wherever the process\n * can. `workDir` is a starting directory, not a jail.\n * - Secret-like parent env vars are dropped by default. Passing\n * `env: \"all\"` in {@link SandboxConfig} puts the host's API keys back within\n * reach of any command the agent runs.\n */\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n // #54 — scrub secret-like host env vars from the child by default.\n env: resolveChildEnv({ policy: this.config.env }),\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n // #363 — the ONLY reliable signal that output was lost. Node caps the buffer AT `maxBuffer`, so\n // for ASCII output the string comes back exactly at the cap and `truncateOutput`'s `> max` test\n // never fires; a length comparison cannot tell a cut document from a complete one that happens\n // to be that long. The child being killed for overflow can.\n const overflowed =\n error !== null && (error as { code?: unknown }).code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\";\n return {\n stdout: this.markIfCut(this.truncateOutput(stdout), overflowed),\n stderr: this.markIfCut(this.truncateOutput(stderr), overflowed),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n /**\n * Append the `...(truncated)` marker `ExecuteResult` tells callers to branch on, when the child\n * was killed for exceeding `maxOutputBytes` and this stream is the one sitting at the cap.\n *\n * `truncateOutput` has already run, so an output it marked is left alone rather than marked\n * twice. Node does not say WHICH stream overflowed, so the stream at the cap is the one that\n * lost data — the other, being shorter, is complete.\n */\n private markIfCut(output: string, overflowed: boolean): string {\n if (!overflowed) return output;\n if (output.endsWith(\"...(truncated)\")) return output;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n return Buffer.byteLength(output) >= max ? `${output}\\n...(truncated)` : output;\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n"]}