@theokit/sdk 4.37.2 → 4.39.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 (457) hide show
  1. package/CHANGELOG.md +309 -72
  2. package/dist/a2a/index.cjs +3 -3
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/a2a/subagent.d.cts +1 -0
  5. package/dist/a2a/subagent.d.ts +1 -0
  6. package/dist/{agent-SmxntivO.d.ts → agent-D7bRK9Kg.d.cts} +108 -41
  7. package/dist/agent-I3EZZR6S.cjs +55 -0
  8. package/dist/{agent-IE6IE4NW.cjs.map → agent-I3EZZR6S.cjs.map} +1 -1
  9. package/dist/agent-KKZYLY5D.js +46 -0
  10. package/dist/{agent-DW2J37IH.js.map → agent-KKZYLY5D.js.map} +1 -1
  11. package/dist/{agent-DGv1-d81.d.cts → agent-ZCZa7YQv.d.ts} +108 -41
  12. package/dist/agent-session-store-N4TVKHBU.cjs +23 -0
  13. package/dist/agent-session-store-N4TVKHBU.cjs.map +1 -0
  14. package/dist/agent-session-store-RHMHP5DG.js +6 -0
  15. package/dist/agent-session-store-RHMHP5DG.js.map +1 -0
  16. package/dist/agent.d.ts +38 -2
  17. package/dist/auth/index.cjs +15 -15
  18. package/dist/auth/index.js +4 -4
  19. package/dist/{batch-SY5GZLFD.js → batch-6KQM3EBA.js} +12 -12
  20. package/dist/batch-6KQM3EBA.js.map +1 -0
  21. package/dist/{batch-3SEPDXCU.cjs → batch-X6JKGDPK.cjs} +26 -26
  22. package/dist/batch-X6JKGDPK.cjs.map +1 -0
  23. package/dist/chunk-2RW7K6FN.cjs +34 -0
  24. package/dist/chunk-2RW7K6FN.cjs.map +1 -0
  25. package/dist/chunk-3I4B3OIX.js +105 -0
  26. package/dist/chunk-3I4B3OIX.js.map +1 -0
  27. package/dist/{chunk-2WFB5ZOX.js → chunk-42IFCKQZ.js} +5 -5
  28. package/dist/{chunk-2WFB5ZOX.js.map → chunk-42IFCKQZ.js.map} +1 -1
  29. package/dist/{chunk-DCJ5MCJ3.js → chunk-4F7JQZOX.js} +9 -36
  30. package/dist/chunk-4F7JQZOX.js.map +1 -0
  31. package/dist/{chunk-JNIWFCKI.js → chunk-4JSZYSGW.js} +3 -3
  32. package/dist/{chunk-JNIWFCKI.js.map → chunk-4JSZYSGW.js.map} +1 -1
  33. package/dist/{chunk-EEZ7CFMM.js → chunk-5KOW3GLE.js} +2 -2
  34. package/dist/chunk-5KOW3GLE.js.map +1 -0
  35. package/dist/{chunk-6VP3XGEK.js → chunk-65ONFZWM.js} +12 -11
  36. package/dist/chunk-65ONFZWM.js.map +1 -0
  37. package/dist/{chunk-CSZRJ4RE.js → chunk-6EEYRFJC.js} +5 -5
  38. package/dist/{chunk-CSZRJ4RE.js.map → chunk-6EEYRFJC.js.map} +1 -1
  39. package/dist/{chunk-FAY3QDGC.cjs → chunk-6LGQECT7.cjs} +11 -11
  40. package/dist/{chunk-FAY3QDGC.cjs.map → chunk-6LGQECT7.cjs.map} +1 -1
  41. package/dist/{chunk-PAEJPLVN.cjs → chunk-6NEHIHFU.cjs} +4 -4
  42. package/dist/{chunk-PAEJPLVN.cjs.map → chunk-6NEHIHFU.cjs.map} +1 -1
  43. package/dist/chunk-6YNYA7GD.cjs +103 -0
  44. package/dist/chunk-6YNYA7GD.cjs.map +1 -0
  45. package/dist/chunk-74D7KSBP.cjs +112 -0
  46. package/dist/chunk-74D7KSBP.cjs.map +1 -0
  47. package/dist/{chunk-FK4EJD2I.cjs → chunk-75DSEWTJ.cjs} +7 -7
  48. package/dist/{chunk-FK4EJD2I.cjs.map → chunk-75DSEWTJ.cjs.map} +1 -1
  49. package/dist/{chunk-SWIBQFPH.cjs → chunk-7OLG7VI4.cjs} +4 -4
  50. package/dist/{chunk-SWIBQFPH.cjs.map → chunk-7OLG7VI4.cjs.map} +1 -1
  51. package/dist/chunk-7U2HAAWB.cjs +199 -0
  52. package/dist/chunk-7U2HAAWB.cjs.map +1 -0
  53. package/dist/{chunk-YBFDBOUN.cjs → chunk-7YBJZS5P.cjs} +8 -8
  54. package/dist/{chunk-YBFDBOUN.cjs.map → chunk-7YBJZS5P.cjs.map} +1 -1
  55. package/dist/{chunk-GLUWH6JO.js → chunk-AECV3G5Z.js} +4 -4
  56. package/dist/{chunk-GLUWH6JO.js.map → chunk-AECV3G5Z.js.map} +1 -1
  57. package/dist/{chunk-UQPDFW4E.js → chunk-AR5MQZ3J.js} +3 -3
  58. package/dist/{chunk-UQPDFW4E.js.map → chunk-AR5MQZ3J.js.map} +1 -1
  59. package/dist/{chunk-G2F67XUR.cjs → chunk-B4YA6BRS.cjs} +13 -14
  60. package/dist/chunk-B4YA6BRS.cjs.map +1 -0
  61. package/dist/{chunk-LTCOPATU.cjs → chunk-BCQ3E2ZG.cjs} +12 -3
  62. package/dist/chunk-BCQ3E2ZG.cjs.map +1 -0
  63. package/dist/{chunk-ALU3KC4G.cjs → chunk-BPN5ONSW.cjs} +223 -277
  64. package/dist/chunk-BPN5ONSW.cjs.map +1 -0
  65. package/dist/{chunk-YHZXBDAW.js → chunk-BQDUEG4C.js} +16 -16
  66. package/dist/{chunk-YHZXBDAW.js.map → chunk-BQDUEG4C.js.map} +1 -1
  67. package/dist/{chunk-IT3PWBW4.cjs → chunk-BURYFNOM.cjs} +2 -2
  68. package/dist/chunk-BURYFNOM.cjs.map +1 -0
  69. package/dist/{chunk-BJMKQOY2.cjs → chunk-C7OP3FAK.cjs} +47 -11
  70. package/dist/chunk-C7OP3FAK.cjs.map +1 -0
  71. package/dist/{chunk-XAYVHS2B.cjs → chunk-CEIHCKTO.cjs} +4 -4
  72. package/dist/chunk-CEIHCKTO.cjs.map +1 -0
  73. package/dist/{chunk-2423XDPT.cjs → chunk-CN6UX5EV.cjs} +28 -56
  74. package/dist/chunk-CN6UX5EV.cjs.map +1 -0
  75. package/dist/{chunk-VNNK6AKU.js → chunk-D7IULBF2.js} +3 -3
  76. package/dist/chunk-D7IULBF2.js.map +1 -0
  77. package/dist/chunk-DCXRHCZJ.cjs +118 -0
  78. package/dist/chunk-DCXRHCZJ.cjs.map +1 -0
  79. package/dist/{chunk-ICYBIC6N.cjs → chunk-DGLLVCNB.cjs} +4 -4
  80. package/dist/chunk-DGLLVCNB.cjs.map +1 -0
  81. package/dist/{chunk-I35DI7ES.js → chunk-DKFGUOWL.js} +3 -3
  82. package/dist/{chunk-I35DI7ES.js.map → chunk-DKFGUOWL.js.map} +1 -1
  83. package/dist/{chunk-TQI3KRXZ.cjs → chunk-DMTZ3FII.cjs} +18 -18
  84. package/dist/{chunk-TQI3KRXZ.cjs.map → chunk-DMTZ3FII.cjs.map} +1 -1
  85. package/dist/{chunk-QFMXXUUT.js → chunk-DU7DE543.js} +3 -3
  86. package/dist/{chunk-QFMXXUUT.js.map → chunk-DU7DE543.js.map} +1 -1
  87. package/dist/{chunk-W4QN5CMG.cjs → chunk-DWY25VLP.cjs} +9 -9
  88. package/dist/{chunk-W4QN5CMG.cjs.map → chunk-DWY25VLP.cjs.map} +1 -1
  89. package/dist/chunk-E2FFG33C.js +109 -0
  90. package/dist/chunk-E2FFG33C.js.map +1 -0
  91. package/dist/{chunk-QUFSDDNU.cjs → chunk-E4IUN3JB.cjs} +15 -15
  92. package/dist/{chunk-QUFSDDNU.cjs.map → chunk-E4IUN3JB.cjs.map} +1 -1
  93. package/dist/{chunk-THEYGCYS.cjs → chunk-ECHGWE47.cjs} +4 -4
  94. package/dist/chunk-ECHGWE47.cjs.map +1 -0
  95. package/dist/{chunk-U2WLFOA3.cjs → chunk-ECW2MLEW.cjs} +4 -4
  96. package/dist/{chunk-U2WLFOA3.cjs.map → chunk-ECW2MLEW.cjs.map} +1 -1
  97. package/dist/{chunk-MXSMAGDU.js → chunk-ET6PHZRX.js} +33 -26
  98. package/dist/chunk-ET6PHZRX.js.map +1 -0
  99. package/dist/{chunk-G6AASL5T.cjs → chunk-FRUBE44B.cjs} +24 -24
  100. package/dist/{chunk-G6AASL5T.cjs.map → chunk-FRUBE44B.cjs.map} +1 -1
  101. package/dist/{chunk-3ILFUXNE.cjs → chunk-FWBSDQZ7.cjs} +5 -5
  102. package/dist/{chunk-3ILFUXNE.cjs.map → chunk-FWBSDQZ7.cjs.map} +1 -1
  103. package/dist/{chunk-7DXLNNKH.cjs → chunk-G2Q3ZC6C.cjs} +4 -4
  104. package/dist/{chunk-7DXLNNKH.cjs.map → chunk-G2Q3ZC6C.cjs.map} +1 -1
  105. package/dist/{chunk-56ZM6P7Z.cjs → chunk-G4XUXSRN.cjs} +12 -12
  106. package/dist/chunk-G4XUXSRN.cjs.map +1 -0
  107. package/dist/{chunk-VYJSHGAY.js → chunk-GIRD3RWH.js} +422 -295
  108. package/dist/chunk-GIRD3RWH.js.map +1 -0
  109. package/dist/{chunk-NQ4AC2U4.cjs → chunk-HIQFVHC6.cjs} +9 -9
  110. package/dist/{chunk-NQ4AC2U4.cjs.map → chunk-HIQFVHC6.cjs.map} +1 -1
  111. package/dist/{chunk-EXQV452X.js → chunk-HWNVAUK4.js} +3 -3
  112. package/dist/{chunk-EXQV452X.js.map → chunk-HWNVAUK4.js.map} +1 -1
  113. package/dist/{chunk-P34DHHYQ.cjs → chunk-I53ZQHU6.cjs} +34 -27
  114. package/dist/chunk-I53ZQHU6.cjs.map +1 -0
  115. package/dist/{chunk-MHCKWQR3.cjs → chunk-IHFNRNTJ.cjs} +8 -8
  116. package/dist/{chunk-MHCKWQR3.cjs.map → chunk-IHFNRNTJ.cjs.map} +1 -1
  117. package/dist/{chunk-W52DKZBR.cjs → chunk-INSFS5GT.cjs} +680 -553
  118. package/dist/chunk-INSFS5GT.cjs.map +1 -0
  119. package/dist/{chunk-TAPQWDW2.js → chunk-IVSD7L22.js} +12 -4
  120. package/dist/chunk-IVSD7L22.js.map +1 -0
  121. package/dist/{chunk-WDGCZDRG.js → chunk-J3UK2GMN.js} +3 -3
  122. package/dist/{chunk-WDGCZDRG.js.map → chunk-J3UK2GMN.js.map} +1 -1
  123. package/dist/{chunk-4YB7B3RP.cjs → chunk-J6T5LWJ4.cjs} +15 -14
  124. package/dist/chunk-J6T5LWJ4.cjs.map +1 -0
  125. package/dist/{chunk-XAEAMI5H.js → chunk-JRLXEYR4.js} +21 -5
  126. package/dist/chunk-JRLXEYR4.js.map +1 -0
  127. package/dist/{chunk-ZJN6NTHE.js → chunk-JZUPMTJY.js} +3 -3
  128. package/dist/{chunk-ZJN6NTHE.js.map → chunk-JZUPMTJY.js.map} +1 -1
  129. package/dist/{chunk-M5ZQBOIZ.js → chunk-KE6XKRLQ.js} +3 -3
  130. package/dist/{chunk-M5ZQBOIZ.js.map → chunk-KE6XKRLQ.js.map} +1 -1
  131. package/dist/chunk-KGRIHEDT.js +110 -0
  132. package/dist/chunk-KGRIHEDT.js.map +1 -0
  133. package/dist/{chunk-T4QWDOG6.js → chunk-KWUNN5J2.js} +5 -5
  134. package/dist/{chunk-T4QWDOG6.js.map → chunk-KWUNN5J2.js.map} +1 -1
  135. package/dist/{chunk-56OXYUZE.js → chunk-KX7JV5KM.js} +3 -3
  136. package/dist/chunk-KX7JV5KM.js.map +1 -0
  137. package/dist/{chunk-D4ZUJTFB.cjs → chunk-LALG2K33.cjs} +8 -8
  138. package/dist/{chunk-D4ZUJTFB.cjs.map → chunk-LALG2K33.cjs.map} +1 -1
  139. package/dist/{chunk-QGDKZDPN.js → chunk-LGILIGV3.js} +3 -3
  140. package/dist/{chunk-QGDKZDPN.js.map → chunk-LGILIGV3.js.map} +1 -1
  141. package/dist/{chunk-HEN5WXXI.js → chunk-LJX2SQV2.js} +6 -6
  142. package/dist/{chunk-HEN5WXXI.js.map → chunk-LJX2SQV2.js.map} +1 -1
  143. package/dist/{chunk-SDIBMLL5.js → chunk-MC5EINBV.js} +44 -8
  144. package/dist/chunk-MC5EINBV.js.map +1 -0
  145. package/dist/{chunk-F6Y4IEQM.js → chunk-ML5A5DOJ.js} +4 -4
  146. package/dist/{chunk-F6Y4IEQM.js.map → chunk-ML5A5DOJ.js.map} +1 -1
  147. package/dist/{chunk-6EDQBX7U.cjs → chunk-N475ETD6.cjs} +17 -17
  148. package/dist/{chunk-6EDQBX7U.cjs.map → chunk-N475ETD6.cjs.map} +1 -1
  149. package/dist/{chunk-YPQF26X7.cjs → chunk-OBA6YK2R.cjs} +2 -2
  150. package/dist/chunk-OBA6YK2R.cjs.map +1 -0
  151. package/dist/chunk-OXNYIMZZ.js +31 -0
  152. package/dist/chunk-OXNYIMZZ.js.map +1 -0
  153. package/dist/{chunk-NFCKEBHI.js → chunk-PI4RO4GR.js} +3 -3
  154. package/dist/{chunk-NFCKEBHI.js.map → chunk-PI4RO4GR.js.map} +1 -1
  155. package/dist/{chunk-2ONFGMBV.js → chunk-PY2RQOA7.js} +2 -2
  156. package/dist/chunk-PY2RQOA7.js.map +1 -0
  157. package/dist/chunk-QKE556YD.js +197 -0
  158. package/dist/chunk-QKE556YD.js.map +1 -0
  159. package/dist/{chunk-FV3YEMQ7.js → chunk-RP5HQVLD.js} +13 -14
  160. package/dist/chunk-RP5HQVLD.js.map +1 -0
  161. package/dist/chunk-SCFW5MJZ.js +100 -0
  162. package/dist/chunk-SCFW5MJZ.js.map +1 -0
  163. package/dist/{chunk-CD73YHEH.js → chunk-SG5ZWT6C.js} +3 -3
  164. package/dist/{chunk-CD73YHEH.js.map → chunk-SG5ZWT6C.js.map} +1 -1
  165. package/dist/{chunk-MRODLUGY.cjs → chunk-TIMPJL5V.cjs} +4 -4
  166. package/dist/{chunk-MRODLUGY.cjs.map → chunk-TIMPJL5V.cjs.map} +1 -1
  167. package/dist/{chunk-77WHPVXE.js → chunk-TOTP24P6.js} +4 -4
  168. package/dist/chunk-TOTP24P6.js.map +1 -0
  169. package/dist/{chunk-3O2ELBST.cjs → chunk-USZTVNUQ.cjs} +5 -5
  170. package/dist/{chunk-3O2ELBST.cjs.map → chunk-USZTVNUQ.cjs.map} +1 -1
  171. package/dist/{chunk-YDLNI7J6.js → chunk-V2RBCCN5.js} +3 -3
  172. package/dist/chunk-V2RBCCN5.js.map +1 -0
  173. package/dist/{chunk-NNSKJCBM.cjs → chunk-VJYSQXN6.cjs} +10 -10
  174. package/dist/{chunk-NNSKJCBM.cjs.map → chunk-VJYSQXN6.cjs.map} +1 -1
  175. package/dist/{chunk-GM7QDQ24.cjs → chunk-W4WKVOOQ.cjs} +11 -11
  176. package/dist/{chunk-GM7QDQ24.cjs.map → chunk-W4WKVOOQ.cjs.map} +1 -1
  177. package/dist/chunk-XYOHKCYG.cjs +109 -0
  178. package/dist/chunk-XYOHKCYG.cjs.map +1 -0
  179. package/dist/{chunk-ZW345YOI.js → chunk-YP67XZES.js} +4 -4
  180. package/dist/{chunk-ZW345YOI.js.map → chunk-YP67XZES.js.map} +1 -1
  181. package/dist/{chunk-YCXMSDSP.js → chunk-YRXY2A5L.js} +4 -4
  182. package/dist/{chunk-YCXMSDSP.js.map → chunk-YRXY2A5L.js.map} +1 -1
  183. package/dist/{chunk-IEUDKUPM.cjs → chunk-Z2CUEBXV.cjs} +25 -9
  184. package/dist/chunk-Z2CUEBXV.cjs.map +1 -0
  185. package/dist/{chunk-GL7CFBVC.js → chunk-ZYB6B7QJ.js} +112 -165
  186. package/dist/chunk-ZYB6B7QJ.js.map +1 -0
  187. package/dist/compact-session-PYEC3NZV.js +18 -0
  188. package/dist/{compact-session-WNKKIIDW.js.map → compact-session-PYEC3NZV.js.map} +1 -1
  189. package/dist/compact-session-VVT6IBJG.cjs +55 -0
  190. package/dist/{compact-session-H5TKLD55.cjs.map → compact-session-VVT6IBJG.cjs.map} +1 -1
  191. package/dist/compaction.cjs +19 -19
  192. package/dist/compaction.d.cts +9 -9
  193. package/dist/compaction.d.ts +9 -9
  194. package/dist/compaction.js +3 -3
  195. package/dist/concurrency.cjs +6 -6
  196. package/dist/concurrency.js +4 -4
  197. package/dist/context-2FZSC6VQ.cjs +22 -0
  198. package/dist/{context-ZV33V4DC.cjs.map → context-2FZSC6VQ.cjs.map} +1 -1
  199. package/dist/context-ATJJAFOS.js +5 -0
  200. package/dist/{context-VAYLPT4O.js.map → context-ATJJAFOS.js.map} +1 -1
  201. package/dist/{cron-Dx7B-3WB.d.ts → cron-Bx7tzm5R.d.ts} +54 -2
  202. package/dist/{cron-BiK_aNJI.d.cts → cron-D-DVjGQe.d.cts} +54 -2
  203. package/dist/cron.cjs +34 -30
  204. package/dist/cron.d.cts +3 -3
  205. package/dist/cron.d.ts +3 -3
  206. package/dist/cron.js +33 -29
  207. package/dist/{errors-DyVbXdR4.d.cts → errors-DMY-gLSK.d.cts} +1 -1
  208. package/dist/{errors-Cua4WC9H.d.ts → errors-DjBQ4Tn8.d.ts} +1 -1
  209. package/dist/errors.cjs +21 -21
  210. package/dist/errors.d.cts +2 -2
  211. package/dist/errors.d.ts +2 -2
  212. package/dist/errors.js +2 -2
  213. package/dist/eval.cjs +42 -37
  214. package/dist/eval.cjs.map +1 -1
  215. package/dist/eval.js +38 -33
  216. package/dist/eval.js.map +1 -1
  217. package/dist/{executor-OZSYXDKF.cjs → executor-BMRICN46.cjs} +26 -25
  218. package/dist/executor-BMRICN46.cjs.map +1 -0
  219. package/dist/{executor-PAH72CB5.js → executor-T65PPOPT.js} +10 -9
  220. package/dist/executor-T65PPOPT.js.map +1 -0
  221. package/dist/filesystem/index.cjs +7 -7
  222. package/dist/filesystem/index.js +3 -3
  223. package/dist/fs-session-store-J5MCFFUM.cjs +19 -0
  224. package/dist/{fs-session-store-7E7UPLF2.cjs.map → fs-session-store-J5MCFFUM.cjs.map} +1 -1
  225. package/dist/fs-session-store-O6FNHECD.js +10 -0
  226. package/dist/{fs-session-store-6MY7PNI2.js.map → fs-session-store-O6FNHECD.js.map} +1 -1
  227. package/dist/generate-object-UF6WIZLF.cjs +20 -0
  228. package/dist/{generate-object-5SCEH2EE.cjs.map → generate-object-UF6WIZLF.cjs.map} +1 -1
  229. package/dist/generate-object-XDCBYVK3.js +7 -0
  230. package/dist/{generate-object-I7UD4NWN.js.map → generate-object-XDCBYVK3.js.map} +1 -1
  231. package/dist/index-manager-N7RQYUKT.cjs +20 -0
  232. package/dist/{index-manager-R6ZJFEZF.cjs.map → index-manager-N7RQYUKT.cjs.map} +1 -1
  233. package/dist/index-manager-ZVZUHPP7.js +11 -0
  234. package/dist/{index-manager-KKAK7NT3.js.map → index-manager-ZVZUHPP7.js.map} +1 -1
  235. package/dist/index.cjs +154 -148
  236. package/dist/index.cjs.map +1 -1
  237. package/dist/index.d.cts +201 -43
  238. package/dist/index.d.ts +201 -43
  239. package/dist/index.js +62 -59
  240. package/dist/index.js.map +1 -1
  241. package/dist/{inject-session-UXNJQTZ6.js → inject-session-GQMTDZUN.js} +8 -7
  242. package/dist/inject-session-GQMTDZUN.js.map +1 -0
  243. package/dist/{inject-session-DM4SKTZO.cjs → inject-session-LFCYVSLJ.cjs} +11 -10
  244. package/dist/inject-session-LFCYVSLJ.cjs.map +1 -0
  245. package/dist/internal/agent-loop/live-events.d.ts +46 -0
  246. package/dist/internal/agent-loop/loop-thinking-steps.d.ts +28 -0
  247. package/dist/internal/agent-loop/message-builders.d.ts +12 -3
  248. package/dist/internal/budget/compute-cost.d.ts +1 -1
  249. package/dist/internal/diagnostics.d.ts +46 -31
  250. package/dist/internal/error-mappers/anthropic.d.ts +1 -1
  251. package/dist/internal/global-singleton.d.ts +7 -7
  252. package/dist/internal/judge/judge-call.d.ts +14 -14
  253. package/dist/internal/llm/anthropic-shared.d.ts +4 -4
  254. package/dist/internal/llm/retrying-client.d.ts +29 -29
  255. package/dist/internal/llm/transport-error.d.ts +2 -2
  256. package/dist/internal/llm/types.d.ts +49 -9
  257. package/dist/internal/local-agent/mcp-pool.d.ts +7 -3
  258. package/dist/internal/memory/adapters/azure-openai-embedding.d.cts +2 -0
  259. package/dist/internal/memory/adapters/catalog.d.cts +1 -0
  260. package/dist/internal/memory/adapters/cohere-embedding.d.cts +2 -0
  261. package/dist/internal/memory/adapters/deepinfra-embedding.d.cts +2 -0
  262. package/dist/internal/memory/adapters/gemini-embedding.d.cts +2 -0
  263. package/dist/internal/memory/adapters/index.cjs +28 -0
  264. package/dist/internal/memory/adapters/index.cjs.map +1 -0
  265. package/dist/internal/memory/adapters/index.d.cts +16 -0
  266. package/dist/internal/memory/adapters/index.d.ts +16 -0
  267. package/dist/internal/memory/adapters/index.js +11 -0
  268. package/dist/internal/memory/adapters/index.js.map +1 -0
  269. package/dist/internal/memory/adapters/jina-embedding.d.cts +2 -0
  270. package/dist/internal/memory/adapters/mistral-embedding.d.cts +2 -0
  271. package/dist/internal/memory/adapters/ollama-embedding.d.cts +34 -0
  272. package/dist/internal/memory/adapters/openai-compatible.d.cts +51 -0
  273. package/dist/internal/memory/adapters/openai-compatible.d.ts +28 -0
  274. package/dist/internal/memory/adapters/openai-embedding.d.cts +2 -0
  275. package/dist/internal/memory/adapters/openrouter-embedding.d.cts +2 -0
  276. package/dist/internal/memory/adapters/voyage-embedding.d.cts +2 -0
  277. package/dist/internal/memory/dreaming/diary.d.ts +4 -0
  278. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  279. package/dist/internal/memory/dreaming/run.d.ts +10 -0
  280. package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +15 -0
  281. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +21 -0
  282. package/dist/internal/persistence/exclusive-create.d.cts +2 -2
  283. package/dist/internal/persistence/exclusive-create.d.ts +2 -2
  284. package/dist/internal/persistence/fs-session-store.d.cts +18 -18
  285. package/dist/internal/persistence/fs-session-store.d.ts +18 -18
  286. package/dist/internal/persistence/index.cjs +25 -25
  287. package/dist/internal/persistence/index.cjs.map +1 -1
  288. package/dist/internal/persistence/index.js +6 -6
  289. package/dist/internal/persistence/index.js.map +1 -1
  290. package/dist/internal/persistence/paths.d.cts +7 -7
  291. package/dist/internal/persistence/paths.d.ts +7 -7
  292. package/dist/internal/persistence/session-transcript.d.cts +13 -7
  293. package/dist/internal/persistence/session-transcript.d.ts +13 -7
  294. package/dist/internal/persistence/session-writer.d.cts +30 -13
  295. package/dist/internal/persistence/session-writer.d.ts +30 -13
  296. package/dist/internal/runtime/concurrency/subagent-credentials.d.ts +35 -0
  297. package/dist/internal/runtime/fixtures/fixture-run-base.d.ts +45 -13
  298. package/dist/internal/runtime/lifecycle/goal-marker.d.ts +8 -8
  299. package/dist/internal/security/index.cjs +13 -13
  300. package/dist/internal/security/index.js +3 -3
  301. package/dist/internal/session/agent-session-store.d.ts +1 -0
  302. package/dist/internal/session/agent-session.d.ts +14 -14
  303. package/dist/internal/session/session-cache.d.ts +9 -9
  304. package/dist/internal/session/session-types.d.ts +6 -1
  305. package/dist/judge-call-NA2G6ZMJ.js +5 -0
  306. package/dist/{judge-call-TAEIXMYG.js.map → judge-call-NA2G6ZMJ.js.map} +1 -1
  307. package/dist/judge-call-U2D33JOW.cjs +22 -0
  308. package/dist/{judge-call-SP3G3X2Y.cjs.map → judge-call-U2D33JOW.cjs.map} +1 -1
  309. package/dist/models.cjs +20 -20
  310. package/dist/models.cjs.map +1 -1
  311. package/dist/models.js +5 -5
  312. package/dist/models.js.map +1 -1
  313. package/dist/path-safety.cjs +10 -10
  314. package/dist/path-safety.js +3 -3
  315. package/dist/persistence.cjs +43 -43
  316. package/dist/persistence.cjs.map +1 -1
  317. package/dist/persistence.d.cts +1 -1
  318. package/dist/persistence.d.ts +1 -1
  319. package/dist/persistence.js +14 -14
  320. package/dist/persistence.js.map +1 -1
  321. package/dist/project.cjs +5 -5
  322. package/dist/project.js +3 -3
  323. package/dist/registry-CAS6Y5ZY.js +9 -0
  324. package/dist/{registry-SOXE4RY6.js.map → registry-CAS6Y5ZY.js.map} +1 -1
  325. package/dist/registry-JSDI4WKA.cjs +46 -0
  326. package/dist/{registry-N3GTKYCI.cjs.map → registry-JSDI4WKA.cjs.map} +1 -1
  327. package/dist/retry.cjs +4 -4
  328. package/dist/retry.js +3 -3
  329. package/dist/{run-CwEJtLPE.d.ts → run-i2-fUohR.d.cts} +217 -174
  330. package/dist/{run-CwEJtLPE.d.cts → run-i2-fUohR.d.ts} +217 -174
  331. package/dist/{run-until-YZ2ODWOF.js → run-until-BK56WG4P.js} +3 -3
  332. package/dist/{run-until-YZ2ODWOF.js.map → run-until-BK56WG4P.js.map} +1 -1
  333. package/dist/{run-until-ZZ2JLPJM.cjs → run-until-L5KQD3PV.cjs} +4 -4
  334. package/dist/{run-until-ZZ2JLPJM.cjs.map → run-until-L5KQD3PV.cjs.map} +1 -1
  335. package/dist/sandbox/bwrap.d.cts +20 -20
  336. package/dist/sandbox/bwrap.d.ts +20 -20
  337. package/dist/sandbox/index.cjs +39 -39
  338. package/dist/sandbox/index.cjs.map +1 -1
  339. package/dist/sandbox/index.d.cts +1 -1
  340. package/dist/sandbox/index.d.ts +1 -1
  341. package/dist/sandbox/index.js +35 -35
  342. package/dist/sandbox/index.js.map +1 -1
  343. package/dist/sandbox/linux-sandbox.d.cts +26 -21
  344. package/dist/sandbox/linux-sandbox.d.ts +26 -21
  345. package/dist/server/auth/index.cjs.map +1 -1
  346. package/dist/server/auth/index.d.cts +6 -6
  347. package/dist/server/auth/index.d.ts +6 -6
  348. package/dist/server/auth/index.js.map +1 -1
  349. package/dist/server/auth/orchestrator.d.cts +2 -2
  350. package/dist/server/auth/orchestrator.d.ts +2 -2
  351. package/dist/server/auth/types.d.cts +4 -4
  352. package/dist/server/auth/types.d.ts +4 -4
  353. package/dist/server/errors-envelope.cjs +14 -14
  354. package/dist/server/errors-envelope.d.cts +3 -3
  355. package/dist/server/errors-envelope.d.ts +3 -3
  356. package/dist/server/errors-envelope.js +3 -3
  357. package/dist/session-transcript-3B52DKTG.js +5 -0
  358. package/dist/{session-transcript-6WKLYIN4.js.map → session-transcript-3B52DKTG.js.map} +1 -1
  359. package/dist/session-transcript-H7NUFXXM.cjs +50 -0
  360. package/dist/{session-transcript-EAKR4D2W.cjs.map → session-transcript-H7NUFXXM.cjs.map} +1 -1
  361. package/dist/skills.cjs +7 -7
  362. package/dist/skills.js +5 -5
  363. package/dist/stream-object-4FDU76YW.cjs +20 -0
  364. package/dist/{stream-object-Y7YCX3BI.cjs.map → stream-object-4FDU76YW.cjs.map} +1 -1
  365. package/dist/stream-object-HWDEEQN4.js +7 -0
  366. package/dist/{stream-object-OFM66VUT.js.map → stream-object-HWDEEQN4.js.map} +1 -1
  367. package/dist/subagents-loader-A4W6C3QP.cjs +15 -0
  368. package/dist/subagents-loader-A4W6C3QP.cjs.map +1 -0
  369. package/dist/subagents-loader-X33KH2SZ.js +6 -0
  370. package/dist/subagents-loader-X33KH2SZ.js.map +1 -0
  371. package/dist/subagents-loader.cjs +6 -6
  372. package/dist/subagents-loader.d.cts +2 -2
  373. package/dist/subagents-loader.d.ts +2 -2
  374. package/dist/subagents-loader.js +4 -4
  375. package/dist/subscription/index.cjs +3 -3
  376. package/dist/subscription/index.js +2 -2
  377. package/dist/task-store.cjs +7 -7
  378. package/dist/task-store.js +4 -4
  379. package/dist/types/agent-prims.d.ts +4 -4
  380. package/dist/types/agent.d.ts +68 -3
  381. package/dist/types/conversation.d.ts +7 -0
  382. package/dist/types/goal-events.d.ts +24 -23
  383. package/dist/types/messages.d.ts +9 -0
  384. package/dist/types/run.d.ts +27 -0
  385. package/dist/types/session-message.d.ts +59 -0
  386. package/dist/types/session-record.d.ts +14 -13
  387. package/dist/types/workflow.d.ts +36 -0
  388. package/dist/workflow.cjs +27 -27
  389. package/dist/workflow.d.cts +17 -1
  390. package/dist/workflow.d.ts +17 -1
  391. package/dist/workflow.js +6 -6
  392. package/docs/harness-capability-map.md +22 -0
  393. package/package.json +22 -13
  394. package/dist/agent-DW2J37IH.js +0 -42
  395. package/dist/agent-IE6IE4NW.cjs +0 -51
  396. package/dist/batch-3SEPDXCU.cjs.map +0 -1
  397. package/dist/batch-SY5GZLFD.js.map +0 -1
  398. package/dist/chunk-2423XDPT.cjs.map +0 -1
  399. package/dist/chunk-2ONFGMBV.js.map +0 -1
  400. package/dist/chunk-4YB7B3RP.cjs.map +0 -1
  401. package/dist/chunk-56OXYUZE.js.map +0 -1
  402. package/dist/chunk-56ZM6P7Z.cjs.map +0 -1
  403. package/dist/chunk-5SB4V74H.js +0 -176
  404. package/dist/chunk-5SB4V74H.js.map +0 -1
  405. package/dist/chunk-6VP3XGEK.js.map +0 -1
  406. package/dist/chunk-77WHPVXE.js.map +0 -1
  407. package/dist/chunk-ALU3KC4G.cjs.map +0 -1
  408. package/dist/chunk-BJMKQOY2.cjs.map +0 -1
  409. package/dist/chunk-DCJ5MCJ3.js.map +0 -1
  410. package/dist/chunk-EEZ7CFMM.js.map +0 -1
  411. package/dist/chunk-FV3YEMQ7.js.map +0 -1
  412. package/dist/chunk-G2F67XUR.cjs.map +0 -1
  413. package/dist/chunk-GL7CFBVC.js.map +0 -1
  414. package/dist/chunk-H5YVJB4K.cjs +0 -185
  415. package/dist/chunk-H5YVJB4K.cjs.map +0 -1
  416. package/dist/chunk-ICYBIC6N.cjs.map +0 -1
  417. package/dist/chunk-IEUDKUPM.cjs.map +0 -1
  418. package/dist/chunk-IT3PWBW4.cjs.map +0 -1
  419. package/dist/chunk-ITLS5LRF.cjs +0 -105
  420. package/dist/chunk-ITLS5LRF.cjs.map +0 -1
  421. package/dist/chunk-LTCOPATU.cjs.map +0 -1
  422. package/dist/chunk-MXSMAGDU.js.map +0 -1
  423. package/dist/chunk-P34DHHYQ.cjs.map +0 -1
  424. package/dist/chunk-SDIBMLL5.js.map +0 -1
  425. package/dist/chunk-TAPQWDW2.js.map +0 -1
  426. package/dist/chunk-THEYGCYS.cjs.map +0 -1
  427. package/dist/chunk-VNNK6AKU.js.map +0 -1
  428. package/dist/chunk-VYJSHGAY.js.map +0 -1
  429. package/dist/chunk-W52DKZBR.cjs.map +0 -1
  430. package/dist/chunk-XAEAMI5H.js.map +0 -1
  431. package/dist/chunk-XAYVHS2B.cjs.map +0 -1
  432. package/dist/chunk-YDLNI7J6.js.map +0 -1
  433. package/dist/chunk-YPQF26X7.cjs.map +0 -1
  434. package/dist/chunk-YVTNFKZO.js +0 -103
  435. package/dist/chunk-YVTNFKZO.js.map +0 -1
  436. package/dist/compact-session-H5TKLD55.cjs +0 -54
  437. package/dist/compact-session-WNKKIIDW.js +0 -17
  438. package/dist/context-VAYLPT4O.js +0 -5
  439. package/dist/context-ZV33V4DC.cjs +0 -22
  440. package/dist/executor-OZSYXDKF.cjs.map +0 -1
  441. package/dist/executor-PAH72CB5.js.map +0 -1
  442. package/dist/fs-session-store-6MY7PNI2.js +0 -10
  443. package/dist/fs-session-store-7E7UPLF2.cjs +0 -19
  444. package/dist/generate-object-5SCEH2EE.cjs +0 -20
  445. package/dist/generate-object-I7UD4NWN.js +0 -7
  446. package/dist/index-manager-KKAK7NT3.js +0 -10
  447. package/dist/index-manager-R6ZJFEZF.cjs +0 -19
  448. package/dist/inject-session-DM4SKTZO.cjs.map +0 -1
  449. package/dist/inject-session-UXNJQTZ6.js.map +0 -1
  450. package/dist/judge-call-SP3G3X2Y.cjs +0 -22
  451. package/dist/judge-call-TAEIXMYG.js +0 -5
  452. package/dist/registry-N3GTKYCI.cjs +0 -46
  453. package/dist/registry-SOXE4RY6.js +0 -9
  454. package/dist/session-transcript-6WKLYIN4.js +0 -5
  455. package/dist/session-transcript-EAKR4D2W.cjs +0 -50
  456. package/dist/stream-object-OFM66VUT.js +0 -7
  457. package/dist/stream-object-Y7YCX3BI.cjs +0 -20
@@ -1,34 +1,35 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkBV2MWEMV_cjs = require('./chunk-BV2MWEMV.cjs');
4
- var chunk6EDQBX7U_cjs = require('./chunk-6EDQBX7U.cjs');
5
- var chunkH5YVJB4K_cjs = require('./chunk-H5YVJB4K.cjs');
6
- var chunkITLS5LRF_cjs = require('./chunk-ITLS5LRF.cjs');
7
- var chunkALU3KC4G_cjs = require('./chunk-ALU3KC4G.cjs');
8
- var chunk2423XDPT_cjs = require('./chunk-2423XDPT.cjs');
9
- var chunkFAY3QDGC_cjs = require('./chunk-FAY3QDGC.cjs');
4
+ var chunkN475ETD6_cjs = require('./chunk-N475ETD6.cjs');
5
+ var chunkDCXRHCZJ_cjs = require('./chunk-DCXRHCZJ.cjs');
6
+ var chunk74D7KSBP_cjs = require('./chunk-74D7KSBP.cjs');
7
+ var chunkBPN5ONSW_cjs = require('./chunk-BPN5ONSW.cjs');
8
+ var chunkCN6UX5EV_cjs = require('./chunk-CN6UX5EV.cjs');
9
+ var chunk6LGQECT7_cjs = require('./chunk-6LGQECT7.cjs');
10
10
  var chunkWPZTYOUX_cjs = require('./chunk-WPZTYOUX.cjs');
11
- var chunkD4ZUJTFB_cjs = require('./chunk-D4ZUJTFB.cjs');
11
+ var chunkLALG2K33_cjs = require('./chunk-LALG2K33.cjs');
12
+ var chunk7U2HAAWB_cjs = require('./chunk-7U2HAAWB.cjs');
12
13
  var chunk6JSIEDKL_cjs = require('./chunk-6JSIEDKL.cjs');
13
- var chunkG2F67XUR_cjs = require('./chunk-G2F67XUR.cjs');
14
+ var chunkB4YA6BRS_cjs = require('./chunk-B4YA6BRS.cjs');
14
15
  var chunkNINIJCHU_cjs = require('./chunk-NINIJCHU.cjs');
15
16
  var chunkYPEPCZHF_cjs = require('./chunk-YPEPCZHF.cjs');
16
17
  var chunkVJ26EKGJ_cjs = require('./chunk-VJ26EKGJ.cjs');
17
- var chunkSWIBQFPH_cjs = require('./chunk-SWIBQFPH.cjs');
18
- var chunkTQI3KRXZ_cjs = require('./chunk-TQI3KRXZ.cjs');
18
+ var chunk7OLG7VI4_cjs = require('./chunk-7OLG7VI4.cjs');
19
+ var chunkZ2CUEBXV_cjs = require('./chunk-Z2CUEBXV.cjs');
20
+ var chunkDMTZ3FII_cjs = require('./chunk-DMTZ3FII.cjs');
19
21
  var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
20
- var chunkIEUDKUPM_cjs = require('./chunk-IEUDKUPM.cjs');
21
22
  var chunkWJVHMTKB_cjs = require('./chunk-WJVHMTKB.cjs');
22
- var chunkICYBIC6N_cjs = require('./chunk-ICYBIC6N.cjs');
23
- var chunkGM7QDQ24_cjs = require('./chunk-GM7QDQ24.cjs');
24
- var chunk4YB7B3RP_cjs = require('./chunk-4YB7B3RP.cjs');
23
+ var chunkDGLLVCNB_cjs = require('./chunk-DGLLVCNB.cjs');
24
+ var chunkW4WKVOOQ_cjs = require('./chunk-W4WKVOOQ.cjs');
25
+ var chunkJ6T5LWJ4_cjs = require('./chunk-J6T5LWJ4.cjs');
25
26
  var chunkVYHJZVL5_cjs = require('./chunk-VYHJZVL5.cjs');
26
- var chunk56ZM6P7Z_cjs = require('./chunk-56ZM6P7Z.cjs');
27
- var chunkQUFSDDNU_cjs = require('./chunk-QUFSDDNU.cjs');
28
- var chunkYBFDBOUN_cjs = require('./chunk-YBFDBOUN.cjs');
29
- var chunk7DXLNNKH_cjs = require('./chunk-7DXLNNKH.cjs');
30
- var chunkMHCKWQR3_cjs = require('./chunk-MHCKWQR3.cjs');
31
- var chunkLTCOPATU_cjs = require('./chunk-LTCOPATU.cjs');
27
+ var chunkG4XUXSRN_cjs = require('./chunk-G4XUXSRN.cjs');
28
+ var chunkE4IUN3JB_cjs = require('./chunk-E4IUN3JB.cjs');
29
+ var chunk7YBJZS5P_cjs = require('./chunk-7YBJZS5P.cjs');
30
+ var chunkG2Q3ZC6C_cjs = require('./chunk-G2Q3ZC6C.cjs');
31
+ var chunkIHFNRNTJ_cjs = require('./chunk-IHFNRNTJ.cjs');
32
+ var chunkBCQ3E2ZG_cjs = require('./chunk-BCQ3E2ZG.cjs');
32
33
  var promises = require('fs/promises');
33
34
  var crypto = require('crypto');
34
35
  var path = require('path');
@@ -224,7 +225,7 @@ async function agentGenerate(agent, agentModel, agentApiKey, agentLocal, input,
224
225
  const { output, maxRetries, errorStrategy, ...sendOptions } = options;
225
226
  const run = await agent.send(input, sendOptions);
226
227
  const result = await run.wait();
227
- const { generateObjectImpl, GenerateObjectError } = await import('./generate-object-5SCEH2EE.cjs');
228
+ const { generateObjectImpl, GenerateObjectError } = await import('./generate-object-UF6WIZLF.cjs');
228
229
  const answer = structurableAnswerOrThrow(result, GenerateObjectError);
229
230
  const { getAgentFacade } = await import('./agent-factory-registry-UU46BUMU.cjs');
230
231
  const facade = getAgentFacade();
@@ -326,7 +327,7 @@ function normalizeModel(m) {
326
327
  if (m === void 0 || typeof m !== "string") return m;
327
328
  const id = m.trim();
328
329
  if (id.length === 0) {
329
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
330
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
330
331
  'model must be a non-empty "provider/model" id string or a ModelSelection object',
331
332
  { code: "invalid_model_selection" }
332
333
  );
@@ -462,7 +463,7 @@ function registryPath(cwd) {
462
463
  return path.join(cwd, REGISTRY_RELATIVE_PATH);
463
464
  }
464
465
  async function loadRegistry(cwd) {
465
- return chunkD4ZUJTFB_cjs.readVersionedJson({
466
+ return chunkLALG2K33_cjs.readVersionedJson({
466
467
  path: registryPath(cwd),
467
468
  currentVersion: SCHEMA_VERSION,
468
469
  defaultValue: () => ({}),
@@ -486,7 +487,7 @@ async function saveRegistry(cwd, agents2) {
486
487
  }
487
488
  const path = registryPath(cwd);
488
489
  await chunkYLQQX5W2_cjs.withCwdMutex(`registry:${cwd}`, async () => {
489
- await chunkD4ZUJTFB_cjs.writeVersionedJson(path, serialized, SCHEMA_VERSION);
490
+ await chunkLALG2K33_cjs.writeVersionedJson(path, serialized, SCHEMA_VERSION);
490
491
  });
491
492
  }
492
493
  function toSerialized(agent) {
@@ -553,7 +554,7 @@ function scheduleSaveForCwd(cwd) {
553
554
  }
554
555
  } catch (cause) {
555
556
  const msg = cause instanceof Error ? cause.message : String(cause);
556
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] registry persist failed (${cwd}): ${msg}
557
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] registry persist failed (${cwd}): ${msg}
557
558
  `);
558
559
  } finally {
559
560
  pendingSaves.delete(cwd);
@@ -892,14 +893,14 @@ async function readLegacyFacts(jsonPath) {
892
893
  }
893
894
  async function writeMigratedFacts(cwd, jsonPath, facts) {
894
895
  try {
895
- for (const fact of facts) await chunk2423XDPT_cjs.appendFactToMarkdown(cwd, fact);
896
+ for (const fact of facts) await chunkCN6UX5EV_cjs.appendFactToMarkdown(cwd, fact);
896
897
  await promises.unlink(jsonPath).catch(() => void 0);
897
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
898
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
898
899
  `);
899
900
  return { migrated: true, factCount: facts.length };
900
901
  } catch (cause) {
901
902
  const message = cause instanceof Error ? cause.message : String(cause);
902
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] memory migration failed (readonly fs?): ${message}
903
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] memory migration failed (readonly fs?): ${message}
903
904
  `);
904
905
  return { migrated: false, factCount: 0, reason: "readonly-fs" };
905
906
  }
@@ -909,12 +910,12 @@ async function migrateLegacyJson(cwd, config) {
909
910
  const key = `${cwd}::${config.namespace ?? "default"}::${config.scope ?? "agent"}::${config.userId ?? "default"}`;
910
911
  if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: "already-migrated" };
911
912
  migrationRun.add(key);
912
- const jsonPath = chunk2423XDPT_cjs.legacyMemoryJsonPath(cwd, config);
913
+ const jsonPath = chunkCN6UX5EV_cjs.legacyMemoryJsonPath(cwd, config);
913
914
  if (!await fileExists(jsonPath)) {
914
915
  return { migrated: false, factCount: 0, reason: "no-legacy-json" };
915
916
  }
916
- if (await fileExists(chunk2423XDPT_cjs.memoryMdPath(cwd))) {
917
- chunkLTCOPATU_cjs.diag(
917
+ if (await fileExists(chunkCN6UX5EV_cjs.memoryMdPath(cwd))) {
918
+ chunkBCQ3E2ZG_cjs.diag(
918
919
  `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact
919
920
  `
920
921
  );
@@ -938,13 +939,13 @@ function extractMemoryFact(message) {
938
939
  async function readMemoryFacts(cwd, config) {
939
940
  if (!config.enabled) return [];
940
941
  await migrateLegacyJson(cwd, config);
941
- return chunk2423XDPT_cjs.readFacts(cwd, config);
942
+ return chunkCN6UX5EV_cjs.readFacts(cwd, config);
942
943
  }
943
944
  async function appendMemoryFact(cwd, config, fact) {
944
945
  if (!config.enabled) return;
945
946
  await migrateLegacyJson(cwd, config);
946
- const sanitized = { text: chunkLTCOPATU_cjs.redactSecrets(fact.text) };
947
- await chunk2423XDPT_cjs.appendFact(cwd, config, sanitized);
947
+ const sanitized = { text: chunkBCQ3E2ZG_cjs.redactSecrets(fact.text) };
948
+ await chunkCN6UX5EV_cjs.appendFact(cwd, config, sanitized);
948
949
  }
949
950
 
950
951
  // src/internal/runtime/fixtures/fixture-scripts.ts
@@ -1292,7 +1293,7 @@ function redactScriptSecrets(script) {
1292
1293
  function redactEventSecrets(event) {
1293
1294
  const serialized = JSON.stringify(event);
1294
1295
  const localStripped = serialized.replace(FIXTURE_SENTINEL, "***");
1295
- const redacted = chunkLTCOPATU_cjs.redactSecrets(localStripped);
1296
+ const redacted = chunkBCQ3E2ZG_cjs.redactSecrets(localStripped);
1296
1297
  if (redacted === serialized) return event;
1297
1298
  return JSON.parse(redacted);
1298
1299
  }
@@ -1323,6 +1324,16 @@ var FixtureRunBase = class {
1323
1324
  resolveTermination;
1324
1325
  terminated = false;
1325
1326
  eventNotifier;
1327
+ /**
1328
+ * theokit#140 - the run's single ordered timeline: structural events and live token/tool deltas,
1329
+ * in the order they actually occurred.
1330
+ *
1331
+ * Kept alongside `script.events` rather than replacing it. `stream()` is the SDKMessage view and
1332
+ * stays byte-identical for every existing consumer; this is the complete view, and a consumer
1333
+ * picks one. Merging them would have changed `stream()`'s element type - a breaking change for
1334
+ * an additive feature.
1335
+ */
1336
+ timeline = [];
1326
1337
  constructor(options) {
1327
1338
  this.id = options.id;
1328
1339
  this.agentId = options.agentId;
@@ -1346,6 +1357,46 @@ var FixtureRunBase = class {
1346
1357
  this.eventNotifier = makeNotifier();
1347
1358
  current.resolve();
1348
1359
  }
1360
+ /**
1361
+ * theokit#140 - every event of this run, in true order, from ONE source.
1362
+ *
1363
+ * ## The defect this replaces
1364
+ *
1365
+ * A consumer that needed tool calls interleaved with tokens had to fuse two surfaces by hand:
1366
+ * `stream()`, which was batched and post-completion, and `SendOptions.onDelta`, which was live.
1367
+ * Neither was complete alone - `onDelta` has no `run_started`/`system`, and `stream()` had no
1368
+ * token granularity - so the entire reconciliation, including its dedup, lived in the consumer.
1369
+ * `@theokit/agents` carried ~200 lines of exactly that, and it is the documented root of its
1370
+ * ordering bug (theokit#47), its namespace-dedup bug (#138) and its missing terminal frame (#142).
1371
+ *
1372
+ * The ordering is not reconstructed here. Both kinds are appended by the loop AS THEY HAPPEN, so
1373
+ * arrival order IS model order - there is nothing to sort, and no timestamp heuristic to get
1374
+ * wrong.
1375
+ *
1376
+ * `callId` is whatever the SDK's own `tool_call` events carry, so a consumer no longer holds two
1377
+ * id namespaces and no longer has to correlate them.
1378
+ */
1379
+ async *events() {
1380
+ let index = 0;
1381
+ while (!this.terminated) {
1382
+ while (index < this.timeline.length) {
1383
+ yield this.timeline[index++];
1384
+ }
1385
+ if (this.terminated) break;
1386
+ await Promise.race([this.eventNotifier.promise, this.terminationPromise]);
1387
+ }
1388
+ while (index < this.timeline.length) {
1389
+ yield this.timeline[index++];
1390
+ }
1391
+ for await (const message of this.terminalErrorEvent()) {
1392
+ yield { kind: "message", message };
1393
+ }
1394
+ }
1395
+ /** theokit#140 - append to the timeline and wake `events()`. */
1396
+ pushTimeline(event) {
1397
+ this.timeline.push(event);
1398
+ this.notifyNewEvents();
1399
+ }
1349
1400
  async *stream() {
1350
1401
  let index = 0;
1351
1402
  while (!this.terminated) {
@@ -1361,22 +1412,22 @@ var FixtureRunBase = class {
1361
1412
  yield* this.terminalErrorEvent();
1362
1413
  }
1363
1414
  /**
1364
- * theokit#101 — quando o run termina em erro, `stream()` tem de DIZER.
1415
+ * theokit#101 — when the run ends in error, `stream()` has to SAY SO.
1365
1416
  *
1366
- * O erro sempre existiu: o loop o registra em `ctx.error` e `wait()` devolve
1367
- * `status: 'error'` com a mensagem. o `stream()` não o mencionavaele drena
1368
- * `script.events` e para. Uma falha de provider (404 "No endpoints found", auth, timeout)
1369
- * produzia um turno que parecia bem-sucedido e vazio, em TODA superfície que consome o
1417
+ * The error always existed: the loop records it in `ctx.error` and `wait()` returns
1418
+ * `status: 'error'` with the message. Only `stream()` failed to mention it it drains
1419
+ * `script.events` and stops. A provider failure (404 "No endpoints found", auth, timeout)
1420
+ * produced a turn that looked successful and empty, on EVERY surface consuming the
1370
1421
  * stream: HTTP web, MCP, stdio, TUI in-process.
1371
1422
  *
1372
- * Erro silencioso é o pior tipo (Regra Inquebrável 8). E a assimetria era o que o tornava
1373
- * difícil de diagnosticar: quem depurasse por `wait()` via o erro e não reproduziria o
1374
- * relato de quem depurava pelo stream.
1423
+ * A silent error is the worst kind (Unbreakable Rule 8). And the asymmetry was what made it
1424
+ * hard to diagnose: anyone debugging via `wait()` saw the error and would not reproduce the
1425
+ * report of anyone debugging via the stream.
1375
1426
  *
1376
- * Emite `SDKStatusMessage` com `status: "ERROR"` — o tipo EXISTE na união `SDKMessage`
1377
- * e é esperado por quem consome. Um tipo novo seria breaking para todo consumidor que
1378
- * faz switch exaustivo; este é aditivo, e um consumidor que ignore `status` simplesmente
1379
- * segue como antesnunca pior que hoje.
1427
+ * It emits `SDKStatusMessage` with `status: "ERROR"` — the type ALREADY EXISTS in the `SDKMessage` union
1428
+ * and is already expected by consumers. A new type would be breaking for every consumer doing
1429
+ * an exhaustive switch; this one is additive, and a consumer ignoring `status` simply
1430
+ * behaves as beforenever worse than today.
1380
1431
  */
1381
1432
  *terminalErrorEvent() {
1382
1433
  if (this.status !== "error") return;
@@ -1386,7 +1437,7 @@ var FixtureRunBase = class {
1386
1437
  agent_id: this.agentId,
1387
1438
  run_id: this.id,
1388
1439
  status: "ERROR",
1389
- // Sem mensagem, o consumidor sabe QUE falhou e não O QUÊque é metade do defeito.
1440
+ // Without a message, the consumer knows THAT it failed and not WHATwhich is half the defect.
1390
1441
  ...detail?.message !== void 0 ? { message: detail.message } : {}
1391
1442
  };
1392
1443
  }
@@ -1565,7 +1616,7 @@ function createRealCloudRun(options) {
1565
1616
  conversation: []
1566
1617
  };
1567
1618
  const apiKey = resolveApiKey(options.agentOptions.apiKey);
1568
- const baseUrl = chunkALU3KC4G_cjs.getConfiguredBaseUrl();
1619
+ const baseUrl = chunkBPN5ONSW_cjs.getConfiguredBaseUrl();
1569
1620
  const handle = new RealCloudRun(
1570
1621
  {
1571
1622
  id,
@@ -1638,7 +1689,7 @@ var RealCloudRun = class extends FixtureRunBase {
1638
1689
  });
1639
1690
  if (!response.ok) {
1640
1691
  const text = await response.text().catch(() => "");
1641
- throw new chunkMHCKWQR3_cjs.NetworkError(
1692
+ throw new chunkIHFNRNTJ_cjs.NetworkError(
1642
1693
  `Cloud Run endpoint returned ${response.status}: ${text.slice(0, 200)}`,
1643
1694
  { code: "cloud_run_http_error" }
1644
1695
  );
@@ -1648,7 +1699,7 @@ var RealCloudRun = class extends FixtureRunBase {
1648
1699
  async consumeStream(response) {
1649
1700
  let finalStatus = "finished";
1650
1701
  let finalText = "";
1651
- for await (const record of chunkALU3KC4G_cjs.parseSseStream(response.body, this.controller.signal)) {
1702
+ for await (const record of chunkBPN5ONSW_cjs.parseSseStream(response.body, this.controller.signal)) {
1652
1703
  const parsed = safeParse(record.data);
1653
1704
  if (parsed === void 0) continue;
1654
1705
  const update = this.applyRecord(record.event, parsed);
@@ -1757,7 +1808,7 @@ var CloudAgent = class {
1757
1808
  */
1758
1809
  isFixtureMode() {
1759
1810
  const apiKey = resolveApiKey(this.options.apiKey);
1760
- return chunkALU3KC4G_cjs.isFixtureApiKey(apiKey) && chunkALU3KC4G_cjs.getConfiguredBaseUrl() === void 0;
1811
+ return chunkBPN5ONSW_cjs.isFixtureApiKey(apiKey) && chunkBPN5ONSW_cjs.getConfiguredBaseUrl() === void 0;
1761
1812
  }
1762
1813
  // SE9 — integrated structured output; delegates to the shared helper.
1763
1814
  generate(message, options) {
@@ -1772,7 +1823,7 @@ var CloudAgent = class {
1772
1823
  }
1773
1824
  async send(message, options = {}) {
1774
1825
  if (options.tools !== void 0 && options.tools.length > 0) {
1775
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
1826
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
1776
1827
  "Custom inline tools are local-only in SDK v1.0 \u2014 cloud agents cannot serialize handler functions",
1777
1828
  { code: "cloud_custom_tools_rejected" }
1778
1829
  );
@@ -1808,7 +1859,7 @@ var CloudAgent = class {
1808
1859
  const userText = typeof message === "string" ? message : message.text;
1809
1860
  const systemPrompt = await this.resolveSystemPromptForSend(userText, options);
1810
1861
  const apiKey = resolveApiKey(this.options.apiKey);
1811
- const useRealRuntime = apiKey !== void 0 && !chunkALU3KC4G_cjs.isFixtureApiKey(apiKey) && chunkALU3KC4G_cjs.getConfiguredBaseUrl() !== void 0;
1862
+ const useRealRuntime = apiKey !== void 0 && !chunkBPN5ONSW_cjs.isFixtureApiKey(apiKey) && chunkBPN5ONSW_cjs.getConfiguredBaseUrl() !== void 0;
1812
1863
  return useRealRuntime ? createRealCloudRun({
1813
1864
  agentId: this.agentId,
1814
1865
  model: this.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },
@@ -1857,7 +1908,7 @@ var CloudAgent = class {
1857
1908
  listArtifacts() {
1858
1909
  if (!this.isFixtureMode()) {
1859
1910
  return Promise.reject(
1860
- new chunkMHCKWQR3_cjs.ConfigurationError(
1911
+ new chunkIHFNRNTJ_cjs.ConfigurationError(
1861
1912
  "Cloud runtime is pre-release. listArtifacts() will return real artifacts when Theo PaaS ships; today it is only available in fixture mode (theo_test_* keys).",
1862
1913
  { code: "cloud_runtime_pre_release" }
1863
1914
  )
@@ -1867,11 +1918,11 @@ var CloudAgent = class {
1867
1918
  }
1868
1919
  downloadArtifact(path) {
1869
1920
  try {
1870
- chunkYBFDBOUN_cjs.validateArtifactPath(path);
1921
+ chunk7YBJZS5P_cjs.validateArtifactPath(path);
1871
1922
  } catch (cause) {
1872
- if (cause instanceof chunkYBFDBOUN_cjs.PathTraversalError) {
1923
+ if (cause instanceof chunk7YBJZS5P_cjs.PathTraversalError) {
1873
1924
  return Promise.reject(
1874
- new chunkMHCKWQR3_cjs.ConfigurationError(`Artifact path must stay inside the workspace: ${path}`, {
1925
+ new chunkIHFNRNTJ_cjs.ConfigurationError(`Artifact path must stay inside the workspace: ${path}`, {
1875
1926
  code: "artifact_path_traversal",
1876
1927
  cause
1877
1928
  })
@@ -1881,7 +1932,7 @@ var CloudAgent = class {
1881
1932
  }
1882
1933
  if (!this.isFixtureMode()) {
1883
1934
  return Promise.reject(
1884
- new chunkMHCKWQR3_cjs.ConfigurationError(
1935
+ new chunkIHFNRNTJ_cjs.ConfigurationError(
1885
1936
  "Cloud runtime is pre-release. downloadArtifact() will fetch real PaaS artifacts when the cloud runtime ships; today it is only available in fixture mode (theo_test_* keys).",
1886
1937
  { code: "cloud_runtime_pre_release" }
1887
1938
  )
@@ -1890,7 +1941,7 @@ var CloudAgent = class {
1890
1941
  const match = buildFixtureArtifacts().find((artifact) => artifact.path === path);
1891
1942
  if (match === void 0) {
1892
1943
  return Promise.reject(
1893
- new chunkMHCKWQR3_cjs.UnknownAgentError(`Artifact ${path} not found`, { code: "unknown_artifact" })
1944
+ new chunkIHFNRNTJ_cjs.UnknownAgentError(`Artifact ${path} not found`, { code: "unknown_artifact" })
1894
1945
  );
1895
1946
  }
1896
1947
  return Promise.resolve(Buffer.from(`fixture artifact content for ${path}
@@ -1904,7 +1955,7 @@ var CloudAgent = class {
1904
1955
  * @public
1905
1956
  */
1906
1957
  runUntil() {
1907
- throw new chunkMHCKWQR3_cjs.UnsupportedRunOperationError(
1958
+ throw new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError(
1908
1959
  "Agent.runUntil() is not supported on cloud agents. Cloud runtime manages goal loops server-side. Use a local agent for autonomous Ralph loops.",
1909
1960
  "runUntil"
1910
1961
  );
@@ -1915,7 +1966,7 @@ var CloudAgent = class {
1915
1966
  * @public
1916
1967
  */
1917
1968
  fork() {
1918
- throw new chunkMHCKWQR3_cjs.UnsupportedRunOperationError(
1969
+ throw new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError(
1919
1970
  "Agent.fork() is not supported on cloud agents. Fork inheritance requires local credential + system-prompt access. Use a local agent.",
1920
1971
  "fork"
1921
1972
  );
@@ -1927,7 +1978,7 @@ var CloudAgent = class {
1927
1978
  * @public
1928
1979
  */
1929
1980
  runToCompletion() {
1930
- throw new chunkMHCKWQR3_cjs.UnsupportedRunOperationError(
1981
+ throw new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError(
1931
1982
  "Agent.runToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.",
1932
1983
  "runToCompletion"
1933
1984
  );
@@ -1939,7 +1990,7 @@ var CloudAgent = class {
1939
1990
  * @public
1940
1991
  */
1941
1992
  streamToCompletion() {
1942
- throw new chunkMHCKWQR3_cjs.UnsupportedRunOperationError(
1993
+ throw new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError(
1943
1994
  "Agent.streamToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.",
1944
1995
  "streamToCompletion"
1945
1996
  );
@@ -1953,7 +2004,7 @@ var CloudAgent = class {
1953
2004
  */
1954
2005
  usePersonality() {
1955
2006
  return Promise.reject(
1956
- new chunkMHCKWQR3_cjs.UnsupportedRunOperationError(
2007
+ new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError(
1957
2008
  "Agent.usePersonality() is not supported on cloud agents (pre-release). Use a local agent or wait for cloud GA.",
1958
2009
  "usePersonality"
1959
2010
  )
@@ -1981,7 +2032,7 @@ function validateCloudToolParity(options) {
1981
2032
  function rejectProcessors(options) {
1982
2033
  const hasProcessors = (options.inputProcessors?.length ?? 0) > 0 || (options.outputProcessors?.length ?? 0) > 0;
1983
2034
  if (hasProcessors) {
1984
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
2035
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
1985
2036
  "Cloud agents can't run guardrail processors \u2014 a Processor carries function handlers that don't survive serialization to PaaS. Run processors on a local agent, or move the guardrail into a server-side gateway in front of TheoCloud.",
1986
2037
  { code: "cloud_incompatible_function_resolver" }
1987
2038
  );
@@ -1989,7 +2040,7 @@ function rejectProcessors(options) {
1989
2040
  }
1990
2041
  function rejectFunctionSystemPrompt(options) {
1991
2042
  if (typeof options.systemPrompt === "function") {
1992
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
2043
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
1993
2044
  "Cloud agents require systemPrompt as a serializable string. SystemPromptResolver functions can't run on PaaS \u2014 resolve to a string before Agent.create() or move the dynamic logic into a hook rule.",
1994
2045
  { code: "cloud_incompatible_function_resolver" }
1995
2046
  );
@@ -1997,7 +2048,7 @@ function rejectFunctionSystemPrompt(options) {
1997
2048
  }
1998
2049
  function rejectFunctionSkills(options) {
1999
2050
  if (typeof options.skills === "function") {
2000
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
2051
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
2001
2052
  "Cloud agents require skills as a static settings object. SkillsResolver functions can't run on PaaS \u2014 resolve to a SkillsSettings object before Agent.create() or move the dynamic logic into a hook rule.",
2002
2053
  { code: "cloud_incompatible_function_resolver" }
2003
2054
  );
@@ -2009,7 +2060,7 @@ function rejectStdioMcpLocalPaths(options) {
2009
2060
  if (!isStdioCommandConfig(config)) continue;
2010
2061
  const command = config.command ?? "";
2011
2062
  if (isLocalPath(command)) {
2012
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
2063
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
2013
2064
  `MCP server "${name}" uses a local-FS command path (${command}). Cloud agents can't reach local binaries \u2014 use a bare command (npx, uvx, node, \u2026) that the PaaS VM image provides, or switch to an HTTP MCP server.`,
2014
2065
  { code: "cloud_incompatible_mcp_stdio_local" }
2015
2066
  );
@@ -2049,14 +2100,14 @@ async function readState(filePath) {
2049
2100
  try {
2050
2101
  parsed = JSON.parse(raw);
2051
2102
  } catch {
2052
- chunkFAY3QDGC_cjs.warnOnce(
2103
+ chunk6LGQECT7_cjs.warnOnce(
2053
2104
  "personality-store-json-parse",
2054
2105
  "[theokit-sdk] personality.json is malformed; treating as empty"
2055
2106
  );
2056
2107
  return emptyState();
2057
2108
  }
2058
2109
  if (!isStateV1(parsed)) {
2059
- chunkFAY3QDGC_cjs.warnOnce(
2110
+ chunk6LGQECT7_cjs.warnOnce(
2060
2111
  "personality-store-bad-version",
2061
2112
  `[theokit-sdk] personality.json has unknown version; treating as empty (file kept untouched)`
2062
2113
  );
@@ -2087,9 +2138,9 @@ var PersonalityStore = class {
2087
2138
  try {
2088
2139
  await this.#persist(agentId, slug);
2089
2140
  } catch (err) {
2090
- chunkFAY3QDGC_cjs.warnOnce(
2141
+ chunk6LGQECT7_cjs.warnOnce(
2091
2142
  `personality-store-persist-failure-${agentId}`,
2092
- `[theokit-sdk] personality persist failed for ${chunkLTCOPATU_cjs.redactSecrets(agentId)}: ${chunkLTCOPATU_cjs.redactSecrets(
2143
+ `[theokit-sdk] personality persist failed for ${chunkBCQ3E2ZG_cjs.redactSecrets(agentId)}: ${chunkBCQ3E2ZG_cjs.redactSecrets(
2093
2144
  err.message
2094
2145
  )}`
2095
2146
  );
@@ -2104,9 +2155,9 @@ var PersonalityStore = class {
2104
2155
  try {
2105
2156
  state = await readState(filePath);
2106
2157
  } catch (err) {
2107
- chunkFAY3QDGC_cjs.warnOnce(
2158
+ chunk6LGQECT7_cjs.warnOnce(
2108
2159
  `personality-store-hydrate-failure-${agentId}`,
2109
- `[theokit-sdk] personality hydrate failed for ${chunkLTCOPATU_cjs.redactSecrets(agentId)}: ${chunkLTCOPATU_cjs.redactSecrets(
2160
+ `[theokit-sdk] personality hydrate failed for ${chunkBCQ3E2ZG_cjs.redactSecrets(agentId)}: ${chunkBCQ3E2ZG_cjs.redactSecrets(
2110
2161
  err.message
2111
2162
  )}`
2112
2163
  );
@@ -2123,17 +2174,17 @@ var PersonalityStore = class {
2123
2174
  async #persist(agentId, slug) {
2124
2175
  const filePath = this.#filePath();
2125
2176
  await promises.mkdir(path.dirname(filePath), { recursive: true });
2126
- await chunkTQI3KRXZ_cjs.withFileLock(filePath, async () => {
2177
+ await chunkDMTZ3FII_cjs.withFileLock(filePath, async () => {
2127
2178
  const current = await readState(filePath);
2128
2179
  const nextAgents = { ...current.agents };
2129
2180
  if (slug === void 0) delete nextAgents[agentId];
2130
2181
  else nextAgents[agentId] = slug;
2131
2182
  const next = { version: SCHEMA_VERSION2, agents: nextAgents };
2132
- await chunkICYBIC6N_cjs.atomicWriteJson(filePath, next);
2183
+ await chunkDGLLVCNB_cjs.atomicWriteJson(filePath, next);
2133
2184
  });
2134
2185
  }
2135
2186
  #filePath() {
2136
- return path.join(chunkD4ZUJTFB_cjs.getTheokitHome(this.#cwd), FILE_NAME);
2187
+ return path.join(chunkLALG2K33_cjs.getTheokitHome(this.#cwd), FILE_NAME);
2137
2188
  }
2138
2189
  };
2139
2190
 
@@ -2156,7 +2207,7 @@ function createPluginContext() {
2156
2207
  },
2157
2208
  on(hook, handler) {
2158
2209
  if (typeof handler !== "function") {
2159
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] ignoring non-function handler for hook "${hook}"
2210
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] ignoring non-function handler for hook "${hook}"
2160
2211
  `);
2161
2212
  return;
2162
2213
  }
@@ -2209,7 +2260,7 @@ var PluginManager = class {
2209
2260
  const seen = /* @__PURE__ */ new Set();
2210
2261
  for (const plugin of plugins) {
2211
2262
  if (seen.has(plugin.name)) {
2212
- chunkLTCOPATU_cjs.diag(
2263
+ chunkBCQ3E2ZG_cjs.diag(
2213
2264
  `[theokit-sdk] duplicate plugin name "${plugin.name}" \u2014 both will register independently
2214
2265
  `
2215
2266
  );
@@ -2236,7 +2287,7 @@ var PluginManager = class {
2236
2287
  */
2237
2288
  async register(plugin) {
2238
2289
  if (plugin.kind !== "general") {
2239
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
2290
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
2240
2291
  `late register supports general plugins only (got "${plugin.kind}" for "${plugin.name}")`,
2241
2292
  { code: "plugin_late_register_kind" }
2242
2293
  );
@@ -2293,7 +2344,7 @@ var PluginManager = class {
2293
2344
  parts.push(result.recalledContext);
2294
2345
  }
2295
2346
  } catch (err) {
2296
- chunkLTCOPATU_cjs.diag(
2347
+ chunkBCQ3E2ZG_cjs.diag(
2297
2348
  `[theokit-sdk] pre_user_send hook failed: ${err instanceof Error ? err.message : String(err)}
2298
2349
  `
2299
2350
  );
@@ -2321,7 +2372,7 @@ var PluginManager = class {
2321
2372
  try {
2322
2373
  await h(ctx);
2323
2374
  } catch (err) {
2324
- chunkLTCOPATU_cjs.diag(
2375
+ chunkBCQ3E2ZG_cjs.diag(
2325
2376
  `[theokit-sdk] post_assistant_reply hook failed: ${err instanceof Error ? err.message : String(err)}
2326
2377
  `
2327
2378
  );
@@ -2337,7 +2388,7 @@ var PluginManager = class {
2337
2388
  try {
2338
2389
  await h(ctx);
2339
2390
  } catch (err) {
2340
- chunkLTCOPATU_cjs.diag(
2391
+ chunkBCQ3E2ZG_cjs.diag(
2341
2392
  `[theokit-sdk] ${name} hook failed: ${err instanceof Error ? err.message : String(err)}
2342
2393
  `
2343
2394
  );
@@ -2352,7 +2403,7 @@ var PluginManager = class {
2352
2403
  const out = await h(current, ctx);
2353
2404
  if (out !== void 0) current = out;
2354
2405
  } catch (err) {
2355
- chunkLTCOPATU_cjs.diag(
2406
+ chunkBCQ3E2ZG_cjs.diag(
2356
2407
  `[theokit-sdk] ${name} hook failed: ${err instanceof Error ? err.message : String(err)}
2357
2408
  `
2358
2409
  );
@@ -2494,7 +2545,7 @@ var HooksExecutor = class {
2494
2545
  this.config = {};
2495
2546
  return;
2496
2547
  }
2497
- this.config = await chunkFAY3QDGC_cjs.loadHookConfig(this.cwd);
2548
+ this.config = await chunk6LGQECT7_cjs.loadHookConfig(this.cwd);
2498
2549
  }
2499
2550
  /** Fire every hook registered for `event` and aggregate the decisions. */
2500
2551
  async run(payload) {
@@ -2600,11 +2651,11 @@ function buildContextBudgetEvent(model, resolved) {
2600
2651
  // src/internal/runtime/lifecycle/post-run-lifecycle.ts
2601
2652
  function resolveWindowForRun(model, contextWindow) {
2602
2653
  const override = contextWindow !== void 0 && contextWindow > 0 ? contextWindow : void 0;
2603
- return chunk4YB7B3RP_cjs.resolveEffectiveContextWindow({
2654
+ return chunkJ6T5LWJ4_cjs.resolveEffectiveContextWindow({
2604
2655
  ...override !== void 0 ? { override } : {},
2605
- catalog: chunk56ZM6P7Z_cjs.getCatalogModelInfo(model)?.limit?.context,
2606
- margin: chunk4YB7B3RP_cjs.CONTEXT_WINDOW_MARGIN,
2607
- floor: chunk4YB7B3RP_cjs.CONTEXT_WINDOW_FLOOR
2656
+ catalog: chunkG4XUXSRN_cjs.getCatalogModelInfo(model)?.limit?.context,
2657
+ margin: chunkJ6T5LWJ4_cjs.CONTEXT_WINDOW_MARGIN,
2658
+ floor: chunkJ6T5LWJ4_cjs.CONTEXT_WINDOW_FLOOR
2608
2659
  });
2609
2660
  }
2610
2661
  async function runPostRunLifecycle(inputs) {
@@ -2628,32 +2679,32 @@ async function runPostRunLifecycle(inputs) {
2628
2679
  try {
2629
2680
  const parcial = await safeConversation(run);
2630
2681
  if (parcial !== void 0) {
2631
- chunkH5YVJB4K_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
2682
+ chunkDCXRHCZJ_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
2632
2683
  userText,
2633
2684
  conversation: parcial
2634
2685
  });
2635
2686
  }
2636
2687
  } catch (cause) {
2637
2688
  const msg = cause instanceof Error ? cause.message : String(cause);
2638
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] partial transcript write failed (${agentId}): ${msg}
2689
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] partial transcript write failed (${agentId}): ${msg}
2639
2690
  `);
2640
2691
  }
2641
- await chunkH5YVJB4K_cjs.flushSessionWrites();
2692
+ await chunkDCXRHCZJ_cjs.flushSessionWrites();
2642
2693
  return;
2643
2694
  }
2644
2695
  if (result.result !== void 0) {
2645
- chunkH5YVJB4K_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
2696
+ chunkDCXRHCZJ_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
2646
2697
  }
2647
2698
  const conversation = await safeConversation(run);
2648
2699
  const resolvedWindow = resolveWindowForRun(model, contextWindow);
2649
- const janelaEfetiva = resolvedWindow.window;
2700
+ const effectiveWindow = resolvedWindow.window;
2650
2701
  const budgetEvent = buildContextBudgetEvent(model, resolvedWindow);
2651
2702
  if (budgetEvent !== void 0 && onRunEvent !== void 0) {
2652
- chunk6EDQBX7U_cjs.emitRunEvent(onRunEvent, budgetEvent);
2703
+ chunkN475ETD6_cjs.emitRunEvent(onRunEvent, budgetEvent);
2653
2704
  }
2654
2705
  const lastRequestUsage = result.usage?.requests?.at(-1)?.totalTokens;
2655
2706
  const usageForTrigger = lastRequestUsage ?? result.usage?.totalTokens;
2656
- chunkH5YVJB4K_cjs.persistTurnToTranscript(
2707
+ chunkDCXRHCZJ_cjs.persistTurnToTranscript(
2657
2708
  sessionStore,
2658
2709
  { cwd: workspaceCwd, agentId, model },
2659
2710
  agentId,
@@ -2662,16 +2713,16 @@ async function runPostRunLifecycle(inputs) {
2662
2713
  conversation,
2663
2714
  autoCompact: {
2664
2715
  usageTotal: usageForTrigger,
2665
- // A janela EFETIVA (após override, clamp e margem) — não a declarada. Trocar por
2666
- // `contextWindow` aqui orçaria contra um número que o clamp rejeitou.
2667
- contextWindow: janelaEfetiva,
2668
- summarize: chunkALU3KC4G_cjs.buildDefaultSummarizer({
2716
+ // The EFFECTIVE window (after override, clamp and margin) — not the declared one. Swapping for
2717
+ // `contextWindow` here would budget against a number the clamp already rejected.
2718
+ contextWindow: effectiveWindow,
2719
+ summarize: chunkBPN5ONSW_cjs.buildDefaultSummarizer({
2669
2720
  agentModel: model,
2670
2721
  ...inputs.apiKey !== void 0 ? { apiKey: inputs.apiKey } : {}
2671
2722
  })
2672
2723
  }
2673
2724
  },
2674
- onRunEvent !== void 0 ? () => chunk6EDQBX7U_cjs.emitRunEvent(onRunEvent, { type: "compact_boundary", trigger: "auto" }) : void 0
2725
+ onRunEvent !== void 0 ? () => chunkN475ETD6_cjs.emitRunEvent(onRunEvent, { type: "compact_boundary", trigger: "auto" }) : void 0
2675
2726
  );
2676
2727
  if (result.status === "finished" && result.result !== void 0) {
2677
2728
  const summaryArgs = {
@@ -2687,14 +2738,14 @@ async function runPostRunLifecycle(inputs) {
2687
2738
  if (memoryProvider?.recordSessionSummary !== void 0) {
2688
2739
  await memoryProvider.recordSessionSummary(summaryArgs);
2689
2740
  } else {
2690
- await chunk2423XDPT_cjs.writeSessionSummary(summaryArgs);
2741
+ await chunkCN6UX5EV_cjs.writeSessionSummary(summaryArgs);
2691
2742
  }
2692
2743
  if (!shouldUsePortMemoryPath()) {
2693
2744
  void memoryGlue.syncIfReady();
2694
2745
  }
2695
2746
  } catch (cause) {
2696
2747
  const message = cause instanceof Error ? cause.message : String(cause);
2697
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] session summary write failed (${result.id}): ${message}
2748
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] session summary write failed (${result.id}): ${message}
2698
2749
  `);
2699
2750
  }
2700
2751
  }
@@ -2707,7 +2758,7 @@ async function runPostRunLifecycle(inputs) {
2707
2758
  agentId,
2708
2759
  runId: result.id
2709
2760
  });
2710
- await chunkH5YVJB4K_cjs.flushSessionWrites();
2761
+ await chunkDCXRHCZJ_cjs.flushSessionWrites();
2711
2762
  }
2712
2763
  async function safeConversation(run) {
2713
2764
  try {
@@ -2782,7 +2833,7 @@ var warned = /* @__PURE__ */ new Set();
2782
2833
  function warnDoubleReasoningOnce() {
2783
2834
  if (warned.has("double-reasoning")) return;
2784
2835
  warned.add("double-reasoning");
2785
- chunkLTCOPATU_cjs.diag(
2836
+ chunkBCQ3E2ZG_cjs.diag(
2786
2837
  "[theokit-sdk] `reasoning: true` skipped \u2014 a native reasoning model is configured (model.params thinking/reasoning); native reasoning wins. Remove one to silence.\n"
2787
2838
  );
2788
2839
  }
@@ -2815,9 +2866,9 @@ var SkillsManager = class {
2815
2866
  }
2816
2867
  async refresh() {
2817
2868
  const skillsRoot = this.skillsDir ?? path.join(this.cwd, ".theokit", "skills");
2818
- const discovered = await chunkQUFSDDNU_cjs.discoverSkills(skillsRoot, {
2869
+ const discovered = await chunkE4IUN3JB_cjs.discoverSkills(skillsRoot, {
2819
2870
  onInvalidSkill: (info) => {
2820
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] skill ${info.name} skipped (${info.code}): ${info.message}
2871
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] skill ${info.name} skipped (${info.code}): ${info.message}
2821
2872
  `);
2822
2873
  }
2823
2874
  });
@@ -2841,7 +2892,7 @@ var SkillsManager = class {
2841
2892
  async get(name) {
2842
2893
  const skill = this.skills.find((s) => s.name === name);
2843
2894
  if (skill === void 0) return void 0;
2844
- const instructions = typeof skill.instructions === "string" ? skill.instructions : chunkQUFSDDNU_cjs.stripSkillFrontmatter(await promises.readFile(skill.source, "utf8"));
2895
+ const instructions = typeof skill.instructions === "string" ? skill.instructions : chunkE4IUN3JB_cjs.stripSkillFrontmatter(await promises.readFile(skill.source, "utf8"));
2845
2896
  const references = skill.references;
2846
2897
  return {
2847
2898
  name: skill.name,
@@ -2927,7 +2978,7 @@ async function safeCall(fn, fallback, label = "safeCall") {
2927
2978
  return await fn();
2928
2979
  } catch (cause) {
2929
2980
  const message = cause instanceof Error ? cause.message : String(cause);
2930
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] ${label} failed: ${message}
2981
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] ${label} failed: ${message}
2931
2982
  `);
2932
2983
  return fallback;
2933
2984
  }
@@ -2941,7 +2992,7 @@ var ActiveMemoryPromptProvider = class {
2941
2992
  if (ctx.activeMemorySummary === void 0 || ctx.activeMemorySummary.length === 0) {
2942
2993
  return Promise.resolve(void 0);
2943
2994
  }
2944
- const body = chunkQUFSDDNU_cjs.escapeBlockBody(ctx.activeMemorySummary);
2995
+ const body = chunkE4IUN3JB_cjs.escapeBlockBody(ctx.activeMemorySummary);
2945
2996
  return Promise.resolve(`<active-memory>
2946
2997
  ${body}
2947
2998
  </active-memory>`);
@@ -2994,7 +3045,7 @@ function formatSource(name, tokens) {
2994
3045
  if (tokens.length === 0) {
2995
3046
  return ` <source name="${escapeAttribute(name)}" />`;
2996
3047
  }
2997
- const body = chunkQUFSDDNU_cjs.escapeBlockBody(tokens.join(" "));
3048
+ const body = chunkE4IUN3JB_cjs.escapeBlockBody(tokens.join(" "));
2998
3049
  return ` <source name="${escapeAttribute(name)}">
2999
3050
  ${body}
3000
3051
  </source>`;
@@ -3010,7 +3061,7 @@ var MemoryPromptProvider = class {
3010
3061
  contribute(ctx) {
3011
3062
  if (ctx.memoryAutoInject === false) return Promise.resolve(void 0);
3012
3063
  if (ctx.memory.length === 0) return Promise.resolve(void 0);
3013
- const lines = ctx.memory.map((fact) => ` - ${chunkQUFSDDNU_cjs.escapeBlockBody(fact.text)}`);
3064
+ const lines = ctx.memory.map((fact) => ` - ${chunkE4IUN3JB_cjs.escapeBlockBody(fact.text)}`);
3014
3065
  return Promise.resolve(`<memory>
3015
3066
  ${lines.join("\n")}
3016
3067
  </memory>`);
@@ -3032,7 +3083,7 @@ var SkillsPromptProvider = class {
3032
3083
  priority = 20;
3033
3084
  contribute(ctx) {
3034
3085
  if (ctx.skillsAutoInject === false) return Promise.resolve(void 0);
3035
- return Promise.resolve(chunkQUFSDDNU_cjs.buildSkillsBlock(ctx.skills));
3086
+ return Promise.resolve(chunkE4IUN3JB_cjs.buildSkillsBlock(ctx.skills));
3036
3087
  }
3037
3088
  };
3038
3089
 
@@ -3044,7 +3095,7 @@ var SystemPromptPipeline = class _SystemPromptPipeline {
3044
3095
  for (const p of providers) {
3045
3096
  const key = `${p.priority}:${p.id}`;
3046
3097
  if (seen.has(key)) {
3047
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Duplicate system-prompt provider ${key}`, {
3098
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Duplicate system-prompt provider ${key}`, {
3048
3099
  code: "pipeline_duplicate_provider"
3049
3100
  });
3050
3101
  }
@@ -3091,7 +3142,7 @@ function validateAgentOptions(options) {
3091
3142
  ensureRuntimeShape(options);
3092
3143
  if (options.local !== void 0) {
3093
3144
  if (options.model === void 0) {
3094
- throw new chunkMHCKWQR3_cjs.ConfigurationError("Local agents require a model selection", {
3145
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError("Local agents require a model selection", {
3095
3146
  code: "missing_model"
3096
3147
  });
3097
3148
  }
@@ -3115,7 +3166,7 @@ function validateCredentialPoolShape(options) {
3115
3166
  ([, arr]) => Array.isArray(arr) && arr.some((k) => typeof k === "string" && k.length > 0)
3116
3167
  );
3117
3168
  if (populated.length === 0) return;
3118
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3169
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3119
3170
  "Ambiguous credential configuration: use either `apiKey: '...'` (single-key, simplest) OR `apiKeys: { provider: [...] }` (multi-key pool), not both.",
3120
3171
  { code: "credential_pool_ambiguous" }
3121
3172
  );
@@ -3124,7 +3175,7 @@ function validatePlugins(options) {
3124
3175
  const plugins = options.plugins;
3125
3176
  if (plugins?.paths === void 0) return;
3126
3177
  if (options.cloud !== void 0 && plugins.paths.length > 0) {
3127
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3178
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3128
3179
  "Cloud agents require committed plugin manifests; local plugin paths are not supported",
3129
3180
  { code: "cloud_plugin_path_rejected" }
3130
3181
  );
@@ -3132,7 +3183,7 @@ function validatePlugins(options) {
3132
3183
  }
3133
3184
  function ensureRuntimeShape(options) {
3134
3185
  if (options.local !== void 0 && options.cloud !== void 0) {
3135
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3186
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3136
3187
  "Pass either local or cloud \u2014 they are mutually exclusive runtimes",
3137
3188
  { code: "runtime_exclusive" }
3138
3189
  );
@@ -3140,7 +3191,7 @@ function ensureRuntimeShape(options) {
3140
3191
  }
3141
3192
  function rejectProgrammaticHooks(options) {
3142
3193
  if (options.hooks !== void 0) {
3143
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3194
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3144
3195
  "Programmatic hooks are not supported \u2014 hooks are file-based only (.theokit/hooks.json)",
3145
3196
  { code: "programmatic_hooks_rejected" }
3146
3197
  );
@@ -3150,7 +3201,7 @@ function validateCloud(cloud) {
3150
3201
  if (cloud.envVars !== void 0) {
3151
3202
  for (const key of Object.keys(cloud.envVars)) {
3152
3203
  if (key.startsWith("THEOKIT_")) {
3153
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3204
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3154
3205
  `Cloud envVars cannot use the reserved THEOKIT_ prefix (got "${key}")`,
3155
3206
  { code: "reserved_env_prefix" }
3156
3207
  );
@@ -3162,7 +3213,7 @@ function validateMcpServers(options) {
3162
3213
  if (options.mcpServers === void 0) return;
3163
3214
  for (const [name, config] of Object.entries(options.mcpServers)) {
3164
3215
  if (options.cloud !== void 0 && isStdioWithCwd(config)) {
3165
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3216
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3166
3217
  `MCP server "${name}" uses stdio with cwd, which is rejected for cloud agents`,
3167
3218
  { code: "cloud_stdio_cwd_rejected" }
3168
3219
  );
@@ -3181,12 +3232,12 @@ function validateSubagents(agents2) {
3181
3232
  if (agents2 === void 0) return;
3182
3233
  for (const [name, definition] of Object.entries(agents2)) {
3183
3234
  if (typeof definition.description !== "string" || definition.description.length === 0) {
3184
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Subagent "${name}" requires a non-empty description`, {
3235
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Subagent "${name}" requires a non-empty description`, {
3185
3236
  code: "subagent_missing_description"
3186
3237
  });
3187
3238
  }
3188
3239
  if (typeof definition.prompt !== "string" || definition.prompt.length === 0) {
3189
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Subagent "${name}" requires a non-empty prompt`, {
3240
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Subagent "${name}" requires a non-empty prompt`, {
3190
3241
  code: "subagent_missing_prompt"
3191
3242
  });
3192
3243
  }
@@ -3199,7 +3250,7 @@ function validateToolCatalog(tools) {
3199
3250
  for (const tool of tools) {
3200
3251
  validateSingleTool(tool);
3201
3252
  if (seen.has(tool.name)) {
3202
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Duplicate custom tool name "${tool.name}"`, {
3253
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Duplicate custom tool name "${tool.name}"`, {
3203
3254
  code: "duplicate_tool_name"
3204
3255
  });
3205
3256
  }
@@ -3210,7 +3261,7 @@ function validateCustomTools(options) {
3210
3261
  const tools = options.tools;
3211
3262
  if (tools === void 0 || tools.length === 0) return;
3212
3263
  if (options.cloud !== void 0) {
3213
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3264
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3214
3265
  "Custom inline tools are local-only in SDK v1.0 \u2014 cloud agents cannot serialize handler functions",
3215
3266
  { code: "cloud_custom_tools_rejected" }
3216
3267
  );
@@ -3222,25 +3273,25 @@ function validateSingleTool(tool) {
3222
3273
  validateToolDescription(tool);
3223
3274
  validateToolSchema(tool);
3224
3275
  if (typeof tool.handler !== "function") {
3225
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Custom tool "${tool.name}" requires a handler function`, {
3276
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Custom tool "${tool.name}" requires a handler function`, {
3226
3277
  code: "tool_missing_handler"
3227
3278
  });
3228
3279
  }
3229
3280
  }
3230
3281
  function validateToolName(tool) {
3231
3282
  if (typeof tool.name !== "string" || tool.name.length === 0) {
3232
- throw new chunkMHCKWQR3_cjs.ConfigurationError("Custom tool requires a non-empty name", {
3283
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError("Custom tool requires a non-empty name", {
3233
3284
  code: "tool_missing_name"
3234
3285
  });
3235
3286
  }
3236
3287
  if (!TOOL_NAME_PATTERN.test(tool.name)) {
3237
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3288
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3238
3289
  `Custom tool name "${tool.name}" must match /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/`,
3239
3290
  { code: "tool_invalid_name" }
3240
3291
  );
3241
3292
  }
3242
3293
  if (RESERVED_TOOL_NAMES.has(tool.name) || tool.name.startsWith("mcp_")) {
3243
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3294
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3244
3295
  `Custom tool name "${tool.name}" collides with a reserved SDK tool name`,
3245
3296
  { code: "tool_reserved_name" }
3246
3297
  );
@@ -3248,7 +3299,7 @@ function validateToolName(tool) {
3248
3299
  }
3249
3300
  function validateToolDescription(tool) {
3250
3301
  if (typeof tool.description !== "string" || tool.description.length === 0) {
3251
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Custom tool "${tool.name}" requires a non-empty description`, {
3302
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Custom tool "${tool.name}" requires a non-empty description`, {
3252
3303
  code: "tool_missing_description"
3253
3304
  });
3254
3305
  }
@@ -3256,12 +3307,12 @@ function validateToolDescription(tool) {
3256
3307
  function validateToolSchema(tool) {
3257
3308
  const schema = tool.inputSchema;
3258
3309
  if (schema === null || schema === void 0 || typeof schema !== "object") {
3259
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Custom tool "${tool.name}" requires an inputSchema object`, {
3310
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Custom tool "${tool.name}" requires an inputSchema object`, {
3260
3311
  code: "tool_missing_schema"
3261
3312
  });
3262
3313
  }
3263
3314
  if (schema.type !== "object") {
3264
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3315
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3265
3316
  `Custom tool "${tool.name}" inputSchema must declare \`type: "object"\``,
3266
3317
  { code: "tool_invalid_schema_type" }
3267
3318
  );
@@ -3272,7 +3323,7 @@ function validateMemory(options) {
3272
3323
  if (memory?.storePath === void 0) return;
3273
3324
  const storePath = memory.storePath;
3274
3325
  if (storePath.includes("..") || storePath.startsWith("/") || /^[A-Z]:/i.test(storePath)) {
3275
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3326
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3276
3327
  `Memory storePath must stay inside the workspace; got "${storePath}"`,
3277
3328
  { code: "memory_path_traversal" }
3278
3329
  );
@@ -3294,7 +3345,7 @@ var HISTOGRAM_NAMES = {
3294
3345
  };
3295
3346
  function safeRequire(moduleName) {
3296
3347
  try {
3297
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-W52DKZBR.cjs', document.baseURI).href)));
3348
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-INSFS5GT.cjs', document.baseURI).href)));
3298
3349
  return r(moduleName);
3299
3350
  } catch {
3300
3351
  return void 0;
@@ -3373,7 +3424,7 @@ var langfuseAdapter = {
3373
3424
  }
3374
3425
  }
3375
3426
  if (lf.LangfuseSpanProcessor === void 0) {
3376
- chunkLTCOPATU_cjs.diag(
3427
+ chunkBCQ3E2ZG_cjs.diag(
3377
3428
  "[theokit-sdk] @langfuse/node detected but LangfuseSpanProcessor not found (v2?). Use Langfuse v3+ for auto-instrumentation.\n"
3378
3429
  );
3379
3430
  return;
@@ -3502,11 +3553,11 @@ function tryAutoRegisterAdapters(settings) {
3502
3553
  try {
3503
3554
  adapter.register();
3504
3555
  registered.add(adapter.moduleName);
3505
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] telemetry: ${adapter.displayName} auto-instrumented.
3556
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] telemetry: ${adapter.displayName} auto-instrumented.
3506
3557
  `);
3507
3558
  } catch (cause) {
3508
3559
  const message = cause instanceof Error ? cause.message : String(cause);
3509
- chunkLTCOPATU_cjs.diag(
3560
+ chunkBCQ3E2ZG_cjs.diag(
3510
3561
  `[theokit-sdk] telemetry: ${adapter.displayName} detected but failed to register: ${message}
3511
3562
  `
3512
3563
  );
@@ -3519,7 +3570,7 @@ var cachedOtel;
3519
3570
  function loadOtel() {
3520
3571
  if (cachedOtel === void 0) {
3521
3572
  try {
3522
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-W52DKZBR.cjs', document.baseURI).href)));
3573
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-INSFS5GT.cjs', document.baseURI).href)));
3523
3574
  const mod = r("@opentelemetry/api");
3524
3575
  cachedOtel = mod;
3525
3576
  } catch {
@@ -3562,7 +3613,7 @@ function safe(op, fallback) {
3562
3613
  if (!warnedOnce) {
3563
3614
  warnedOnce = true;
3564
3615
  const message = cause instanceof Error ? cause.message : String(cause);
3565
- chunkLTCOPATU_cjs.diag(
3616
+ chunkBCQ3E2ZG_cjs.diag(
3566
3617
  `[theokit-sdk] telemetry exporter error (suppressed; agent.send continues): ${message}
3567
3618
  `
3568
3619
  );
@@ -3576,7 +3627,7 @@ function createTelemetry(settings) {
3576
3627
  if (otel === null) {
3577
3628
  if (!warnedOnce) {
3578
3629
  warnedOnce = true;
3579
- chunkLTCOPATU_cjs.diag(
3630
+ chunkBCQ3E2ZG_cjs.diag(
3580
3631
  "[theokit-sdk] telemetry.enabled = true but `@opentelemetry/api` is not installed; telemetry is a no-op.\n"
3581
3632
  );
3582
3633
  }
@@ -3670,12 +3721,12 @@ function wrapSpan(span, openSpans) {
3670
3721
  }
3671
3722
  function redactAttrValue(value) {
3672
3723
  if (typeof value !== "string") return value;
3673
- return chunkLTCOPATU_cjs.redactSecrets(value);
3724
+ return chunkBCQ3E2ZG_cjs.redactSecrets(value);
3674
3725
  }
3675
3726
  function redactAttrs(attrs) {
3676
3727
  const out = {};
3677
3728
  for (const [k, v] of Object.entries(attrs)) {
3678
- out[k] = typeof v === "string" ? chunkLTCOPATU_cjs.redactSecrets(v) : v;
3729
+ out[k] = typeof v === "string" ? chunkBCQ3E2ZG_cjs.redactSecrets(v) : v;
3679
3730
  }
3680
3731
  return out;
3681
3732
  }
@@ -3757,10 +3808,10 @@ async function loadMarkdownEntities(opts) {
3757
3808
  const raw = await promises.readFile(resolved.source, "utf8").catch(() => null);
3758
3809
  if (raw === null) continue;
3759
3810
  const split = splitFrontmatter(raw, resolved.source, errorCodePrefix);
3760
- const fields = chunk7DXLNNKH_cjs.parseSimpleYaml(split.frontmatter);
3811
+ const fields = chunkG2Q3ZC6C_cjs.parseSimpleYaml(split.frontmatter);
3761
3812
  const parsed = schema.safeParse(fields);
3762
3813
  if (!parsed.success) {
3763
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3814
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3764
3815
  `Invalid frontmatter in ${resolved.source}: ${parsed.error.message}`,
3765
3816
  { code: `${errorCodePrefix}_frontmatter_invalid` }
3766
3817
  );
@@ -3778,13 +3829,13 @@ async function assertFileSizeUnderCap(source, errorCodePrefix) {
3778
3829
  try {
3779
3830
  const info = await promises.stat(source);
3780
3831
  if (info.size > MAX_MD_FILE_BYTES) {
3781
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3832
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3782
3833
  `Config file ${source} exceeds 1 MB size limit (${info.size} bytes). Reduce the file or split into multiple entities.`,
3783
3834
  { code: `${errorCodePrefix}_file_too_large` }
3784
3835
  );
3785
3836
  }
3786
3837
  } catch (cause) {
3787
- if (cause instanceof chunkMHCKWQR3_cjs.ConfigurationError) throw cause;
3838
+ if (cause instanceof chunkIHFNRNTJ_cjs.ConfigurationError) throw cause;
3788
3839
  }
3789
3840
  }
3790
3841
  async function readDirSafe(dir, errorCodePrefix) {
@@ -3793,7 +3844,7 @@ async function readDirSafe(dir, errorCodePrefix) {
3793
3844
  } catch (cause) {
3794
3845
  const code = cause.code;
3795
3846
  if (code === "ENOENT") return null;
3796
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Failed to read ${dir}`, {
3847
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Failed to read ${dir}`, {
3797
3848
  code: `${errorCodePrefix}_dir_read_error`,
3798
3849
  cause
3799
3850
  });
@@ -3810,7 +3861,7 @@ function resolveEntryPath(entry, pattern, dir) {
3810
3861
  function splitFrontmatter(raw, source, errorCodePrefix) {
3811
3862
  const match = /^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/.exec(raw);
3812
3863
  if (match === null) {
3813
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
3864
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
3814
3865
  `Missing or malformed frontmatter in ${source} (expected \`---\` delimited block at file head)`,
3815
3866
  { code: `${errorCodePrefix}_missing_frontmatter` }
3816
3867
  );
@@ -4294,7 +4345,7 @@ async function loadContextConfig(cwd) {
4294
4345
  });
4295
4346
  if (mdEntities.length > 0) {
4296
4347
  if (fs.existsSync(jsonPath)) {
4297
- chunkFAY3QDGC_cjs.warnOnce(
4348
+ chunk6LGQECT7_cjs.warnOnce(
4298
4349
  "context-both-present",
4299
4350
  "[theokit-sdk] both .theokit/context/ and .theokit/context.json detected \u2014 using markdown; remove context.json"
4300
4351
  );
@@ -4304,7 +4355,7 @@ async function loadContextConfig(cwd) {
4304
4355
  };
4305
4356
  }
4306
4357
  if (!fs.existsSync(jsonPath)) return { sources: [] };
4307
- chunkFAY3QDGC_cjs.warnOnce(
4358
+ chunk6LGQECT7_cjs.warnOnce(
4308
4359
  "context-json-deprecated",
4309
4360
  "[theokit-sdk] .theokit/context.json is deprecated; migrate to .theokit/context/<name>.md via theokit-migrate-config"
4310
4361
  );
@@ -4312,7 +4363,7 @@ async function loadContextConfig(cwd) {
4312
4363
  try {
4313
4364
  raw = await promises.readFile(jsonPath, "utf8");
4314
4365
  } catch (cause) {
4315
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Failed to read context config: ${jsonPath}`, {
4366
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Failed to read context config: ${jsonPath}`, {
4316
4367
  code: "context_read_error",
4317
4368
  cause
4318
4369
  });
@@ -4324,13 +4375,13 @@ function parseConfig(raw, configPath) {
4324
4375
  try {
4325
4376
  parsed = JSON.parse(raw);
4326
4377
  } catch (cause) {
4327
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Invalid JSON in context config: ${configPath}`, {
4378
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Invalid JSON in context config: ${configPath}`, {
4328
4379
  code: "context_json_invalid",
4329
4380
  cause
4330
4381
  });
4331
4382
  }
4332
4383
  if (!parsed || typeof parsed !== "object") {
4333
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Context config must be an object: ${configPath}`, {
4384
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Context config must be an object: ${configPath}`, {
4334
4385
  code: "context_config_shape"
4335
4386
  });
4336
4387
  }
@@ -4345,7 +4396,7 @@ function parseConfig(raw, configPath) {
4345
4396
  }
4346
4397
  function readSources(sourcesRaw, configPath) {
4347
4398
  if (!Array.isArray(sourcesRaw)) {
4348
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Context config sources must be an array: ${configPath}`, {
4399
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Context config sources must be an array: ${configPath}`, {
4349
4400
  code: "context_sources_shape"
4350
4401
  });
4351
4402
  }
@@ -4443,7 +4494,7 @@ var PluginsManager = class {
4443
4494
  async refresh() {
4444
4495
  this.plugins = [];
4445
4496
  const pluginsRoot = path.join(this.cwd, ".theokit", "plugins");
4446
- const entries = await chunk7DXLNNKH_cjs.readWorkspaceDir(pluginsRoot, "plugins_read_error", "plugins directory");
4497
+ const entries = await chunkG2Q3ZC6C_cjs.readWorkspaceDir(pluginsRoot, "plugins_read_error", "plugins directory");
4447
4498
  for (const entry of entries) {
4448
4499
  if (!entry.isDirectory()) continue;
4449
4500
  const folderName = entry.name;
@@ -4451,13 +4502,13 @@ var PluginsManager = class {
4451
4502
  const jsonPath = path.join(pluginsRoot, folderName, "plugin.json");
4452
4503
  const metadata = fs.existsSync(mdPath) ? await loadPluginManifestFromMarkdown(pluginsRoot, folderName) : await loadPluginManifestFromJson(jsonPath, folderName);
4453
4504
  if (fs.existsSync(mdPath) && fs.existsSync(jsonPath)) {
4454
- chunkFAY3QDGC_cjs.warnOnce(
4505
+ chunk6LGQECT7_cjs.warnOnce(
4455
4506
  `plugin-${folderName}-both`,
4456
4507
  `[theokit-sdk] both ${folderName}/PLUGIN.md and ${folderName}/plugin.json detected \u2014 using markdown; remove plugin.json`
4457
4508
  );
4458
4509
  }
4459
4510
  if (!fs.existsSync(mdPath) && fs.existsSync(jsonPath)) {
4460
- chunkFAY3QDGC_cjs.warnOnce(
4511
+ chunk6LGQECT7_cjs.warnOnce(
4461
4512
  "plugin-json-deprecated",
4462
4513
  "[theokit-sdk] plugin.json manifests are deprecated; migrate to PLUGIN.md via theokit-migrate-config"
4463
4514
  );
@@ -4475,11 +4526,11 @@ var PluginsManager = class {
4475
4526
  const entry = metadata.entry;
4476
4527
  if (entry === void 0) return;
4477
4528
  const pluginRoot = path.join(this.cwd, ".theokit", "plugins", folderName);
4478
- const entryPath = chunkYBFDBOUN_cjs.safePathJoin(pluginRoot, entry);
4529
+ const entryPath = chunk7YBJZS5P_cjs.safePathJoin(pluginRoot, entry);
4479
4530
  try {
4480
4531
  await promises.readFile(entryPath, "utf8");
4481
4532
  } catch (cause) {
4482
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${metadata.name} entry file is missing: ${entry}`, {
4533
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${metadata.name} entry file is missing: ${entry}`, {
4483
4534
  code: "plugin_entry_missing",
4484
4535
  cause
4485
4536
  });
@@ -4488,7 +4539,7 @@ var PluginsManager = class {
4488
4539
  assertCloudRules() {
4489
4540
  if (!this.cloud) return;
4490
4541
  if (this.localPaths !== void 0 && this.localPaths.length > 0) {
4491
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
4542
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
4492
4543
  "Cloud agents reject local plugin paths \u2014 plugins must come from committed repo files",
4493
4544
  { code: "cloud_plugin_path_rejected" }
4494
4545
  );
@@ -4500,7 +4551,7 @@ async function loadPluginManifestFromJson(manifestPath, folderName) {
4500
4551
  try {
4501
4552
  raw = await promises.readFile(manifestPath, "utf8");
4502
4553
  } catch (cause) {
4503
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${folderName} is missing plugin.json`, {
4554
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${folderName} is missing plugin.json`, {
4504
4555
  code: "plugin_missing_manifest",
4505
4556
  cause
4506
4557
  });
@@ -4509,13 +4560,13 @@ async function loadPluginManifestFromJson(manifestPath, folderName) {
4509
4560
  try {
4510
4561
  parsed = JSON.parse(raw);
4511
4562
  } catch (cause) {
4512
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${folderName} manifest is invalid JSON`, {
4563
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${folderName} manifest is invalid JSON`, {
4513
4564
  code: "plugin_manifest_invalid",
4514
4565
  cause
4515
4566
  });
4516
4567
  }
4517
4568
  if (!parsed || typeof parsed !== "object") {
4518
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${folderName} manifest must be an object`, {
4569
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${folderName} manifest must be an object`, {
4519
4570
  code: "plugin_manifest_shape"
4520
4571
  });
4521
4572
  }
@@ -4534,7 +4585,7 @@ async function loadPluginManifestFromMarkdown(pluginsRoot, folderName) {
4534
4585
  try {
4535
4586
  raw = await promises.readFile(mdPath, "utf8");
4536
4587
  } catch (cause) {
4537
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${folderName} is missing PLUGIN.md`, {
4588
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${folderName} is missing PLUGIN.md`, {
4538
4589
  code: "plugin_missing_manifest",
4539
4590
  cause
4540
4591
  });
@@ -4549,7 +4600,7 @@ async function loadPluginManifestFromMarkdown(pluginsRoot, folderName) {
4549
4600
  });
4550
4601
  const entity = entities.find((e) => e.slug === "PLUGIN");
4551
4602
  if (entity === void 0) {
4552
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`Plugin ${folderName} PLUGIN.md not parseable`, {
4603
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`Plugin ${folderName} PLUGIN.md not parseable`, {
4553
4604
  code: "plugin_missing_manifest"
4554
4605
  });
4555
4606
  }
@@ -4823,7 +4874,7 @@ function assertValidThresholds(soft, hard) {
4823
4874
  ["hardThreshold", hard]
4824
4875
  ]) {
4825
4876
  if (!Number.isInteger(value) || value < 1) {
4826
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
4877
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
4827
4878
  `doomLoop.${label} must be a positive integer (received ${value}).`,
4828
4879
  { code: "invalid_doom_loop_threshold" }
4829
4880
  );
@@ -4942,6 +4993,35 @@ var UsageAccumulator = class {
4942
4993
  }
4943
4994
  };
4944
4995
 
4996
+ // src/internal/agent-loop/live-events.ts
4997
+ var LiveEventLog = class extends Array {
4998
+ /**
4999
+ * Not readonly, and not a constructor parameter — `Array` subclasses are re-instantiated by
5000
+ * `map`/`filter`/`slice` with a length argument, so a constructor with a different signature
5001
+ * breaks those. The sink is attached after construction instead.
5002
+ */
5003
+ #sink;
5004
+ /** Attach the live subscriber. One sink: the run that owns this loop. */
5005
+ subscribe(sink) {
5006
+ this.#sink = sink;
5007
+ }
5008
+ push(...events) {
5009
+ const length = super.push(...events);
5010
+ for (const event of events) {
5011
+ try {
5012
+ this.#sink?.(event);
5013
+ } catch {
5014
+ }
5015
+ }
5016
+ return length;
5017
+ }
5018
+ };
5019
+ function createEventLog(seed) {
5020
+ const log = new LiveEventLog();
5021
+ log.push(...seed);
5022
+ return log;
5023
+ }
5024
+
4945
5025
  // src/internal/agent-loop/message-builders.ts
4946
5026
  function buildSystemEvent(inputs, toolNames) {
4947
5027
  return {
@@ -4969,7 +5049,7 @@ function buildAssistantEvent(inputs, text) {
4969
5049
  message: { role: "assistant", content: [{ type: "text", text }] }
4970
5050
  };
4971
5051
  }
4972
- function buildThinkingEvent(inputs, text, thinkingDurationMs) {
5052
+ function buildThinkingEvent(inputs, text, thinkingDurationMs, signature) {
4973
5053
  const event = {
4974
5054
  type: "thinking",
4975
5055
  agent_id: inputs.agentId,
@@ -4979,10 +5059,12 @@ function buildThinkingEvent(inputs, text, thinkingDurationMs) {
4979
5059
  if (thinkingDurationMs !== void 0 && thinkingDurationMs >= 0) {
4980
5060
  event.thinking_duration_ms = thinkingDurationMs;
4981
5061
  }
5062
+ if (signature !== void 0) event.signature = signature;
4982
5063
  return event;
4983
5064
  }
4984
- function buildAssistantTurn(text, toolCalls) {
5065
+ function buildAssistantTurn(text, toolCalls, thinking) {
4985
5066
  const content = [];
5067
+ if (thinking !== void 0) content.push(thinking);
4986
5068
  if (text.length > 0) content.push({ type: "text", text });
4987
5069
  for (const call of toolCalls) content.push(call);
4988
5070
  return { role: "assistant", content };
@@ -5051,13 +5133,14 @@ async function initLoopContext(inputs) {
5051
5133
  });
5052
5134
  }
5053
5135
  }
5054
- const events = [
5136
+ const events = createEventLog([
5055
5137
  buildSystemEvent(
5056
5138
  inputs,
5057
5139
  tools.map((t) => t.name)
5058
5140
  ),
5059
5141
  buildUserEvent(inputs)
5060
- ];
5142
+ ]);
5143
+ if (inputs.onLoopEvent !== void 0) events.subscribe(inputs.onLoopEvent);
5061
5144
  const priorMessages = (inputs.priorMessages ?? []).map((msg) => ({
5062
5145
  role: msg.role,
5063
5146
  content: [{ type: "text", text: msg.text }]
@@ -5104,7 +5187,7 @@ async function safeListTools(client, serverName) {
5104
5187
  } catch (cause) {
5105
5188
  const message = cause instanceof Error ? cause.message : String(cause);
5106
5189
  const server = serverName ?? "unknown";
5107
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] mcp listTools failed (server=${server}): ${message}
5190
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] mcp listTools failed (server=${server}): ${message}
5108
5191
  `);
5109
5192
  return [];
5110
5193
  }
@@ -5173,7 +5256,7 @@ function emitLlmMetrics(inputs, result, startAt) {
5173
5256
  inputs.telemetry?.recordHistogram(HISTOGRAM_NAMES.LLM_USAGE_MISSING, 1, {
5174
5257
  provider: inputs.llm.name
5175
5258
  });
5176
- chunkLTCOPATU_cjs.diag(
5259
+ chunkBCQ3E2ZG_cjs.diag(
5177
5260
  `[theokit-sdk] llm usage missing from ${inputs.llm.name} finish \u2014 budget may undercount
5178
5261
  `
5179
5262
  );
@@ -5236,6 +5319,7 @@ async function streamLlmTurn(inputs, ctx) {
5236
5319
  emitLlmMetrics(inputs, result, startAt);
5237
5320
  llmSpan?.end();
5238
5321
  const stripped = stripThinkBlocks(collected.accumulatedText);
5322
+ const thinking = result.thinking ?? collected.thinking;
5239
5323
  return {
5240
5324
  text: stripped.visible,
5241
5325
  toolCalls: result.toolCalls,
@@ -5245,18 +5329,21 @@ async function streamLlmTurn(inputs, ctx) {
5245
5329
  outputTokens: result.outputTokens,
5246
5330
  cacheReadTokens: result.cacheReadTokens,
5247
5331
  cacheWriteTokens: result.cacheWriteTokens,
5248
- reasoningTokens: result.reasoningTokens
5332
+ reasoningTokens: result.reasoningTokens,
5333
+ ...thinking !== void 0 ? { thinking } : {}
5249
5334
  };
5250
5335
  }
5251
5336
  async function collectLlmEvents(generator, inputs, ctx) {
5252
5337
  let accumulatedText = "";
5253
5338
  let errored = false;
5254
5339
  let finishValue;
5340
+ let thinking;
5255
5341
  try {
5256
5342
  const result = await runCollectorLoop(generator, inputs, ctx);
5257
5343
  accumulatedText = result.accumulatedText;
5258
5344
  errored = result.errored;
5259
5345
  finishValue = result.finishValue;
5346
+ thinking = result.thinking;
5260
5347
  } catch (cause) {
5261
5348
  if (inputs.signal?.aborted === true) {
5262
5349
  ctx.finalText = "[aborted]";
@@ -5267,7 +5354,12 @@ async function collectLlmEvents(generator, inputs, ctx) {
5267
5354
  }
5268
5355
  errored = true;
5269
5356
  }
5270
- return { accumulatedText, errored, finishValue };
5357
+ return {
5358
+ accumulatedText,
5359
+ errored,
5360
+ finishValue,
5361
+ ...thinking !== void 0 ? { thinking } : {}
5362
+ };
5271
5363
  }
5272
5364
  function registerLoopError(ctx, cause) {
5273
5365
  if (ctx.error !== void 0) return;
@@ -5278,11 +5370,26 @@ function registerLoopError(ctx, cause) {
5278
5370
  const code = typeof metaCode === "string" ? metaCode : typeof rawCode === "string" ? rawCode : void 0;
5279
5371
  ctx.error = code !== void 0 ? { message, code, cause } : { message, cause };
5280
5372
  }
5373
+ async function consumeStreamEvent(inputs, reasoning, event) {
5374
+ if (event.type === "text_delta") {
5375
+ const text = event.text ?? "";
5376
+ await emitTextDeltaCallback(inputs, text);
5377
+ return text;
5378
+ }
5379
+ if (event.type === "reasoning_delta") {
5380
+ await consumeReasoningDelta(inputs, reasoning, {
5381
+ text: event.text ?? "",
5382
+ ...event.signature !== void 0 ? { signature: event.signature } : {}
5383
+ });
5384
+ }
5385
+ return "";
5386
+ }
5281
5387
  async function runCollectorLoop(generator, inputs, ctx) {
5282
5388
  let accumulatedText = "";
5283
- const reasoning = { text: "", startedAt: void 0 };
5389
+ const reasoning = { text: "", startedAt: void 0, signature: void 0 };
5284
5390
  let errored = false;
5285
5391
  let finishValue;
5392
+ let thinking;
5286
5393
  try {
5287
5394
  while (true) {
5288
5395
  const next = await generator.next();
@@ -5290,24 +5397,22 @@ async function runCollectorLoop(generator, inputs, ctx) {
5290
5397
  finishValue = next;
5291
5398
  break;
5292
5399
  }
5293
- if (next.value.type === "text_delta") {
5294
- accumulatedText += next.value.text;
5295
- await emitTextDeltaCallback(inputs, next.value.text);
5296
- }
5297
- if (next.value.type === "reasoning_delta") {
5298
- await accumulateReasoning(inputs, reasoning, next.value.text);
5299
- }
5300
5400
  if (next.value.type === "error") {
5301
5401
  registerLoopError(ctx, next.value);
5302
5402
  ctx.finalText = "";
5303
5403
  errored = true;
5304
5404
  break;
5305
5405
  }
5406
+ accumulatedText += await consumeStreamEvent(inputs, reasoning, next.value);
5306
5407
  }
5307
5408
  } finally {
5308
- await finalizeReasoning(inputs, ctx, reasoning);
5409
+ thinking = await finalizeReasoning(inputs, ctx, reasoning);
5309
5410
  }
5310
- return { accumulatedText, errored, finishValue };
5411
+ return { accumulatedText, errored, finishValue, ...thinking !== void 0 ? { thinking } : {} };
5412
+ }
5413
+ async function consumeReasoningDelta(inputs, reasoning, delta) {
5414
+ if (delta.signature !== void 0) reasoning.signature = delta.signature;
5415
+ await accumulateReasoning(inputs, reasoning, delta.text);
5311
5416
  }
5312
5417
  async function accumulateReasoning(inputs, reasoning, text) {
5313
5418
  if (reasoning.startedAt === void 0) reasoning.startedAt = Date.now();
@@ -5315,10 +5420,17 @@ async function accumulateReasoning(inputs, reasoning, text) {
5315
5420
  await emitReasoningDeltaCallback(inputs, text);
5316
5421
  }
5317
5422
  async function finalizeReasoning(inputs, ctx, reasoning) {
5318
- if (reasoning.text.length === 0) return;
5423
+ if (reasoning.text.length === 0) return void 0;
5319
5424
  const thinkingDurationMs = reasoning.startedAt === void 0 ? 0 : Date.now() - reasoning.startedAt;
5320
- ctx.events.push(buildThinkingEvent(inputs, reasoning.text, thinkingDurationMs));
5425
+ ctx.events.push(
5426
+ buildThinkingEvent(inputs, reasoning.text, thinkingDurationMs, reasoning.signature)
5427
+ );
5321
5428
  await emitThinkingCompletedCallback(inputs, thinkingDurationMs);
5429
+ return {
5430
+ type: "thinking",
5431
+ text: reasoning.text,
5432
+ ...reasoning.signature !== void 0 ? { signature: reasoning.signature } : {}
5433
+ };
5322
5434
  }
5323
5435
  async function emitTextDeltaCallback(inputs, text) {
5324
5436
  if (inputs.onDelta === void 0) return;
@@ -5348,6 +5460,24 @@ async function emitThinkingCompletedCallback(inputs, thinkingDurationMs) {
5348
5460
  );
5349
5461
  }
5350
5462
 
5463
+ // src/internal/agent-loop/loop-thinking-steps.ts
5464
+ function thinkingStep(thinking) {
5465
+ return {
5466
+ type: "thinkingMessage",
5467
+ message: {
5468
+ text: thinking.text,
5469
+ ...thinking.signature !== void 0 ? { signature: thinking.signature } : {}
5470
+ }
5471
+ };
5472
+ }
5473
+ function recordThinkingOnSilentToolRound(ctx, text, thinking) {
5474
+ if (text.length > 0 || thinking === void 0) return;
5475
+ ctx.conversation.push({
5476
+ type: "agentConversationTurn",
5477
+ turn: { steps: [thinkingStep(thinking)] }
5478
+ });
5479
+ }
5480
+
5351
5481
  // src/internal/tool-dispatch/repair-middleware.ts
5352
5482
  var DECIMAL_RE = /^-?\d+(\.\d+)?$/;
5353
5483
  function repairToolCall(raw, registry) {
@@ -5422,7 +5552,7 @@ function coerceArgsToSchema(args, schema) {
5422
5552
  }
5423
5553
 
5424
5554
  // src/tool-error.ts
5425
- var ToolError = class extends chunkMHCKWQR3_cjs.TheokitAgentError {
5555
+ var ToolError = class extends chunkIHFNRNTJ_cjs.TheokitAgentError {
5426
5556
  name = "ToolError";
5427
5557
  /** The error content surfaced to the model: a string, or text/image blocks. */
5428
5558
  content;
@@ -5616,7 +5746,7 @@ function raceToolExecution(exec, opts) {
5616
5746
  // src/internal/agent-loop/tool-dispatch.ts
5617
5747
  async function dispatchTools(inputs, tools, toolCalls, events, parentSpan) {
5618
5748
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
5619
- return chunkSWIBQFPH_cjs.mapWithConcurrency(
5749
+ return chunk7OLG7VI4_cjs.mapWithConcurrency(
5620
5750
  toolCalls,
5621
5751
  maxConcurrent,
5622
5752
  (call) => dispatchSingleCall(inputs, tools, call, events, parentSpan)
@@ -5644,7 +5774,7 @@ async function dispatchSingleCall(inputs, tools, call, events, parentSpan) {
5644
5774
  toolSpan?.end();
5645
5775
  return fileVeto;
5646
5776
  }
5647
- chunk6EDQBX7U_cjs.emitRunEvent(inputs.runEventSink, {
5777
+ chunkN475ETD6_cjs.emitRunEvent(inputs.runEventSink, {
5648
5778
  type: "tool_progress",
5649
5779
  toolName: workingCall.name,
5650
5780
  toolCallId: callId
@@ -5675,7 +5805,7 @@ function applyRepairAndExtractCall(tools, call) {
5675
5805
  function vetoFromForkWhitelist(inputs, call, callId, events) {
5676
5806
  const whitelistDecision = chunkVJ26EKGJ_cjs.checkToolWhitelist(call.name);
5677
5807
  if (whitelistDecision.allowed) return void 0;
5678
- chunk6EDQBX7U_cjs.emitRunEvent(inputs.runEventSink, {
5808
+ chunkN475ETD6_cjs.emitRunEvent(inputs.runEventSink, {
5679
5809
  type: "permission_denied",
5680
5810
  toolName: call.name,
5681
5811
  toolCallId: callId,
@@ -5720,7 +5850,7 @@ async function vetoFromPluginPreHook(inputs, call, callId, events) {
5720
5850
  ...inputs.permissionMode !== void 0 ? { permissionMode: inputs.permissionMode } : {}
5721
5851
  });
5722
5852
  if (pluginVeto === void 0) return void 0;
5723
- chunk6EDQBX7U_cjs.emitRunEvent(inputs.runEventSink, {
5853
+ chunkN475ETD6_cjs.emitRunEvent(inputs.runEventSink, {
5724
5854
  type: "permission_denied",
5725
5855
  toolName: call.name,
5726
5856
  toolCallId: callId,
@@ -5749,7 +5879,7 @@ async function vetoFromFileHookPreDecision(inputs, call, callId, events) {
5749
5879
  runId: inputs.runId
5750
5880
  });
5751
5881
  if (!preDecision.blocked) return void 0;
5752
- chunk6EDQBX7U_cjs.emitRunEvent(inputs.runEventSink, {
5882
+ chunkN475ETD6_cjs.emitRunEvent(inputs.runEventSink, {
5753
5883
  type: "permission_denied",
5754
5884
  toolName: call.name,
5755
5885
  toolCallId: callId,
@@ -5850,7 +5980,7 @@ function finalizeSpanAndPostHook(inputs, call, callId, result, events, toolSpan)
5850
5980
  agentId: inputs.agentId,
5851
5981
  runId: inputs.runId
5852
5982
  }).catch((err) => {
5853
- chunkLTCOPATU_cjs.diag(
5983
+ chunkBCQ3E2ZG_cjs.diag(
5854
5984
  `[theokit-sdk] postToolUse hook error (swallowed): ${err instanceof Error ? err.message : String(err)}
5855
5985
  `
5856
5986
  );
@@ -5869,7 +5999,7 @@ async function emitToolLifecycleDelta(inputs, update) {
5869
5999
  try {
5870
6000
  await inputs.onDelta({ update });
5871
6001
  } catch (err) {
5872
- chunkLTCOPATU_cjs.diag(
6002
+ chunkBCQ3E2ZG_cjs.diag(
5873
6003
  `[theokit-sdk] onDelta tool-lifecycle emit error (swallowed): ${err instanceof Error ? err.message : String(err)}
5874
6004
  `
5875
6005
  );
@@ -5881,7 +6011,7 @@ async function safeEmitToolHook(callback, event) {
5881
6011
  await callback(event);
5882
6012
  } catch (cause) {
5883
6013
  const msg = cause instanceof Error ? cause.message : String(cause);
5884
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] tool lifecycle hook threw: ${msg}
6014
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] tool lifecycle hook threw: ${msg}
5885
6015
  `);
5886
6016
  }
5887
6017
  }
@@ -5948,7 +6078,7 @@ function applyToolResultGuard(parts, opts) {
5948
6078
  (p) => (
5949
6079
  // SE7 — guard the TEXT of a tool result (string or the text blocks of a
5950
6080
  // structured content); image blocks pass through untouched.
5951
- p.type === "tool_result" ? { ...p, content: chunkALU3KC4G_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
6081
+ p.type === "tool_result" ? { ...p, content: chunkBPN5ONSW_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
5952
6082
  )
5953
6083
  );
5954
6084
  }
@@ -6143,7 +6273,7 @@ function catalogCostFallback(provider, cleanedModel) {
6143
6273
  const candidates = [`${provider}/${cleanedModel}`, cleanedModel];
6144
6274
  if (stripped !== cleanedModel) candidates.push(`${provider}/${stripped}`, stripped);
6145
6275
  for (const key of candidates) {
6146
- const info = chunk56ZM6P7Z_cjs.getCatalogModelInfo(key);
6276
+ const info = chunkG4XUXSRN_cjs.getCatalogModelInfo(key);
6147
6277
  const cost = info?.cost;
6148
6278
  if (cost === void 0) continue;
6149
6279
  const [prov, ...modelParts] = key.split("/");
@@ -6155,7 +6285,7 @@ function catalogCostFallback(provider, cleanedModel) {
6155
6285
  ...cost.cache_read !== void 0 ? { cacheReadCostPerMillion: cost.cache_read } : {},
6156
6286
  ...cost.cache_write !== void 0 ? { cacheWriteCostPerMillion: cost.cache_write } : {},
6157
6287
  // M44 M5 fix — honest provenance: a key patched by the LIVE models-dev source is not "vendored".
6158
- pricingVersion: chunk56ZM6P7Z_cjs.isPatchedModelKey(key) ? "catalog-models-dev" : "catalog-vendored"
6288
+ pricingVersion: chunkG4XUXSRN_cjs.isPatchedModelKey(key) ? "catalog-models-dev" : "catalog-vendored"
6159
6289
  };
6160
6290
  }
6161
6291
  return void 0;
@@ -6399,12 +6529,13 @@ async function runAgentLoop(inputs) {
6399
6529
  sendSpan?.end();
6400
6530
  }
6401
6531
  }
6402
- async function emitAssistantTextStep(inputs, ctx, text) {
6532
+ async function emitAssistantTextStep(inputs, ctx, text, thinking) {
6403
6533
  ctx.events.push(buildAssistantEvent(inputs, text));
6404
- ctx.conversation.push({
6405
- type: "agentConversationTurn",
6406
- turn: { steps: [{ type: "assistantMessage", message: { text } }] }
6407
- });
6534
+ const steps = [
6535
+ ...thinking !== void 0 ? [thinkingStep(thinking)] : [],
6536
+ { type: "assistantMessage", message: { text } }
6537
+ ];
6538
+ ctx.conversation.push({ type: "agentConversationTurn", turn: { steps } });
6408
6539
  ctx.finalText = text;
6409
6540
  if (inputs.onStep === void 0) return;
6410
6541
  const cb = inputs.onStep;
@@ -6540,13 +6671,15 @@ async function continueOrTerminate(inputs, ctx, llmOutput) {
6540
6671
  if (llmOutput.errored) return "error";
6541
6672
  const tCtx = { agentId: inputs.agentId, runId: inputs.runId };
6542
6673
  const text = llmOutput.text.length > 0 ? await transformLlmOutputText(inputs, llmOutput.text, tCtx) : llmOutput.text;
6674
+ const thinking = llmOutput.thinking;
6543
6675
  if (text.length > 0) {
6544
- await emitAssistantTextStep(inputs, ctx, text);
6676
+ await emitAssistantTextStep(inputs, ctx, text, thinking);
6545
6677
  }
6546
6678
  if (llmOutput.stopReason !== "tool_use" || llmOutput.toolCalls.length === 0) {
6547
6679
  return finishOrReflect(inputs, ctx, llmOutput);
6548
6680
  }
6549
- ctx.messages.push(buildAssistantTurn(text, llmOutput.toolCalls));
6681
+ recordThinkingOnSilentToolRound(ctx, text, thinking);
6682
+ ctx.messages.push(buildAssistantTurn(text, llmOutput.toolCalls, thinking));
6550
6683
  const rawResults = await dispatchTools(
6551
6684
  // SE12 — forward a read-only text projection of the transcript-so-far to tool
6552
6685
  // handlers via `ctx.messages` (consumed by defineSubAgent's messageFilter).
@@ -6582,7 +6715,9 @@ async function inspectDoomLoop(inputs, ctx, toolCalls) {
6582
6715
  await emitAssistantTextStep(
6583
6716
  inputs,
6584
6717
  ctx,
6585
- verdict.message ?? "Stopped: repeated identical tool calls made no progress."
6718
+ verdict.message ?? "Stopped: repeated identical tool calls made no progress.",
6719
+ // The doom-loop stop message is the SDK's own text, not a model turn — it has no thinking.
6720
+ void 0
6586
6721
  );
6587
6722
  return "stop";
6588
6723
  }
@@ -6603,15 +6738,15 @@ var FallbackLlmClient = class {
6603
6738
  let lastError;
6604
6739
  for (const client of this.clients) {
6605
6740
  if (signal.aborted) throw abortError(signal);
6606
- const attempt = await chunkALU3KC4G_cjs.tryFirstEvent(client, request, signal, true);
6741
+ const attempt = await chunkBPN5ONSW_cjs.tryFirstEvent(client, request, signal, true);
6607
6742
  if (attempt.kind === "handshake_error") {
6608
6743
  lastError = attempt.error;
6609
6744
  continue;
6610
6745
  }
6611
- return yield* chunkALU3KC4G_cjs.relayStream(attempt.generator, attempt.firstResult);
6746
+ return yield* chunkBPN5ONSW_cjs.relayStream(attempt.generator, attempt.firstResult);
6612
6747
  }
6613
6748
  if (lastError !== void 0) throw lastError;
6614
- throw new chunkMHCKWQR3_cjs.NetworkError("FallbackLlmClient has no providers configured", {
6749
+ throw new chunkIHFNRNTJ_cjs.NetworkError("FallbackLlmClient has no providers configured", {
6615
6750
  code: "fallback_empty_chain"
6616
6751
  });
6617
6752
  }
@@ -6634,7 +6769,7 @@ function reconnectDelay(attempt) {
6634
6769
  return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
6635
6770
  }
6636
6771
  function mcpTimeoutError(name, timeoutMs) {
6637
- return new chunkMHCKWQR3_cjs.NetworkError(`MCP ${name} request timed out after ${timeoutMs}ms`, {
6772
+ return new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${name} request timed out after ${timeoutMs}ms`, {
6638
6773
  code: "mcp_timeout"
6639
6774
  });
6640
6775
  }
@@ -6717,7 +6852,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6717
6852
  child.stdin.on("error", () => void 0);
6718
6853
  child.on("error", () => {
6719
6854
  this.rejectAllPending(
6720
- new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} process crashed`, { code: "mcp_crashed" })
6855
+ new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} process crashed`, { code: "mcp_crashed" })
6721
6856
  );
6722
6857
  });
6723
6858
  child.on("exit", () => {
@@ -6725,11 +6860,24 @@ var StdioMcpClient = class extends BaseMcpClient {
6725
6860
  this.child = void 0;
6726
6861
  this.dropped = true;
6727
6862
  this.rejectAllPending(
6728
- new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} disconnected`, { code: "mcp_disconnected" })
6863
+ new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} disconnected`, { code: "mcp_disconnected" })
6729
6864
  );
6730
6865
  });
6731
6866
  }
6867
+ /**
6868
+ * theokit#155 — idempotent while the child is LIVE.
6869
+ *
6870
+ * Under `mcpLifecycle: 'session'` the pool hands the same client back on the next turn, and
6871
+ * `initializeMcp` runs every turn. An unconditional `spawnChild()` would overwrite `this.child`,
6872
+ * orphaning a healthy process (its `exit` handler is skipped by the `this.child === child` guard)
6873
+ * and paying the ~146 ms spawn + handshake the option exists to avoid.
6874
+ *
6875
+ * This does NOT touch the #59 reconnect path: `reconnect()` calls `spawnChild()` and
6876
+ * `super.initialize()` directly, so it re-spawns exactly as before. After `close()` — or after a
6877
+ * drop, which clears `child` — this method spawns again, as it must.
6878
+ */
6732
6879
  async initialize() {
6880
+ if (this.child !== void 0) return;
6733
6881
  this.spawnChild();
6734
6882
  await super.initialize();
6735
6883
  }
@@ -6740,7 +6888,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6740
6888
  if (this.child !== void 0) return Promise.resolve();
6741
6889
  if (!this.dropped) {
6742
6890
  return Promise.reject(
6743
- new chunkMHCKWQR3_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" })
6891
+ new chunkIHFNRNTJ_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" })
6744
6892
  );
6745
6893
  }
6746
6894
  this.reconnectPromise ??= this.reconnect().finally(() => {
@@ -6761,13 +6909,13 @@ var StdioMcpClient = class extends BaseMcpClient {
6761
6909
  lastErr = err;
6762
6910
  }
6763
6911
  }
6764
- throw new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} reconnect exhausted`, {
6912
+ throw new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} reconnect exhausted`, {
6765
6913
  code: "mcp_disconnected",
6766
6914
  ...lastErr instanceof Error ? { cause: lastErr } : {}
6767
6915
  });
6768
6916
  }
6769
6917
  async close() {
6770
- this.rejectAllPending(new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} closed`, { code: "mcp_closed" }));
6918
+ this.rejectAllPending(new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} closed`, { code: "mcp_closed" }));
6771
6919
  const child = this.child;
6772
6920
  this.child = void 0;
6773
6921
  this.dropped = false;
@@ -6786,7 +6934,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6786
6934
  if (this.buffer.length > MAX_STDIO_BUFFER_BYTES) {
6787
6935
  this.buffer = "";
6788
6936
  this.rejectAllPending(
6789
- new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} exceeded stdout buffer limit`, {
6937
+ new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} exceeded stdout buffer limit`, {
6790
6938
  code: "mcp_buffer_overflow"
6791
6939
  })
6792
6940
  );
@@ -6821,7 +6969,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6821
6969
  if (child !== void 0) return this.send(child, method, params);
6822
6970
  if (this.dropped) return this.reconnectAndRequest(method, params);
6823
6971
  return Promise.reject(
6824
- new chunkMHCKWQR3_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" })
6972
+ new chunkIHFNRNTJ_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" })
6825
6973
  );
6826
6974
  }
6827
6975
  /** M2 #59 — reconnect a dropped client, then send. Separate async path so the
@@ -6830,7 +6978,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6830
6978
  await this.ensureConnected();
6831
6979
  const child = this.child;
6832
6980
  if (child === void 0) {
6833
- throw new chunkMHCKWQR3_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" });
6981
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(`MCP ${this.name} is not initialized`, { code: "mcp_not_init" });
6834
6982
  }
6835
6983
  return this.send(child, method, params);
6836
6984
  }
@@ -6847,7 +6995,7 @@ var StdioMcpClient = class extends BaseMcpClient {
6847
6995
  this.child = void 0;
6848
6996
  this.dropped = true;
6849
6997
  this.rejectAllPending(
6850
- new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} disconnected`, { code: "mcp_disconnected" })
6998
+ new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} disconnected`, { code: "mcp_disconnected" })
6851
6999
  );
6852
7000
  }, this.timeoutMs);
6853
7001
  this.pending.set(id, { resolve, reject, timer });
@@ -6918,14 +7066,14 @@ var HttpMcpClient = class extends BaseMcpClient {
6918
7066
  async readBody(response) {
6919
7067
  const tipo = response.headers.get("content-type") ?? "";
6920
7068
  if (!tipo.includes("text/event-stream")) return await response.json();
6921
- const texto = await response.text();
6922
- for (const linha of texto.split(/\r?\n/)) {
6923
- if (!linha.startsWith("data:")) continue;
6924
- const carga = linha.slice(5).trim();
6925
- if (carga === "") continue;
6926
- return JSON.parse(carga);
6927
- }
6928
- throw new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} returned an event stream with no data payload`, {
7069
+ const text = await response.text();
7070
+ for (const line of text.split(/\r?\n/)) {
7071
+ if (!line.startsWith("data:")) continue;
7072
+ const payload = line.slice(5).trim();
7073
+ if (payload === "") continue;
7074
+ return JSON.parse(payload);
7075
+ }
7076
+ throw new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} returned an event stream with no data payload`, {
6929
7077
  code: "mcp_http_error"
6930
7078
  });
6931
7079
  }
@@ -6953,7 +7101,7 @@ var HttpMcpClient = class extends BaseMcpClient {
6953
7101
  throw cause;
6954
7102
  }
6955
7103
  if (!response.ok) {
6956
- throw new chunkMHCKWQR3_cjs.NetworkError(`MCP ${this.name} returned ${response.status}`, {
7104
+ throw new chunkIHFNRNTJ_cjs.NetworkError(`MCP ${this.name} returned ${response.status}`, {
6957
7105
  code: "mcp_http_error"
6958
7106
  });
6959
7107
  }
@@ -6969,14 +7117,14 @@ var HttpMcpClient = class extends BaseMcpClient {
6969
7117
  function resolveMcpCwd(configCwd) {
6970
7118
  if (configCwd === void 0) return process.cwd();
6971
7119
  if (path.isAbsolute(configCwd)) return configCwd;
6972
- return chunkYBFDBOUN_cjs.safePathJoin(process.cwd(), configCwd);
7120
+ return chunk7YBJZS5P_cjs.safePathJoin(process.cwd(), configCwd);
6973
7121
  }
6974
7122
 
6975
7123
  // src/internal/providers/register-plugin-providers.ts
6976
7124
  function registerPluginProviderProfiles(entries) {
6977
7125
  let registered2 = 0;
6978
7126
  for (const entry of entries) {
6979
- chunk56ZM6P7Z_cjs.registerProvider(entry.profile);
7127
+ chunkG4XUXSRN_cjs.registerProvider(entry.profile);
6980
7128
  registered2 += 1;
6981
7129
  }
6982
7130
  return registered2;
@@ -7056,7 +7204,7 @@ function applyPersonalityFilter(exposedTools, whitelist, opts) {
7056
7204
  if (exposedSet.has(name)) continue;
7057
7205
  const hint = suggestClosest(name, exposedSet);
7058
7206
  const message = hint !== void 0 ? `[theokit-sdk] personality "${opts?.personalityName ?? "?"}" references unknown tool "${name}"; did you mean "${hint}"?` : `[theokit-sdk] personality "${opts?.personalityName ?? "?"}" references unknown tool "${name}" (not exposed)`;
7059
- chunkFAY3QDGC_cjs.warnOnce(
7207
+ chunk6LGQECT7_cjs.warnOnce(
7060
7208
  `personality-tool-missing|${opts?.agentId ?? "?"}|${opts?.personalityName ?? "?"}|${name}`,
7061
7209
  message
7062
7210
  );
@@ -7098,18 +7246,17 @@ function levenshtein(a, b) {
7098
7246
  // src/internal/local-agent/real-local-run-tools.ts
7099
7247
  function declarativeSubagentTools(agents2, parentTools) {
7100
7248
  if (agents2 === void 0 || Object.keys(agents2).length === 0) return [];
7101
- return chunkG2F67XUR_cjs.subAgentToolsFromDefinitions(agents2, parentTools);
7249
+ return chunkB4YA6BRS_cjs.subAgentToolsFromDefinitions(agents2, parentTools);
7102
7250
  }
7103
- function bindParentCredentials(tools, agentOptions) {
7251
+ function resolveInheritedCredentials(agentOptions) {
7104
7252
  const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
7105
7253
  const parentSandbox = agentOptions.local?.sandboxOptions?.enabled;
7106
- const credentials = {
7254
+ return {
7107
7255
  ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
7108
7256
  ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
7109
7257
  ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {},
7110
7258
  ...parentSandbox !== void 0 ? { sandbox: parentSandbox } : {}
7111
7259
  };
7112
- for (const tool of tools) chunkG2F67XUR_cjs.inheritSubAgentCredentials(tool, credentials);
7113
7260
  }
7114
7261
  function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, personalityToolWhitelist, agentId, personalityName, subagents, effectiveModel) {
7115
7262
  const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];
@@ -7121,7 +7268,6 @@ function buildCustomToolsInput(agentOptions, sendOptions, pluginManager, persona
7121
7268
  return {};
7122
7269
  }
7123
7270
  const allTools = [...baseTools, ...subagentTools, ...pluginTools, ...reasoningTools];
7124
- bindParentCredentials(allTools, agentOptions);
7125
7271
  const merged = allTools.map((tool) => ({
7126
7272
  name: tool.name,
7127
7273
  description: tool.description,
@@ -7157,7 +7303,9 @@ function createRealLocalRun(options) {
7157
7303
  supportedOps: supported,
7158
7304
  startTime
7159
7305
  },
7160
- () => buildLoopInputs(options, id, userText, userImages)
7306
+ () => buildLoopInputs(options, id, userText, userImages),
7307
+ runOwnsMcpClients(options.agentOptions),
7308
+ resolveInheritedCredentials(options.agentOptions)
7161
7309
  );
7162
7310
  handle.bootstrap();
7163
7311
  registerRun(handle);
@@ -7165,25 +7313,25 @@ function createRealLocalRun(options) {
7165
7313
  }
7166
7314
  var pluginProvidersAnnounced = false;
7167
7315
  function resolveRunProvider(options) {
7168
- chunk56ZM6P7Z_cjs.registerBuiltins();
7316
+ chunkG4XUXSRN_cjs.registerBuiltins();
7169
7317
  const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];
7170
7318
  const registered2 = registerPluginProviderProfiles(profiles);
7171
7319
  if (registered2 > 0 && !pluginProvidersAnnounced) {
7172
7320
  pluginProvidersAnnounced = true;
7173
7321
  const names = profiles.map((e) => e.profile.name).join(", ");
7174
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] registered ${registered2} plugin provider profile(s): ${names}
7322
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] registered ${registered2} plugin provider profile(s): ${names}
7175
7323
  `);
7176
7324
  }
7177
7325
  const parsedModel = chunkVYHJZVL5_cjs.parseModelId(options.model?.id);
7178
- const modelInferredProvider = parsedModel.provider !== void 0 && chunk56ZM6P7Z_cjs.getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
7179
- const keyInferredProvider = chunkALU3KC4G_cjs.inferProviderFromApiKey(options.agentOptions.apiKey);
7180
- const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? keyInferredProvider ?? modelInferredProvider ?? chunkALU3KC4G_cjs.detectPrimaryProvider();
7326
+ const modelInferredProvider = parsedModel.provider !== void 0 && chunkG4XUXSRN_cjs.getProviderProfile(parsedModel.provider) !== void 0 ? parsedModel.provider : void 0;
7327
+ const keyInferredProvider = chunkBPN5ONSW_cjs.inferProviderFromApiKey(options.agentOptions.apiKey);
7328
+ const primary = options.agentOptions.providers?.routes?.[0]?.provider ?? keyInferredProvider ?? modelInferredProvider ?? chunkBPN5ONSW_cjs.detectPrimaryProvider();
7181
7329
  const effectiveModelId = modelInferredProvider !== void 0 && modelInferredProvider === primary ? parsedModel.name : options.model?.id ?? "claude-sonnet-4-6";
7182
7330
  return { primary, effectiveModelId };
7183
7331
  }
7184
7332
  function mergeExplicitApiKey(pools, primary, apiKey) {
7185
7333
  if (apiKey === void 0 || apiKey.length === 0) return pools;
7186
- if (chunkALU3KC4G_cjs.isFixtureApiKey(apiKey) || apiKey === LOCAL_RUNTIME_MOCK_KEY) return pools;
7334
+ if (chunkBPN5ONSW_cjs.isFixtureApiKey(apiKey) || apiKey === LOCAL_RUNTIME_MOCK_KEY) return pools;
7187
7335
  const existing = pools?.[primary];
7188
7336
  if (existing !== void 0 && existing.length > 0) return pools;
7189
7337
  return { ...pools ?? {}, [primary]: [apiKey] };
@@ -7191,7 +7339,7 @@ function mergeExplicitApiKey(pools, primary, apiKey) {
7191
7339
  function buildLoopInputs(options, runId, userText, userImages) {
7192
7340
  const maxIterations = options.sendOptions.maxIterations;
7193
7341
  if (maxIterations !== void 0 && (!Number.isInteger(maxIterations) || maxIterations < 1)) {
7194
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
7342
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
7195
7343
  `SendOptions.maxIterations must be a positive integer, got ${maxIterations}`,
7196
7344
  { code: "invalid_max_iterations" }
7197
7345
  );
@@ -7206,14 +7354,14 @@ function buildLoopInputs(options, runId, userText, userImages) {
7206
7354
  const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;
7207
7355
  const extractToolCallsFromContent = options.agentOptions.providers?.routes?.[0]?.extractToolCallsFromContent;
7208
7356
  const rateLimitSink = options.sendOptions.onRunEvent;
7209
- const chain = chunkALU3KC4G_cjs.resolveProviderChain({
7357
+ const chain = chunkBPN5ONSW_cjs.resolveProviderChain({
7210
7358
  primary,
7211
7359
  ...fallback !== void 0 ? { fallback } : {},
7212
7360
  ...apiKeys !== void 0 ? { apiKeys } : {},
7213
7361
  ...credentialPoolStrategy !== void 0 ? { credentialPoolStrategy } : {},
7214
7362
  ...extractToolCallsFromContent === true ? { extractToolCallsFromContent: true } : {},
7215
7363
  ...rateLimitSink !== void 0 ? {
7216
- onRateLimit: (info) => chunk6EDQBX7U_cjs.emitRunEvent(rateLimitSink, { type: "rate_limit", ...info })
7364
+ onRateLimit: (info) => chunkN475ETD6_cjs.emitRunEvent(rateLimitSink, { type: "rate_limit", ...info })
7217
7365
  } : {}
7218
7366
  });
7219
7367
  const llm = chain.length === 1 ? chain[0] : new FallbackLlmClient(chain);
@@ -7296,11 +7444,14 @@ function disposeSessionMcpClients(agentId) {
7296
7444
  void client.close();
7297
7445
  });
7298
7446
  }
7447
+ function runOwnsMcpClients(agentOptions) {
7448
+ return agentOptions.mcpLifecycle !== "session";
7449
+ }
7299
7450
  function buildMcpMap(options) {
7300
7451
  const map = /* @__PURE__ */ new Map();
7301
7452
  const inline = options.sendOptions.mcpServers ?? options.agentOptions.mcpServers;
7302
7453
  if (inline === void 0) return map;
7303
- const pooled = options.agentOptions.mcpLifecycle === "session";
7454
+ const pooled = !runOwnsMcpClients(options.agentOptions);
7304
7455
  if (pooled) sessionMcpPool.reapIdle((c) => void c.close());
7305
7456
  for (const [name, config] of Object.entries(inline)) {
7306
7457
  map.set(
@@ -7312,9 +7463,15 @@ function buildMcpMap(options) {
7312
7463
  }
7313
7464
  var RealLocalRun = class extends FixtureRunBase {
7314
7465
  buildInputs;
7315
- constructor(options, buildInputs) {
7466
+ /** theokit#155 — whether this turn releases its MCP clients, or the session pool does. */
7467
+ ownsMcpClients;
7468
+ /** theokit#148 — what a delegated child inherits from this parent, scoped to the loop. */
7469
+ inheritedCredentials;
7470
+ constructor(options, buildInputs, ownsMcpClients, inheritedCredentials) {
7316
7471
  super(options);
7317
7472
  this.buildInputs = buildInputs;
7473
+ this.ownsMcpClients = ownsMcpClients;
7474
+ this.inheritedCredentials = inheritedCredentials;
7318
7475
  }
7319
7476
  bootstrap() {
7320
7477
  setTimeout(() => {
@@ -7354,17 +7511,39 @@ var RealLocalRun = class extends FixtureRunBase {
7354
7511
  }
7355
7512
  }
7356
7513
  }
7514
+ /**
7515
+ * theokit#140 - events already handed to stream() by the live subscriber.
7516
+ *
7517
+ * The loop still RETURNS its full event list, and that batch path is deliberately kept: it is the
7518
+ * fallback if a live event is ever lost, and removing it would make the live channel a single
7519
+ * point of failure for the whole transcript.
7520
+ */
7521
+ liveDelivered = /* @__PURE__ */ new Set();
7357
7522
  async executeAgentLoop(inputs) {
7523
+ inputs.onLoopEvent = (event) => {
7524
+ this.liveDelivered.add(event);
7525
+ this.script.events.push(event);
7526
+ this.pushTimeline({ kind: "message", message: event });
7527
+ this.notifyNewEvents();
7528
+ };
7529
+ const callerOnDelta = inputs.onDelta;
7530
+ inputs.onDelta = (delta) => {
7531
+ callerOnDelta?.(delta);
7532
+ this.pushTimeline({ kind: "delta", update: delta.update });
7533
+ };
7358
7534
  try {
7359
- const output = inputs.activeTools !== void 0 ? await chunkVJ26EKGJ_cjs.withToolWhitelist(new Set(inputs.activeTools), () => runAgentLoop(inputs)) : await runAgentLoop(inputs);
7535
+ const runLoop = () => inputs.activeTools !== void 0 ? chunkVJ26EKGJ_cjs.withToolWhitelist(new Set(inputs.activeTools), () => runAgentLoop(inputs)) : runAgentLoop(inputs);
7536
+ const output = await chunkB4YA6BRS_cjs.withInheritedSubAgentCredentials(this.inheritedCredentials, runLoop);
7360
7537
  this.applyAgentLoopOutput(output);
7361
7538
  this.transitionTo(output.finalStatus);
7362
7539
  } catch (cause) {
7363
7540
  this.emitErrorEvent(cause, "Agent loop failed", "", "agent_loop_failed");
7364
7541
  this.transitionTo("error");
7365
7542
  } finally {
7366
- for (const client of inputs.mcp.values()) {
7367
- await client.close().catch(() => void 0);
7543
+ if (this.ownsMcpClients) {
7544
+ for (const client of inputs.mcp.values()) {
7545
+ await client.close().catch(() => void 0);
7546
+ }
7368
7547
  }
7369
7548
  }
7370
7549
  }
@@ -7377,10 +7556,7 @@ var RealLocalRun = class extends FixtureRunBase {
7377
7556
  * Finding-B fix (sdk-error-packaging v1.1): set-once errorDetail copy.
7378
7557
  */
7379
7558
  applyAgentLoopOutput(output) {
7380
- for (const event of output.events) {
7381
- this.script.events.push(event);
7382
- this.notifyNewEvents();
7383
- }
7559
+ this.deliverUndeliveredEvents(output.events);
7384
7560
  this.script.conversation.push(...output.conversation);
7385
7561
  if (output.result.length > 0) this.script.result = output.result;
7386
7562
  if (output.usage !== void 0) this.script.usage = output.usage;
@@ -7395,6 +7571,25 @@ var RealLocalRun = class extends FixtureRunBase {
7395
7571
  };
7396
7572
  }
7397
7573
  }
7574
+ /**
7575
+ * theokit#140 - deliver only what the live subscriber has NOT already handed to `stream()`.
7576
+ *
7577
+ * The loop now reports each event as it happens, so this batch is the SAME list, replayed.
7578
+ * Without the guard every event would reach `stream()` twice: once live, once here.
7579
+ *
7580
+ * Identity, not deep equality: these are the very objects the live sink saw, and two genuinely
7581
+ * distinct events can be structurally identical (the same tool called twice with the same args
7582
+ * is not a duplicate).
7583
+ *
7584
+ * Extracted because the guard pushed `applyAgentLoopOutput` past the cognitive-complexity cap.
7585
+ */
7586
+ deliverUndeliveredEvents(events) {
7587
+ for (const event of events) {
7588
+ if (this.liveDelivered.has(event)) continue;
7589
+ this.script.events.push(event);
7590
+ this.notifyNewEvents();
7591
+ }
7592
+ }
7398
7593
  emitErrorEvent(cause, fallback, prefix = "", code) {
7399
7594
  if (this.script.errorDetail === void 0) {
7400
7595
  const message = cause instanceof Error ? cause.message : String(cause);
@@ -7431,7 +7626,7 @@ function buildRealRunOptions(args) {
7431
7626
  };
7432
7627
  }
7433
7628
  async function createFixtureRunHelper(args) {
7434
- const sessionMessages = chunkH5YVJB4K_cjs.getSessionMessages(args.inputs.agentId);
7629
+ const sessionMessages = chunkDCXRHCZJ_cjs.getSessionMessages(args.inputs.agentId);
7435
7630
  const projectMcpServers = args.inputs.settingSourcesIncludeProject ? await readProjectMcpServers(args.inputs.workspaceCwd) : {};
7436
7631
  return createLocalRun({
7437
7632
  agentId: args.inputs.agentId,
@@ -7450,7 +7645,7 @@ async function createFixtureRunHelper(args) {
7450
7645
  }
7451
7646
  async function dispatchLocalRun(args) {
7452
7647
  const apiKey = resolveApiKey(args.inputs.options.apiKey);
7453
- if (chunkALU3KC4G_cjs.shouldUseRealLocalRuntime(apiKey)) {
7648
+ if (chunkBPN5ONSW_cjs.shouldUseRealLocalRuntime(apiKey)) {
7454
7649
  return createRealLocalRun(
7455
7650
  buildRealRunOptions({
7456
7651
  inputs: args.inputs,
@@ -7485,20 +7680,20 @@ async function readProjectMcpServers(cwd) {
7485
7680
 
7486
7681
  // src/internal/local-agent/local-agent-invalidate.ts
7487
7682
  async function applyDeferredInvalidation(agentId, pending, refresh) {
7488
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] applying deferred cache invalidation (${agentId}): ${pending.reason}
7683
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] applying deferred cache invalidation (${agentId}): ${pending.reason}
7489
7684
  `);
7490
7685
  try {
7491
7686
  await refresh();
7492
7687
  } catch (err) {
7493
7688
  const msg = err instanceof Error ? err.message : String(err);
7494
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] invalidateCache reload failed (continuing): ${msg}
7689
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] invalidateCache reload failed (continuing): ${msg}
7495
7690
  `);
7496
7691
  }
7497
7692
  }
7498
7693
  async function invalidateCacheImpl(agentId, reason, options, disposed, dispose, setPending) {
7499
7694
  if (disposed) return;
7500
7695
  if (options.applyNow === true) {
7501
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] invalidateCache applyNow disposing agent (${agentId}): ${reason}
7696
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] invalidateCache applyNow disposing agent (${agentId}): ${reason}
7502
7697
  `);
7503
7698
  await dispose();
7504
7699
  return;
@@ -7559,7 +7754,7 @@ var LiveAgentRegistry = class {
7559
7754
  const existing = this.#agents.get(id);
7560
7755
  if (existing !== void 0 && existing.agent !== agent) {
7561
7756
  void existing.agent.dispose().catch(() => {
7562
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] dispose during overwrite failed (${id})
7757
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] dispose during overwrite failed (${id})
7563
7758
  `);
7564
7759
  });
7565
7760
  }
@@ -7663,7 +7858,7 @@ var LiveAgentRegistry = class {
7663
7858
  await agent.dispose();
7664
7859
  } catch (cause) {
7665
7860
  const msg = cause instanceof Error ? cause.message : String(cause);
7666
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] dispose during eviction failed (${id}): ${msg}
7861
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] dispose during eviction failed (${id}): ${msg}
7667
7862
  `);
7668
7863
  }
7669
7864
  if (this.#onEvict !== void 0) {
@@ -7671,7 +7866,7 @@ var LiveAgentRegistry = class {
7671
7866
  this.#onEvict(id, reason);
7672
7867
  } catch (cause) {
7673
7868
  const msg = cause instanceof Error ? cause.message : String(cause);
7674
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] onEvict listener threw (${id}): ${msg}
7869
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] onEvict listener threw (${id}): ${msg}
7675
7870
  `);
7676
7871
  }
7677
7872
  }
@@ -7680,20 +7875,20 @@ var LiveAgentRegistry = class {
7680
7875
  var liveAgentRegistry = new LiveAgentRegistry();
7681
7876
 
7682
7877
  // src/internal/local-agent/local-agent-lifecycle.ts
7683
- async function adquirirLeaseSePossivel(store, agentId) {
7878
+ async function acquireLeaseIfPossible(store, agentId) {
7684
7879
  const a = store.acquire;
7685
7880
  if (typeof a !== "function") return;
7686
7881
  try {
7687
7882
  await a.call(store, agentId);
7688
7883
  } catch (err) {
7689
7884
  if (err instanceof Error && err.name === "SessionBusyError") throw err;
7690
- chunkLTCOPATU_cjs.diag(
7885
+ chunkBCQ3E2ZG_cjs.diag(
7691
7886
  `[theokit-sdk] writer lease unavailable for ${agentId} (${err instanceof Error ? err.message : String(err)}) \u2014 proceeding without single-writer protection
7692
7887
  `
7693
7888
  );
7694
7889
  }
7695
7890
  }
7696
- async function soltarLeaseSePossivel(store, agentId) {
7891
+ async function releaseLeaseIfPossible(store, agentId) {
7697
7892
  const r = store.release;
7698
7893
  if (typeof r === "function") await r.call(store, agentId);
7699
7894
  }
@@ -7706,16 +7901,16 @@ async function disposeLocalAgentSession(agent) {
7706
7901
  agent.lifecycleAbortController.abort();
7707
7902
  await chunkYLQQX5W2_cjs.withCwdMutex(`agent-send:${agent.agentId}`, () => Promise.resolve());
7708
7903
  disposeSessionMcpClients(agent.agentId);
7709
- await chunkH5YVJB4K_cjs.flushSessionWrites();
7904
+ await chunkDCXRHCZJ_cjs.flushSessionWrites();
7710
7905
  await flushRegistrySaves(agent.workspaceCwd);
7711
7906
  await disposeSessionStore(agent.sessionStore);
7712
- chunkH5YVJB4K_cjs.descartarSessao(agent.workspaceCwd, agent.agentId);
7907
+ chunkDCXRHCZJ_cjs.discardSession(agent.workspaceCwd, agent.agentId);
7713
7908
  }
7714
7909
  async function reloadLocalAgent(agent) {
7715
7910
  if (agent.context !== void 0) await agent.context.refresh();
7716
7911
  if (agent.skillsManager !== void 0) await agent.skillsManager.refresh();
7717
7912
  if (agent.pluginsManager !== void 0) await agent.pluginsManager.refresh();
7718
- return await chunkGM7QDQ24_cjs.loadSubagents(
7913
+ return await chunkW4WKVOOQ_cjs.loadSubagents(
7719
7914
  agent.workspaceCwd,
7720
7915
  agent.settingSourcesIncludeProject,
7721
7916
  agent.options.agents
@@ -7723,12 +7918,12 @@ async function reloadLocalAgent(agent) {
7723
7918
  }
7724
7919
  async function persistActiveMemoryTranscript(cwd, transcript) {
7725
7920
  try {
7726
- const dir = path.join(chunk2423XDPT_cjs.memoryDir(cwd), "transcripts", "active-memory");
7921
+ const dir = path.join(chunkCN6UX5EV_cjs.memoryDir(cwd), "transcripts", "active-memory");
7727
7922
  const file = path.join(dir, `${transcript.runId}.json`);
7728
- await chunkICYBIC6N_cjs.atomicWriteJson(file, transcript);
7923
+ await chunkDGLLVCNB_cjs.atomicWriteJson(file, transcript);
7729
7924
  } catch (cause) {
7730
7925
  const message = cause instanceof Error ? cause.message : String(cause);
7731
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] active-memory transcript persist failed: ${message}
7926
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] active-memory transcript persist failed: ${message}
7732
7927
  `);
7733
7928
  }
7734
7929
  }
@@ -7849,7 +8044,7 @@ async function searchOnce(args, cfg, query, started) {
7849
8044
  return { summary, durationMs: Date.now() - started, status: "ok", hits };
7850
8045
  } catch (cause) {
7851
8046
  const message = cause instanceof Error ? cause.message : String(cause);
7852
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] active-memory recall failed: ${message}
8047
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] active-memory recall failed: ${message}
7853
8048
  `);
7854
8049
  return { summary: void 0, durationMs: Date.now() - started, status: "error", hits: [] };
7855
8050
  }
@@ -7955,184 +8150,6 @@ function cacheKey(userText, queryMode, ctx) {
7955
8150
  const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
7956
8151
  return crypto.createHash("sha256").update(parts.join("\0")).digest("hex");
7957
8152
  }
7958
- var MAX_BATCH = 100;
7959
- var MAX_RETRIES = 2;
7960
- async function createOpenAiCompatibleRuntime(cfg, options) {
7961
- const model = options.model ?? cfg.defaultModel;
7962
- const apiKey = options.apiKey ?? process.env[cfg.apiKeyEnv];
7963
- if (apiKey === void 0 || apiKey.length === 0) {
7964
- throw new chunkMHCKWQR3_cjs.AuthenticationError(`${cfg.apiKeyEnv} missing`, {
7965
- code: "embedding_missing_api_key"
7966
- });
7967
- }
7968
- const envBaseUrl = cfg.baseUrlEnv !== void 0 ? process.env[cfg.baseUrlEnv] : void 0;
7969
- const baseUrl = options.baseUrl ?? envBaseUrl ?? cfg.defaultBaseUrl;
7970
- const fetchImpl = options.fetch ?? fetch;
7971
- const cache = options.cache ?? chunk2423XDPT_cjs.globalEmbeddingCache;
7972
- const dimension = cfg.dimensionByModel[model];
7973
- if (dimension === void 0) {
7974
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
7975
- `${cfg.id} adapter: model "${model}" is not in the dimension table. Use one of: ${Object.keys(cfg.dimensionByModel).join(", ")}. To add it, update dimensionByModel in the adapter source.`,
7976
- { code: "embedding_unknown_model" }
7977
- );
7978
- }
7979
- const embeddingsPath = cfg.embeddingsPath ?? "/v1/embeddings";
7980
- const stats = {
7981
- cacheHits: 0,
7982
- cacheMisses: 0,
7983
- httpCalls: 0,
7984
- retries: 0
7985
- };
7986
- return {
7987
- id: cfg.id,
7988
- model,
7989
- dimension,
7990
- stats: () => ({ ...stats }),
7991
- embed: (texts) => embedTexts({
7992
- texts,
7993
- cache,
7994
- stats,
7995
- model,
7996
- dimension,
7997
- apiKey,
7998
- baseUrl,
7999
- embeddingsPath,
8000
- fetchImpl,
8001
- providerId: cfg.id
8002
- })
8003
- };
8004
- }
8005
- async function embedTexts(input) {
8006
- const { texts, cache, stats, model, dimension } = input;
8007
- const results = new Array(texts.length);
8008
- const pending = [];
8009
- for (let i = 0; i < texts.length; i++) {
8010
- classifyEntry({
8011
- index: i,
8012
- text: texts[i] ?? "",
8013
- model,
8014
- dimension,
8015
- cache,
8016
- stats,
8017
- results,
8018
- pending
8019
- });
8020
- }
8021
- await embedInBoundedBatches(input, pending, results);
8022
- return results.map((v) => v ?? new Array(dimension).fill(0));
8023
- }
8024
- function classifyEntry(args) {
8025
- if (args.text.trim().length === 0) {
8026
- args.results[args.index] = new Array(args.dimension).fill(0);
8027
- return;
8028
- }
8029
- const key = hashKey(args.model, args.text);
8030
- const cached = args.cache.get(key);
8031
- if (cached !== void 0) {
8032
- args.stats.cacheHits += 1;
8033
- args.results[args.index] = cached;
8034
- return;
8035
- }
8036
- args.stats.cacheMisses += 1;
8037
- args.pending.push({ index: args.index, text: args.text, key });
8038
- }
8039
- var MAX_CONCURRENT_BATCHES = 3;
8040
- async function embedInBoundedBatches(input, pending, results) {
8041
- const batches = [];
8042
- for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {
8043
- batches.push(pending.slice(offset, offset + MAX_BATCH));
8044
- }
8045
- await chunkSWIBQFPH_cjs.mapWithConcurrency(
8046
- batches,
8047
- MAX_CONCURRENT_BATCHES,
8048
- (batch) => processBatch(input, batch, results)
8049
- );
8050
- }
8051
- async function processBatch(input, batch, results) {
8052
- const vectors = await embedBatch({
8053
- apiKey: input.apiKey,
8054
- baseUrl: input.baseUrl,
8055
- embeddingsPath: input.embeddingsPath,
8056
- model: input.model,
8057
- inputs: batch.map((b) => b.text),
8058
- fetchImpl: input.fetchImpl,
8059
- stats: input.stats,
8060
- providerId: input.providerId
8061
- });
8062
- for (let j = 0; j < batch.length; j++) {
8063
- const slot = batch[j];
8064
- const vector = vectors[j];
8065
- if (slot === void 0 || vector === void 0) continue;
8066
- results[slot.index] = vector;
8067
- input.cache.set(slot.key, vector);
8068
- }
8069
- }
8070
- async function embedBatch(opts) {
8071
- const url = `${opts.baseUrl.replace(/\/$/, "")}${opts.embeddingsPath}`;
8072
- let attempt = 0;
8073
- while (true) {
8074
- opts.stats.httpCalls += 1;
8075
- const response = await postEmbedRequest(opts, url);
8076
- if (response.ok)
8077
- return await parseEmbedResponse(response, opts.providerId, opts.embeddingsPath);
8078
- if (isRetryable(response.status) && attempt < MAX_RETRIES) {
8079
- attempt += 1;
8080
- opts.stats.retries += 1;
8081
- await sleep(linearBackoffMs(attempt));
8082
- continue;
8083
- }
8084
- const text = await response.text().catch(() => "");
8085
- let body = text;
8086
- try {
8087
- body = JSON.parse(text);
8088
- } catch {
8089
- }
8090
- throw chunkALU3KC4G_cjs.mapOpenAICompatibleError({
8091
- providerId: opts.providerId,
8092
- status: response.status,
8093
- body,
8094
- headers: response.headers,
8095
- endpoint: opts.embeddingsPath
8096
- });
8097
- }
8098
- }
8099
- async function postEmbedRequest(opts, url) {
8100
- return opts.fetchImpl(url, {
8101
- method: "POST",
8102
- headers: {
8103
- "content-type": "application/json",
8104
- authorization: `Bearer ${opts.apiKey}`
8105
- },
8106
- body: JSON.stringify({ model: opts.model, input: opts.inputs })
8107
- });
8108
- }
8109
- async function parseEmbedResponse(response, providerId, endpoint) {
8110
- const json = await response.json();
8111
- if (!Array.isArray(json.data)) {
8112
- throw new chunkMHCKWQR3_cjs.NetworkError(`${providerId} ${endpoint} returned no data`, {
8113
- code: "embedding_invalid_response",
8114
- metadata: {
8115
- provider: providerId,
8116
- endpoint,
8117
- code: "invalid_request",
8118
- raw: json
8119
- }
8120
- });
8121
- }
8122
- return json.data.map((d) => d.embedding);
8123
- }
8124
- function isRetryable(status) {
8125
- return status === 429 || status >= 500 && status < 600;
8126
- }
8127
- function hashKey(model, text) {
8128
- return crypto.createHash("sha256").update(`${model} ${text}`).digest("hex");
8129
- }
8130
- function linearBackoffMs(attempt) {
8131
- return 50 * attempt;
8132
- }
8133
- function sleep(ms) {
8134
- return new Promise((resolve) => setTimeout(resolve, ms));
8135
- }
8136
8153
 
8137
8154
  // src/internal/memory/adapters/azure-openai-embedding.ts
8138
8155
  var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
@@ -8147,7 +8164,7 @@ var azureOpenAiMemoryEmbeddingProviderAdapter = {
8147
8164
  transport: "remote",
8148
8165
  authProviderId: "azure-openai",
8149
8166
  autoSelectPriority: 25,
8150
- create: (options) => createOpenAiCompatibleRuntime(
8167
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8151
8168
  {
8152
8169
  id: "azure-openai",
8153
8170
  defaultBaseUrl: "https://your-resource.openai.azure.com",
@@ -8155,7 +8172,15 @@ var azureOpenAiMemoryEmbeddingProviderAdapter = {
8155
8172
  baseUrlEnv: "AZURE_OPENAI_ENDPOINT",
8156
8173
  defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,
8157
8174
  embeddingsPath: "/openai/deployments/{model}/embeddings?api-version=2024-02-01",
8158
- dimensionByModel: DIMENSION_BY_MODEL
8175
+ dimensionByModel: DIMENSION_BY_MODEL,
8176
+ // theokit#159 — Azure is NOT OpenAI on the wire, despite the name. It authenticates an API
8177
+ // key with the `api-key` header (`Authorization: Bearer` is for Entra ID tokens, not for
8178
+ // AZURE_OPENAI_API_KEY), and the deployment already rides in the path, so `model` has no
8179
+ // place in the body. Sending the OpenAI shape meant every request was rejected.
8180
+ dialect: {
8181
+ authHeaders: (apiKey) => ({ "api-key": apiKey }),
8182
+ body: (_model, inputs) => ({ input: inputs })
8183
+ }
8159
8184
  },
8160
8185
  options
8161
8186
  )
@@ -8175,14 +8200,27 @@ var cohereMemoryEmbeddingProviderAdapter = {
8175
8200
  transport: "remote",
8176
8201
  authProviderId: "cohere",
8177
8202
  autoSelectPriority: 30,
8178
- create: (options) => createOpenAiCompatibleRuntime(
8203
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8179
8204
  {
8180
8205
  id: "cohere",
8181
8206
  defaultBaseUrl: "https://api.cohere.com",
8182
8207
  apiKeyEnv: "COHERE_API_KEY",
8183
8208
  defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,
8184
8209
  embeddingsPath: "/v2/embed",
8185
- dimensionByModel: DIMENSION_BY_MODEL2
8210
+ dimensionByModel: DIMENSION_BY_MODEL2,
8211
+ // theokit#159 — `/v2/embed` diverges in BOTH directions: it names the payload `texts`, requires
8212
+ // `input_type`, and answers `{embeddings:{float:[[...]]}}` rather than `{data:[{embedding}]}`.
8213
+ // `search_document` is the right default here because this runtime embeds material for
8214
+ // storage; a query-side embedder would use `search_query`.
8215
+ dialect: {
8216
+ body: (model, inputs) => ({
8217
+ model,
8218
+ texts: [...inputs],
8219
+ input_type: "search_document",
8220
+ embedding_types: ["float"]
8221
+ }),
8222
+ vectors: (json) => json.embeddings?.float
8223
+ }
8186
8224
  },
8187
8225
  options
8188
8226
  )
@@ -8208,7 +8246,7 @@ var deepinfraMemoryEmbeddingProviderAdapter = {
8208
8246
  transport: "remote",
8209
8247
  authProviderId: "deepinfra",
8210
8248
  autoSelectPriority: 13,
8211
- create: (options) => createOpenAiCompatibleRuntime(
8249
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8212
8250
  {
8213
8251
  id: "deepinfra",
8214
8252
  defaultBaseUrl: "https://api.deepinfra.com",
@@ -8234,12 +8272,15 @@ var geminiMemoryEmbeddingProviderAdapter = {
8234
8272
  transport: "remote",
8235
8273
  authProviderId: "gemini",
8236
8274
  autoSelectPriority: 30,
8237
- create: (options) => createOpenAiCompatibleRuntime(
8275
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8238
8276
  {
8239
8277
  id: "gemini",
8240
8278
  defaultBaseUrl: "https://generativelanguage.googleapis.com",
8241
8279
  apiKeyEnv: "GEMINI_API_KEY",
8242
8280
  defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,
8281
+ // theokit#159 — the compat surface is under `/v1beta/openai/`, not the default
8282
+ // `/v1/embeddings`; the previous path 404'd on every call.
8283
+ embeddingsPath: "/v1beta/openai/embeddings",
8243
8284
  dimensionByModel: DIMENSION_BY_MODEL4
8244
8285
  },
8245
8286
  options
@@ -8259,7 +8300,7 @@ var jinaMemoryEmbeddingProviderAdapter = {
8259
8300
  transport: "remote",
8260
8301
  authProviderId: "jina",
8261
8302
  autoSelectPriority: 35,
8262
- create: (options) => createOpenAiCompatibleRuntime(
8303
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8263
8304
  {
8264
8305
  id: "jina",
8265
8306
  defaultBaseUrl: "https://api.jina.ai",
@@ -8282,7 +8323,7 @@ var mistralMemoryEmbeddingProviderAdapter = {
8282
8323
  transport: "remote",
8283
8324
  authProviderId: "mistral",
8284
8325
  autoSelectPriority: 18,
8285
- create: (options) => createOpenAiCompatibleRuntime(
8326
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8286
8327
  {
8287
8328
  id: "mistral",
8288
8329
  defaultBaseUrl: "https://api.mistral.ai",
@@ -8324,7 +8365,7 @@ var ollamaMemoryEmbeddingProviderAdapter = {
8324
8365
  autoSelectPriority: 10,
8325
8366
  create: (options) => {
8326
8367
  const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;
8327
- return createOpenAiCompatibleRuntime(
8368
+ return chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8328
8369
  {
8329
8370
  id: "ollama",
8330
8371
  defaultBaseUrl: "http://localhost:11434",
@@ -8351,7 +8392,7 @@ var openAiMemoryEmbeddingProviderAdapter = {
8351
8392
  transport: "remote",
8352
8393
  authProviderId: "openai",
8353
8394
  autoSelectPriority: 20,
8354
- create: (options) => createOpenAiCompatibleRuntime(
8395
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8355
8396
  {
8356
8397
  id: "openai",
8357
8398
  defaultBaseUrl: "https://api.openai.com",
@@ -8378,7 +8419,7 @@ var openRouterMemoryEmbeddingProviderAdapter = {
8378
8419
  transport: "remote",
8379
8420
  authProviderId: "openrouter",
8380
8421
  autoSelectPriority: 15,
8381
- create: (options) => createOpenAiCompatibleRuntime(
8422
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8382
8423
  {
8383
8424
  id: "openrouter",
8384
8425
  defaultBaseUrl: "https://openrouter.ai/api",
@@ -8406,7 +8447,7 @@ var voyageMemoryEmbeddingProviderAdapter = {
8406
8447
  transport: "remote",
8407
8448
  authProviderId: "voyage",
8408
8449
  autoSelectPriority: 14,
8409
- create: (options) => createOpenAiCompatibleRuntime(
8450
+ create: (options) => chunk7U2HAAWB_cjs.createOpenAiCompatibleRuntime(
8410
8451
  {
8411
8452
  id: "voyage",
8412
8453
  defaultBaseUrl: "https://api.voyageai.com",
@@ -8507,7 +8548,7 @@ function createMemorySearchTool(opts) {
8507
8548
  };
8508
8549
  }
8509
8550
  function createMemoryGetTool(opts) {
8510
- const memoryRoot = path.resolve(chunk2423XDPT_cjs.memoryDir(opts.cwd));
8551
+ const memoryRoot = path.resolve(chunkCN6UX5EV_cjs.memoryDir(opts.cwd));
8511
8552
  return {
8512
8553
  name: "memory_get",
8513
8554
  description: GET_DESCRIPTION,
@@ -8518,7 +8559,7 @@ function createMemoryGetTool(opts) {
8518
8559
  const lines = readNumber(input.lines);
8519
8560
  const resolved = path.resolve(memoryRoot, relPath);
8520
8561
  if (!isPathInside(memoryRoot, resolved)) {
8521
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8562
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8522
8563
  `memory_get rejected path that escapes memory root: ${relPath}`,
8523
8564
  { code: "memory_path_escapes_root" }
8524
8565
  );
@@ -8538,7 +8579,7 @@ function readString(value, errorIfMissing, allowUndefined = false) {
8538
8579
  if (typeof value === "string") return value;
8539
8580
  if (allowUndefined && (value === void 0 || value === null)) return "";
8540
8581
  if (errorIfMissing !== void 0) {
8541
- throw new chunkMHCKWQR3_cjs.ConfigurationError(errorIfMissing, { code: "memory_tool_bad_args" });
8582
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(errorIfMissing, { code: "memory_tool_bad_args" });
8542
8583
  }
8543
8584
  return "";
8544
8585
  }
@@ -8614,7 +8655,7 @@ var LocalAgentMemory = class {
8614
8655
  const openOpts = { cwd: this.workspaceCwd };
8615
8656
  if (embedding !== void 0) openOpts.embedding = embedding;
8616
8657
  if (cfg?.backend !== void 0) openOpts.backend = cfg.backend;
8617
- this.index = await chunk2423XDPT_cjs.IndexManager.open(openOpts);
8658
+ this.index = await chunkCN6UX5EV_cjs.IndexManager.open(openOpts);
8618
8659
  await this.index.sync();
8619
8660
  this.toolsCache = [
8620
8661
  createMemorySearchTool({ index: this.index }),
@@ -8629,7 +8670,7 @@ var LocalAgentMemory = class {
8629
8670
  const warned2 = g[sym];
8630
8671
  if (!warned2.has(message)) {
8631
8672
  warned2.add(message);
8632
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] memory tools unavailable: ${message}
8673
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] memory tools unavailable: ${message}
8633
8674
  `);
8634
8675
  }
8635
8676
  return void 0;
@@ -8638,7 +8679,7 @@ var LocalAgentMemory = class {
8638
8679
  async runActiveMemoryIfEnabled(userText, priorMessages, telemetry) {
8639
8680
  const cfg = this.options.memory?.activeRecall;
8640
8681
  if (cfg?.enabled !== true || this.index === void 0) return void 0;
8641
- if (this.breaker === void 0) this.breaker = new chunkALU3KC4G_cjs.CircuitBreaker();
8682
+ if (this.breaker === void 0) this.breaker = new chunkBPN5ONSW_cjs.CircuitBreaker();
8642
8683
  if (this.cache === void 0) this.cache = new ActiveMemoryCache();
8643
8684
  const result = await runActiveMemory({
8644
8685
  userText,
@@ -8688,7 +8729,7 @@ var LocalAgentMemory = class {
8688
8729
  await this.index.sync();
8689
8730
  } catch (cause) {
8690
8731
  const message = cause instanceof Error ? cause.message : String(cause);
8691
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] session index sync failed: ${message}
8732
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] session index sync failed: ${message}
8692
8733
  `);
8693
8734
  }
8694
8735
  }
@@ -8701,7 +8742,7 @@ var LocalAgentMemory = class {
8701
8742
  return await adapter.create(cfg.model !== void 0 ? { model: cfg.model } : {});
8702
8743
  } catch (cause) {
8703
8744
  const message = cause instanceof Error ? cause.message : String(cause);
8704
- chunkLTCOPATU_cjs.diag(`[theokit-sdk] memory embedding ${cfg.provider} unavailable: ${message}
8745
+ chunkBCQ3E2ZG_cjs.diag(`[theokit-sdk] memory embedding ${cfg.provider} unavailable: ${message}
8705
8746
  `);
8706
8747
  return void 0;
8707
8748
  }
@@ -8737,7 +8778,7 @@ function buildAgentMemory(pluginManager, workspaceCwd, defaultContext) {
8737
8778
  ...partial?.metadata !== void 0 ? { metadata: partial.metadata } : defaultContext?.metadata !== void 0 ? { metadata: defaultContext.metadata } : {}
8738
8779
  };
8739
8780
  if (merged.userId === "") {
8740
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8781
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8741
8782
  "agent.memory requires a userId \u2014 either set AgentOptions.memoryContext.userId or pass ctx.userId at call time.",
8742
8783
  { code: "memory_context_missing_user_id" }
8743
8784
  );
@@ -8747,7 +8788,7 @@ function buildAgentMemory(pluginManager, workspaceCwd, defaultContext) {
8747
8788
  async function requireAdapters() {
8748
8789
  const r = await ensure();
8749
8790
  if (r.adapters.length === 0) {
8750
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8791
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8751
8792
  "No memory adapter registered. Pass a memory plugin in AgentOptions.plugins (e.g. supermemoryMemory({...})).",
8752
8793
  { code: "no_memory_adapter" }
8753
8794
  );
@@ -8788,7 +8829,7 @@ function buildAgentMemory(pluginManager, workspaceCwd, defaultContext) {
8788
8829
  const prefix = id.split(":", 1)[0] ?? "";
8789
8830
  const target = adapters.find((a) => a.id === prefix);
8790
8831
  if (target === void 0) {
8791
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8832
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8792
8833
  `No adapter found for MemoryId prefix "${prefix}" (registered: ${adapters.map((a) => a.id).join(", ")}).`,
8793
8834
  { code: "no_memory_adapter" }
8794
8835
  );
@@ -8861,7 +8902,7 @@ function createLocalAgentMemoryProvider(opts) {
8861
8902
  return { facts: [], systemPromptAdditions: summary };
8862
8903
  },
8863
8904
  async recordSessionSummary(args) {
8864
- await chunk2423XDPT_cjs.writeSessionSummary(args);
8905
+ await chunkCN6UX5EV_cjs.writeSessionSummary(args);
8865
8906
  },
8866
8907
  async sync(handle) {
8867
8908
  const state = handle[INTERNAL_LAM_KEY];
@@ -8939,19 +8980,19 @@ var PersonalityRegistry = class _PersonalityRegistry {
8939
8980
  function addEntity(byName, entity, origin, collisionMap) {
8940
8981
  const fm = entity.frontmatter;
8941
8982
  if (PersonalityRegistry.isReservedClearSlug(fm.name)) {
8942
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8983
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8943
8984
  `Personality name "${fm.name}" is reserved (used to clear active preset)`,
8944
8985
  { code: "personality_reserved_name" }
8945
8986
  );
8946
8987
  }
8947
8988
  if (entity.body.trim().length === 0) {
8948
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
8989
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8949
8990
  `Personality "${fm.name}" has empty body (system prompt required)`,
8950
8991
  { code: "personality_empty_body" }
8951
8992
  );
8952
8993
  }
8953
8994
  if (origin === "project" && collisionMap?.has(fm.name)) {
8954
- chunkFAY3QDGC_cjs.warnOnce(
8995
+ chunk6LGQECT7_cjs.warnOnce(
8955
8996
  `personality-collision-${fm.name}`,
8956
8997
  `[theokit-sdk] personality "${fm.name}" overridden by project preset`
8957
8998
  );
@@ -8980,7 +9021,7 @@ async function performPersonalitySwitch(args) {
8980
9021
  const preset = args.registry.get(args.requestedName);
8981
9022
  if (preset === void 0) {
8982
9023
  const available = args.registry.all().map((p) => p.name).join(", ") || "(none)";
8983
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
9024
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
8984
9025
  `Personality "${args.requestedName}" not found. Available: ${available}`,
8985
9026
  { code: "personality_not_found" }
8986
9027
  );
@@ -9001,14 +9042,14 @@ async function performPersonalitySwitch(args) {
9001
9042
 
9002
9043
  // src/internal/local-agent/local-agent-personality-extensions.ts
9003
9044
  function resolveActivePersonalityPreset(args) {
9004
- const forkCtx = chunkFAY3QDGC_cjs.currentPersonalityContext();
9045
+ const forkCtx = chunk6LGQECT7_cjs.currentPersonalityContext();
9005
9046
  const slug = forkCtx !== void 0 ? forkCtx.slug : args.personalityStore.active(args.agentId);
9006
9047
  if (slug === void 0) return void 0;
9007
9048
  return args.personalityRegistry?.get(slug);
9008
9049
  }
9009
9050
  async function ensurePersonalityRegistryIfNeeded(args) {
9010
9051
  if (args.personalityRegistry !== void 0) return args.personalityRegistry;
9011
- const forkSlug = chunkFAY3QDGC_cjs.currentPersonalityContext()?.slug;
9052
+ const forkSlug = chunk6LGQECT7_cjs.currentPersonalityContext()?.slug;
9012
9053
  const ownSlug = args.personalityStore.active(args.agentId);
9013
9054
  if (forkSlug === void 0 && ownSlug === void 0) return void 0;
9014
9055
  return await PersonalityRegistry.load(args.workspaceCwd);
@@ -9022,8 +9063,8 @@ ${preset.systemPrompt}`;
9022
9063
  }
9023
9064
  async function localAgentUsePersonality(args) {
9024
9065
  if (args.disposed) throw new Error("Agent has been disposed");
9025
- if (chunkFAY3QDGC_cjs.currentPersonalityContext() !== void 0) {
9026
- chunkFAY3QDGC_cjs.warnPersonalitySwitchInsideFork(args.agentId);
9066
+ if (chunk6LGQECT7_cjs.currentPersonalityContext() !== void 0) {
9067
+ chunk6LGQECT7_cjs.warnPersonalitySwitchInsideFork(args.agentId);
9027
9068
  return null;
9028
9069
  }
9029
9070
  let registry = args.personalityRegistry;
@@ -9040,8 +9081,8 @@ async function localAgentUsePersonality(args) {
9040
9081
  registry,
9041
9082
  store: args.personalityStore,
9042
9083
  invalidateCache: (reason) => args.invalidateCache(reason),
9043
- appendSessionMessage: (msg) => chunkH5YVJB4K_cjs.appendSessionMessage(args.agentId, msg),
9044
- clearSession: () => chunkH5YVJB4K_cjs.clearSession(args.agentId),
9084
+ appendSessionMessage: (msg) => chunkDCXRHCZJ_cjs.appendSessionMessage(args.agentId, msg),
9085
+ clearSession: () => chunkDCXRHCZJ_cjs.clearSession(args.agentId),
9045
9086
  opts: args.opts ?? {}
9046
9087
  })
9047
9088
  );
@@ -9050,9 +9091,9 @@ async function localAgentUsePersonality(args) {
9050
9091
  // src/internal/local-agent/local-agent-runtime-extensions.ts
9051
9092
  function localAgentRunUntil(agent, goal, options) {
9052
9093
  async function* wrap() {
9053
- const { runUntilImpl } = await import('./run-until-ZZ2JLPJM.cjs');
9094
+ const { runUntilImpl } = await import('./run-until-L5KQD3PV.cjs');
9054
9095
  const buildDeps = async () => {
9055
- const { judgeCallImpl } = await import('./judge-call-SP3G3X2Y.cjs');
9096
+ const { judgeCallImpl } = await import('./judge-call-U2D33JOW.cjs');
9056
9097
  const { getAgentFacade } = await import('./agent-factory-registry-UU46BUMU.cjs');
9057
9098
  const create = getAgentFacade().create;
9058
9099
  return {
@@ -9085,7 +9126,7 @@ async function* localAgentStreamToCompletion(agent, message, options) {
9085
9126
  async function localAgentFork(parent, options) {
9086
9127
  const { forkAgentImpl } = await import('./fork-agent-Y2IK2RYU.cjs');
9087
9128
  const { getAgentFacade } = await import('./agent-factory-registry-UU46BUMU.cjs');
9088
- const { withPersonalityContext } = await import('./context-ZV33V4DC.cjs');
9129
+ const { withPersonalityContext } = await import('./context-2FZSC6VQ.cjs');
9089
9130
  const create = getAgentFacade().create;
9090
9131
  return withPersonalityContext(
9091
9132
  { slug: parent.personalitySlugSnapshot, isFork: true },
@@ -9145,7 +9186,7 @@ function wrapRunWithCompletionCheck(args) {
9145
9186
  judgeOpts
9146
9187
  );
9147
9188
  const complete = !verdict.parseFailed && verdict.verdict === "done";
9148
- chunk6EDQBX7U_cjs.emitRunEvent(args.onRunEvent, {
9189
+ chunkN475ETD6_cjs.emitRunEvent(args.onRunEvent, {
9149
9190
  type: "completion_check",
9150
9191
  complete,
9151
9192
  reason: verdict.reason
@@ -9241,6 +9282,9 @@ var SUPPORTED = /* @__PURE__ */ new Set([
9241
9282
  "cancel",
9242
9283
  "conversation"
9243
9284
  ]);
9285
+ function emptyTimeline() {
9286
+ return emptyStream();
9287
+ }
9244
9288
  function emptyStream() {
9245
9289
  return {
9246
9290
  next: () => Promise.resolve({ done: true, value: void 0 }),
@@ -9265,6 +9309,9 @@ function createTripwireRun(args) {
9265
9309
  status: "cancelled",
9266
9310
  ...args.model !== void 0 ? { model: args.model } : {},
9267
9311
  stream: () => emptyStream(),
9312
+ // theokit#140 - a tripwire run never executed, so its timeline is empty by construction, the
9313
+ // same reason `stream()` is. Both are empty for the same fact, not by coincidence.
9314
+ events: () => emptyTimeline(),
9268
9315
  wait: () => Promise.resolve(result),
9269
9316
  cancel: () => Promise.resolve(),
9270
9317
  conversation: () => Promise.resolve([]),
@@ -9286,7 +9333,7 @@ function wrapRunWithOutputProcessors(args) {
9286
9333
  if (result.status !== "finished" || result.result === void 0) return result;
9287
9334
  const res = await runOutputProcessors(args.processors, result.result, args.agentId);
9288
9335
  if (res.kind === "ok") return { ...result, result: res.value };
9289
- chunk6EDQBX7U_cjs.emitRunEvent(args.onRunEvent, {
9336
+ chunkN475ETD6_cjs.emitRunEvent(args.onRunEvent, {
9290
9337
  type: "tripwire",
9291
9338
  reason: res.tripwire.reason,
9292
9339
  processorId: res.tripwire.processorId
@@ -9361,7 +9408,7 @@ async function applyInputProcessors(inputs, message, rawUserText, options, sendM
9361
9408
  }
9362
9409
  const res = await runInputProcessors(processors, rawUserText, inputs.agentId);
9363
9410
  if (res.kind === "tripwire") {
9364
- chunk6EDQBX7U_cjs.emitRunEvent(options.onRunEvent, {
9411
+ chunkN475ETD6_cjs.emitRunEvent(options.onRunEvent, {
9365
9412
  type: "tripwire",
9366
9413
  reason: res.tripwire.reason,
9367
9414
  processorId: res.tripwire.processorId
@@ -9378,7 +9425,7 @@ async function applyInputProcessors(inputs, message, rawUserText, options, sendM
9378
9425
  return { userText: res.value, effectiveMessage };
9379
9426
  }
9380
9427
  async function executeSendLocked(inputs, message, options) {
9381
- if (inputs.disposed) throw new chunkMHCKWQR3_cjs.AgentDisposedError(inputs.agentId);
9428
+ if (inputs.disposed) throw new chunkIHFNRNTJ_cjs.AgentDisposedError(inputs.agentId);
9382
9429
  await consumePending(inputs.agentId, inputs.invalidationPending, inputs.clearInvalidation, inputs.reload);
9383
9430
  const sendModel = normalizeModel(options.model);
9384
9431
  inputs.applyModelOverride(sendModel);
@@ -9389,7 +9436,7 @@ async function executeSendLocked(inputs, message, options) {
9389
9436
  if (inputs.options.onBeforeSend !== void 0) {
9390
9437
  await inputs.options.onBeforeSend({
9391
9438
  conversationId: inputs.agentId,
9392
- previousMessageCount: chunkH5YVJB4K_cjs.getSessionMessages(inputs.agentId).length
9439
+ previousMessageCount: chunkDCXRHCZJ_cjs.getSessionMessages(inputs.agentId).length
9393
9440
  });
9394
9441
  }
9395
9442
  await inputs.runPreHook(userText);
@@ -9401,8 +9448,8 @@ async function executeSendLocked(inputs, message, options) {
9401
9448
  userText,
9402
9449
  sendOptions: options
9403
9450
  });
9404
- const priorMessages = [...chunkH5YVJB4K_cjs.getSessionMessages(inputs.agentId)];
9405
- chunkH5YVJB4K_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
9451
+ const priorMessages = [...chunkDCXRHCZJ_cjs.getSessionMessages(inputs.agentId)];
9452
+ chunkDCXRHCZJ_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
9406
9453
  await persistMemoryFactIfWritePrompt(inputs.workspaceCwd, inputs.options.memory, userText);
9407
9454
  const memoryFacts = await readMemoryForSend(inputs.workspaceCwd, inputs.options.memory);
9408
9455
  const portPathActive = shouldUsePortMemoryPath();
@@ -9460,7 +9507,7 @@ async function executeSendLocked(inputs, message, options) {
9460
9507
  function buildCompletionCheckDeps() {
9461
9508
  return {
9462
9509
  judge: async (ctx, opts) => {
9463
- const { judgeCallImpl } = await import('./judge-call-SP3G3X2Y.cjs');
9510
+ const { judgeCallImpl } = await import('./judge-call-U2D33JOW.cjs');
9464
9511
  const { getAgentFacade } = await import('./agent-factory-registry-UU46BUMU.cjs');
9465
9512
  return judgeCallImpl(ctx, opts, { create: getAgentFacade().create });
9466
9513
  }
@@ -9480,7 +9527,7 @@ function registerRunAsTask(run, agentId, taskOpt, userText) {
9480
9527
  promptPreview: userText.slice(0, 120),
9481
9528
  ...opts.meta ?? {}
9482
9529
  };
9483
- void chunk6EDQBX7U_cjs.submit({
9530
+ void chunkN475ETD6_cjs.submit({
9484
9531
  kind: "run",
9485
9532
  work: async (ctx) => {
9486
9533
  ctx.signal.addEventListener(
@@ -9564,7 +9611,7 @@ var LocalAgent = class {
9564
9611
  this.options = options;
9565
9612
  this.workspaceCwd = resolveCwd(options.local?.cwd);
9566
9613
  this.transcriptBaseDir = resolveBaseDir(options.local?.baseDir);
9567
- this.sessionStore = options.local?.sessionStore ?? new chunkITLS5LRF_cjs.FsSessionStore({ baseDir: this.transcriptBaseDir, cwd: this.workspaceCwd });
9614
+ this.sessionStore = options.local?.sessionStore ?? new chunk74D7KSBP_cjs.FsSessionStore({ baseDir: this.transcriptBaseDir, cwd: this.workspaceCwd });
9568
9615
  this.settingSourcesIncludeProject = includesSetting(options, "project");
9569
9616
  this.settingSourcesIncludePlugins = includesSetting(options, "plugins");
9570
9617
  const sub = bootstrapSubmanagers({
@@ -9607,17 +9654,17 @@ var LocalAgent = class {
9607
9654
  if (this.pluginsManager !== void 0) await this.pluginsManager.initialize();
9608
9655
  const codePlugins = chunkBV2MWEMV_cjs.extractCodePlugins(this.options.plugins);
9609
9656
  await this.pluginManagerCode.initialize(codePlugins);
9610
- this.resolvedSubagents = await chunkGM7QDQ24_cjs.loadSubagents(
9657
+ this.resolvedSubagents = await chunkW4WKVOOQ_cjs.loadSubagents(
9611
9658
  this.workspaceCwd,
9612
9659
  this.settingSourcesIncludeProject,
9613
9660
  this.options.agents
9614
9661
  );
9615
- await adquirirLeaseSePossivel(this.sessionStore, this.agentId);
9662
+ await acquireLeaseIfPossible(this.sessionStore, this.agentId);
9616
9663
  try {
9617
- await chunkH5YVJB4K_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
9664
+ await chunkDCXRHCZJ_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
9618
9665
  await this.personalityStore.hydrate(this.agentId);
9619
9666
  } catch (err) {
9620
- await soltarLeaseSePossivel(this.sessionStore, this.agentId);
9667
+ await releaseLeaseIfPossible(this.sessionStore, this.agentId);
9621
9668
  throw err;
9622
9669
  }
9623
9670
  }
@@ -9650,16 +9697,16 @@ var LocalAgent = class {
9650
9697
  });
9651
9698
  }
9652
9699
  /**
9653
- * A janela de contexto declarada na seleção de modelo, no formato de spread condicional.
9700
+ * The context window declared on the model selection, in conditional-spread form.
9654
9701
  *
9655
- * M94 — sem isto, o `override` de `resolveEffectiveContextWindow` existia desde o M77 e nenhum
9656
- * call site de produção o passava: um modelo de 400k sem entrada de catálogo era orçado contra o
9657
- * piso de 128k. Método próprio porque o spread inline empurrava `runLockedSendCycle` para além do
9658
- * teto de complexidade cognitiva do projeto.
9702
+ * M94 — without this, `resolveEffectiveContextWindow`'s `override` had existed since M77 and no
9703
+ * production call site passed it: a 400k model with no catalog entry was budgeted against the
9704
+ * 128k floor. Its own method because the inline spread pushed `runLockedSendCycle` past the
9705
+ * project's cognitive-complexity ceiling.
9659
9706
  */
9660
- #janelaDeclarada() {
9661
- const declarada = this.model?.contextWindow;
9662
- return declarada !== void 0 ? { contextWindow: declarada } : {};
9707
+ #declaredWindow() {
9708
+ const declared = this.model?.contextWindow;
9709
+ return declared !== void 0 ? { contextWindow: declared } : {};
9663
9710
  }
9664
9711
  async runLockedSendCycle(message, options, sendSpan, resolve, reject) {
9665
9712
  const userText = typeof message === "string" ? message : message.text;
@@ -9688,7 +9735,7 @@ var LocalAgent = class {
9688
9735
  workspaceCwd: this.workspaceCwd,
9689
9736
  sessionStore: this.sessionStore,
9690
9737
  model: this.model?.id ?? "unknown",
9691
- ...this.#janelaDeclarada(),
9738
+ ...this.#declaredWindow(),
9692
9739
  // M50 — the auto-compaction summarizer resolves credentials like the run itself.
9693
9740
  ...this.options.apiKey !== void 0 ? { apiKey: this.options.apiKey } : {},
9694
9741
  ...options.onRunEvent !== void 0 ? { onRunEvent: options.onRunEvent } : {},
@@ -9763,7 +9810,7 @@ var LocalAgent = class {
9763
9810
  agentId: this.agentId
9764
9811
  });
9765
9812
  if (preRun.blocked) {
9766
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
9813
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
9767
9814
  `preRun hook denied execution: ${preRun.reason ?? "unspecified"}`,
9768
9815
  { code: "hook_denied" }
9769
9816
  );
@@ -9844,7 +9891,7 @@ var LocalAgent = class {
9844
9891
  }
9845
9892
  // biome-ignore format: G8 budget — see listArtifacts.
9846
9893
  downloadArtifact(_path) {
9847
- return Promise.reject(new chunkMHCKWQR3_cjs.UnsupportedRunOperationError("Artifacts are not supported for local agents", "downloadArtifact"));
9894
+ return Promise.reject(new chunkIHFNRNTJ_cjs.UnsupportedRunOperationError("Artifacts are not supported for local agents", "downloadArtifact"));
9848
9895
  }
9849
9896
  // biome-ignore format: G8 budget — delegates to `local-agent-runtime-extensions.ts`; kept 1-line.
9850
9897
  runUntil(goal, options) {
@@ -9867,7 +9914,7 @@ function resolveCwd(cwd) {
9867
9914
  return (Array.isArray(cwd) ? cwd[0] : cwd) ?? process.cwd();
9868
9915
  }
9869
9916
  function resolveBaseDir(baseDir) {
9870
- return baseDir === void 0 ? chunkIEUDKUPM_cjs.defaultBaseDir() : chunkIEUDKUPM_cjs.expandTilde(baseDir);
9917
+ return baseDir === void 0 ? chunkZ2CUEBXV_cjs.defaultBaseDir() : chunkZ2CUEBXV_cjs.expandTilde(baseDir);
9871
9918
  }
9872
9919
  function includesSetting(options, source) {
9873
9920
  const sources = options.local?.settingSources;
@@ -9892,7 +9939,7 @@ async function guardAgainstIdCollision(options) {
9892
9939
  const persistenceCwd = resolveAgentPersistenceCwd(options);
9893
9940
  await hydrateRegistryFromDisk(persistenceCwd);
9894
9941
  if (getRegisteredAgent(options.agentId) !== void 0) {
9895
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
9942
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
9896
9943
  `Agent "${options.agentId}" already exists. Use Agent.resume("${options.agentId}") to reattach, or pick a different agentId.`,
9897
9944
  { code: "agent_id_already_exists" }
9898
9945
  );
@@ -9925,7 +9972,7 @@ async function maybeInjectHandoffTools(options) {
9925
9972
  const spec = "@theokit/sdk-handoff/internal/tool-injector";
9926
9973
  mod = await import(spec);
9927
9974
  } catch (err) {
9928
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
9975
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
9929
9976
  "Agent.create({ handoffs: [...] }) requires @theokit/sdk-handoff. Install it: pnpm add @theokit/sdk-handoff. Or migrate to the preferred plugin pattern: plugins: [Handoff.asPlugin({ targets: [...] })] (see docs/migration/1-x-to-2-0.md#handoff).",
9930
9977
  { code: "handoff_package_missing", cause: err }
9931
9978
  );
@@ -9945,9 +9992,9 @@ async function maybeInjectHandoffTools(options) {
9945
9992
  async function createLocalAgent(options) {
9946
9993
  const apiKey = resolveApiKey(options.apiKey);
9947
9994
  if (apiKey === void 0) {
9948
- throw new chunkMHCKWQR3_cjs.AuthenticationError("Missing API key", { code: "missing_api_key" });
9995
+ throw new chunkIHFNRNTJ_cjs.AuthenticationError("Missing API key", { code: "missing_api_key" });
9949
9996
  }
9950
- const willFlowToProvider = !chunkALU3KC4G_cjs.isFixtureApiKey(apiKey) && !chunkALU3KC4G_cjs.shouldUseRealLocalRuntime(apiKey);
9997
+ const willFlowToProvider = !chunkBPN5ONSW_cjs.isFixtureApiKey(apiKey) && !chunkBPN5ONSW_cjs.shouldUseRealLocalRuntime(apiKey);
9951
9998
  const shape = validateApiKeyShape(apiKey, {
9952
9999
  strict: willFlowToProvider,
9953
10000
  // `options.model` is already normalized by `runCreateUnderSpan`; `normalizeModel`
@@ -9956,10 +10003,10 @@ async function createLocalAgent(options) {
9956
10003
  ...willFlowToProvider ? { provider: providerFromModelId(normalizeModel(options.model)?.id) } : {}
9957
10004
  });
9958
10005
  if (shape.malformed) {
9959
- throw new chunkMHCKWQR3_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
10006
+ throw new chunkIHFNRNTJ_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
9960
10007
  }
9961
- if (!chunkALU3KC4G_cjs.isFixtureApiKey(apiKey) && chunkALU3KC4G_cjs.getConfiguredBaseUrl() === void 0 && !chunkALU3KC4G_cjs.shouldUseRealLocalRuntime(apiKey)) {
9962
- throw new chunkMHCKWQR3_cjs.AuthenticationError("Invalid API key", {
10008
+ if (!chunkBPN5ONSW_cjs.isFixtureApiKey(apiKey) && chunkBPN5ONSW_cjs.getConfiguredBaseUrl() === void 0 && !chunkBPN5ONSW_cjs.shouldUseRealLocalRuntime(apiKey)) {
10009
+ throw new chunkIHFNRNTJ_cjs.AuthenticationError("Invalid API key", {
9963
10010
  code: "authentication_error"
9964
10011
  });
9965
10012
  }
@@ -9970,19 +10017,19 @@ async function createLocalAgent(options) {
9970
10017
  async function createCloudAgent(options) {
9971
10018
  const apiKey = resolveApiKey(options.apiKey);
9972
10019
  if (apiKey === void 0) {
9973
- throw new chunkMHCKWQR3_cjs.ConfigurationError("Missing API key for cloud agent", {
10020
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError("Missing API key for cloud agent", {
9974
10021
  code: "missing_api_key"
9975
10022
  });
9976
10023
  }
9977
10024
  const shape = validateApiKeyShape(apiKey);
9978
10025
  if (shape.malformed) {
9979
- throw new chunkMHCKWQR3_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
10026
+ throw new chunkIHFNRNTJ_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
9980
10027
  }
9981
- const baseUrl = chunkALU3KC4G_cjs.getConfiguredBaseUrl();
10028
+ const baseUrl = chunkBPN5ONSW_cjs.getConfiguredBaseUrl();
9982
10029
  if (baseUrl === void 0) {
9983
10030
  return new CloudAgent(options);
9984
10031
  }
9985
- const response = await chunkALU3KC4G_cjs.httpRequest("/v1/agents", {
10032
+ const response = await chunkBPN5ONSW_cjs.httpRequest("/v1/agents", {
9986
10033
  apiKey,
9987
10034
  method: "POST",
9988
10035
  body: {
@@ -10007,7 +10054,7 @@ function resolveAgentPersistenceCwd(options) {
10007
10054
  return process.cwd();
10008
10055
  }
10009
10056
  async function rehydrateExistingAgent(agentId, existing, options) {
10010
- await chunkALU3KC4G_cjs.discoverProviderPlugins();
10057
+ await chunkBPN5ONSW_cjs.discoverProviderPlugins();
10011
10058
  await validateRehydratedAgent(agentId, existing);
10012
10059
  const mergedLocal = options.local !== void 0 && existing.options.local !== void 0 ? { ...existing.options.local, ...options.local } : options.local ?? existing.options.local;
10013
10060
  const mergedOptions = {
@@ -10038,7 +10085,7 @@ async function validateRehydratedAgent(agentId, entry) {
10038
10085
  throw new Error(`Workspace path is not a directory: ${candidate}`);
10039
10086
  }
10040
10087
  } catch (cause) {
10041
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(
10088
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10042
10089
  `Agent "${agentId}" cannot be rehydrated \u2014 workspace cwd "${candidate}" is missing or inaccessible.`,
10043
10090
  { code: "agent_rehydration_failed", cause }
10044
10091
  );
@@ -10090,7 +10137,7 @@ async function getRegisteredAgentOrThrow(agentId) {
10090
10137
  agent = getRegisteredAgent(agentId);
10091
10138
  }
10092
10139
  if (agent === void 0) {
10093
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(`Agent ${agentId} not found`, { code: "unknown_agent" });
10140
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(`Agent ${agentId} not found`, { code: "unknown_agent" });
10094
10141
  }
10095
10142
  return agent;
10096
10143
  }
@@ -10135,7 +10182,7 @@ var Agent = class _Agent {
10135
10182
  pluginCount: enabledPluginNames(options.plugins).length
10136
10183
  });
10137
10184
  try {
10138
- await chunkALU3KC4G_cjs.discoverProviderPlugins();
10185
+ await chunkBPN5ONSW_cjs.discoverProviderPlugins();
10139
10186
  const agent = await runCreateUnderSpan(options, span);
10140
10187
  return agent;
10141
10188
  } catch (err) {
@@ -10161,8 +10208,8 @@ var Agent = class _Agent {
10161
10208
  const run = await agent.send(message);
10162
10209
  const result = await run.wait();
10163
10210
  if (options.throwOnError === true && result.status === "error" && result.error !== void 0) {
10164
- throw new chunkMHCKWQR3_cjs.AgentRunError(result.error.message, {
10165
- code: chunkMHCKWQR3_cjs.coerceToKnownAgentRunErrorCode(result.error.code),
10211
+ throw new chunkIHFNRNTJ_cjs.AgentRunError(result.error.message, {
10212
+ code: chunkIHFNRNTJ_cjs.coerceToKnownAgentRunErrorCode(result.error.code),
10166
10213
  cause: result.error.cause
10167
10214
  });
10168
10215
  }
@@ -10189,7 +10236,7 @@ var Agent = class _Agent {
10189
10236
  if (existing !== void 0) {
10190
10237
  return await rehydrateExistingAgent(agentId, existing, options);
10191
10238
  }
10192
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(
10239
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10193
10240
  `Agent "${agentId}" not found. Use Agent.create({ agentId, ... }) for first-time setup, or catch UnknownAgentError to branch resume-vs-create.`,
10194
10241
  { code: "unknown_agent" }
10195
10242
  );
@@ -10218,7 +10265,7 @@ var Agent = class _Agent {
10218
10265
  * @public
10219
10266
  */
10220
10267
  static async generateObject(options) {
10221
- const { generateObjectImpl } = await import('./generate-object-5SCEH2EE.cjs');
10268
+ const { generateObjectImpl } = await import('./generate-object-UF6WIZLF.cjs');
10222
10269
  return generateObjectImpl(options, {
10223
10270
  create: (opts) => _Agent.create(opts),
10224
10271
  delete: (agentId) => _Agent.delete(agentId)
@@ -10242,7 +10289,7 @@ var Agent = class _Agent {
10242
10289
  delete: (agentId) => _Agent.delete(agentId)
10243
10290
  };
10244
10291
  async function* wrapper() {
10245
- streamObjectImport ??= import('./stream-object-Y7YCX3BI.cjs');
10292
+ streamObjectImport ??= import('./stream-object-4FDU76YW.cjs');
10246
10293
  const { streamObjectImpl } = await streamObjectImport;
10247
10294
  yield* streamObjectImpl(options, deps);
10248
10295
  }
@@ -10266,7 +10313,7 @@ var Agent = class _Agent {
10266
10313
  * @public
10267
10314
  */
10268
10315
  static async batch(prompts, options) {
10269
- const { batchImpl } = await import('./batch-3SEPDXCU.cjs');
10316
+ const { batchImpl } = await import('./batch-X6JKGDPK.cjs');
10270
10317
  return batchImpl(prompts, options, { create: (opts) => _Agent.create(opts) });
10271
10318
  }
10272
10319
  /**
@@ -10290,7 +10337,7 @@ var Agent = class _Agent {
10290
10337
  *
10291
10338
  * This bullet used to say the opposite ("Disposed agents are NOT auto-deleted...
10292
10339
  * call `Agent.delete(agentId)` first"). It was measured false in M91:
10293
- * `tests/m91-getorcreate-apos-dispose.test.ts` builds an agent, disposes it, and
10340
+ * `tests/m91-getorcreate-after-dispose.test.ts` builds an agent, disposes it, and
10294
10341
  * gets a different instance back. The claim was about the PERSISTENT registry and
10295
10342
  * read as being about the live cache — and consumers built around the wrong half.
10296
10343
  * The agent-builder's M85 interrupt rotates the session id to work around a
@@ -10346,14 +10393,14 @@ var Agent = class _Agent {
10346
10393
  */
10347
10394
  static async getRun(runId, options = {}) {
10348
10395
  if (options.runtime === "cloud") {
10349
- throw new chunkMHCKWQR3_cjs.ConfigurationError(
10396
+ throw new chunkIHFNRNTJ_cjs.ConfigurationError(
10350
10397
  "Cloud runtime is pre-release. Theo PaaS endpoints are not wired yet \u2014 getRun({ runtime: 'cloud' }) will be enabled when the PaaS ships.",
10351
10398
  { code: "cloud_runtime_pre_release" }
10352
10399
  );
10353
10400
  }
10354
10401
  const existing = getRun(runId);
10355
10402
  if (existing !== void 0) return existing;
10356
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(
10403
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10357
10404
  `Run ${runId} is not in this process's registry. It may have been disposed, persisted in a previous process, or never created.`,
10358
10405
  { code: "run_not_found" }
10359
10406
  );
@@ -10400,13 +10447,13 @@ var Agent = class _Agent {
10400
10447
  reg = getRegisteredAgent(agentId);
10401
10448
  }
10402
10449
  if (reg === void 0 || reg.runtime !== "local") {
10403
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(
10450
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10404
10451
  `No local agent "${agentId}" registered \u2014 compact targets local sessions.`
10405
10452
  );
10406
10453
  }
10407
- const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-H5TKLD55.cjs');
10408
- const { cwd, model, store } = await abrirStoreLocal(reg);
10409
- return chunkH5YVJB4K_cjs.enqueueSessionWrite(
10454
+ const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-VVT6IBJG.cjs');
10455
+ const { cwd, model, store } = await openLocalStore(reg);
10456
+ return chunkDCXRHCZJ_cjs.enqueueSessionWrite(
10410
10457
  cwd,
10411
10458
  agentId,
10412
10459
  () => compactSessionTranscript({
@@ -10436,12 +10483,12 @@ var Agent = class _Agent {
10436
10483
  reg = getRegisteredAgent(agentId);
10437
10484
  }
10438
10485
  if (reg === void 0 || reg.runtime !== "local") {
10439
- throw new chunkMHCKWQR3_cjs.UnknownAgentError(
10486
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10440
10487
  `No local agent "${agentId}" registered \u2014 injectSessionTurn targets local sessions.`
10441
10488
  );
10442
10489
  }
10443
- const { injectSessionTurn } = await import('./inject-session-DM4SKTZO.cjs');
10444
- const { cwd, model, store } = await abrirStoreLocal(reg);
10490
+ const { injectSessionTurn } = await import('./inject-session-LFCYVSLJ.cjs');
10491
+ const { cwd, model, store } = await openLocalStore(reg);
10445
10492
  await injectSessionTurn({
10446
10493
  store,
10447
10494
  loc: { cwd, agentId, model },
@@ -10450,6 +10497,86 @@ var Agent = class _Agent {
10450
10497
  assistantText: turn.assistantText
10451
10498
  });
10452
10499
  }
10500
+ /**
10501
+ * theokit#146 — read a LOCAL agent's persisted transcript as STRUCTURE, for rendering.
10502
+ *
10503
+ * A resumed session already replays correctly to the model, but a host had no way to draw it:
10504
+ * the only projection available folded a tool call to the string `[tool call] NAME`, dropping the
10505
+ * call id and every argument. A card UI got prose, so cross-restart resume was worth less than
10506
+ * starting fresh — which is what at least one consumer did.
10507
+ *
10508
+ * Each returned message carries both projections: `text` (unchanged, what the model replay uses)
10509
+ * and `parts` (`text` / `tool_use` / `tool_result` with ids, names, arguments and the
10510
+ * `toolUseId` that correlates a result back to its call).
10511
+ *
10512
+ * Read-only and local-only: it opens the agent's session store and walks the transcript, exactly
10513
+ * as {@link Agent.compact} and {@link Agent.injectSessionTurn} do. It appends nothing.
10514
+ *
10515
+ * @throws UnknownAgentError when `agentId` names no local agent.
10516
+ * @public
10517
+ */
10518
+ static async transcript(agentId) {
10519
+ let reg = getRegisteredAgent(agentId);
10520
+ if (reg === void 0) {
10521
+ await hydrateRegistryFromDisk(process.cwd());
10522
+ reg = getRegisteredAgent(agentId);
10523
+ }
10524
+ if (reg === void 0 || reg.runtime !== "local") {
10525
+ throw new chunkIHFNRNTJ_cjs.UnknownAgentError(
10526
+ `No local agent "${agentId}" registered \u2014 transcript targets local sessions.`
10527
+ );
10528
+ }
10529
+ const { readSessionMessages } = await import('./agent-session-store-N4TVKHBU.cjs');
10530
+ const { store } = await openLocalStore(reg);
10531
+ return readSessionMessages(store, agentId);
10532
+ }
10533
+ /**
10534
+ * theokit#123 — read-only introspection of a registered agent's tools and subagents.
10535
+ *
10536
+ * `Agent.list()` / `Agent.get()` enumerate agents and `agent.skills.list()` covers skills, but
10537
+ * tools and subagents lived only on `RegisteredAgent.options` — an internal contract. A
10538
+ * reflection endpoint (theokit-studio's `theokit dev`) therefore had to report empty lists for
10539
+ * both, and say so with an `unavailable_reason`.
10540
+ *
10541
+ * A PROJECTION, not the options object. Tool handlers and subagent prompts are stripped: a
10542
+ * handler is an executable that cannot cross a process boundary, and a prompt is the agent's
10543
+ * instructions rather than its signature — a reflection endpoint serializes what it is handed.
10544
+ *
10545
+ * @throws UnknownAgentError when `agentId` names no registered agent.
10546
+ * @public
10547
+ */
10548
+ static async describe(agentId) {
10549
+ const agent = await getRegisteredAgentOrThrow(agentId);
10550
+ const { loadSubagents: loadSubagents2 } = await import('./subagents-loader-A4W6C3QP.cjs');
10551
+ const settingSources = agent.options.local?.settingSources;
10552
+ const subagents = await loadSubagents2(
10553
+ agent.cwd ?? process.cwd(),
10554
+ settingSources === void 0 || settingSources.includes("project"),
10555
+ agent.options.agents
10556
+ );
10557
+ return {
10558
+ agentId: agent.agentId,
10559
+ runtime: agent.runtime,
10560
+ ...agent.model !== void 0 ? { model: agent.model } : {},
10561
+ // Always arrays, so a caller can tell "this agent has none" from "the SDK did not say".
10562
+ //
10563
+ // Honest limit, stated because the alternative is an implied claim: `tools` is still the
10564
+ // DECLARED catalog. Plugin tools and the reasoning `think` tool are assembled per run by
10565
+ // `buildCustomToolsInput`, so they are not knowable from the registry alone. Documented on
10566
+ // `AgentDescription.tools`.
10567
+ tools: (agent.options.tools ?? []).map((tool) => ({
10568
+ name: tool.name,
10569
+ description: tool.description,
10570
+ inputSchema: tool.inputSchema
10571
+ })),
10572
+ subagents: Object.entries(subagents).map(([name, def]) => ({
10573
+ name,
10574
+ description: def.description,
10575
+ ...def.model !== void 0 ? { model: def.model } : {},
10576
+ ...def.tools !== void 0 ? { tools: def.tools } : {}
10577
+ }))
10578
+ };
10579
+ }
10453
10580
  /**
10454
10581
  * Permanently delete a cloud agent.
10455
10582
  *
@@ -10464,12 +10591,12 @@ async function getOrCreateUncached(agentId, options) {
10464
10591
  try {
10465
10592
  return await Agent.resume(agentId, options);
10466
10593
  } catch (err) {
10467
- if (!(err instanceof chunkMHCKWQR3_cjs.UnknownAgentError)) throw err;
10594
+ if (!(err instanceof chunkIHFNRNTJ_cjs.UnknownAgentError)) throw err;
10468
10595
  }
10469
10596
  try {
10470
10597
  return await Agent.create({ ...options, agentId });
10471
10598
  } catch (err) {
10472
- if (err instanceof chunkMHCKWQR3_cjs.ConfigurationError && err.code === "agent_id_already_exists") {
10599
+ if (err instanceof chunkIHFNRNTJ_cjs.ConfigurationError && err.code === "agent_id_already_exists") {
10473
10600
  return await Agent.resume(agentId, options);
10474
10601
  }
10475
10602
  throw err;
@@ -10483,12 +10610,12 @@ chunkNINIJCHU_cjs.setAgentFacade({
10483
10610
  resume: (agentId, options) => Agent.resume(agentId, options),
10484
10611
  batch: (prompts, options) => Agent.batch(prompts, options)
10485
10612
  });
10486
- async function abrirStoreLocal(reg) {
10613
+ async function openLocalStore(reg) {
10487
10614
  const cwd = reg.cwd ?? process.cwd();
10488
10615
  const optModel = reg.options.model;
10489
10616
  const model = reg.model?.id ?? (typeof optModel === "string" ? optModel : optModel?.id) ?? "unknown";
10490
- const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-7E7UPLF2.cjs');
10491
- const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-EAKR4D2W.cjs');
10617
+ const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-J5MCFFUM.cjs');
10618
+ const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-H7NUFXXM.cjs');
10492
10619
  const baseDir = reg.options.local?.baseDir !== void 0 ? expandTilde2(reg.options.local.baseDir) : defaultBaseDir2();
10493
10620
  return { cwd, model, store: new FsSessionStore2({ baseDir, cwd }) };
10494
10621
  }
@@ -10505,5 +10632,5 @@ exports.generateCronId = generateCronId;
10505
10632
  exports.getPricingEntry = getPricingEntry;
10506
10633
  exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
10507
10634
  exports.resolveApiKey = resolveApiKey;
10508
- //# sourceMappingURL=chunk-W52DKZBR.cjs.map
10509
- //# sourceMappingURL=chunk-W52DKZBR.cjs.map
10635
+ //# sourceMappingURL=chunk-INSFS5GT.cjs.map
10636
+ //# sourceMappingURL=chunk-INSFS5GT.cjs.map