@theokit/sdk 4.24.0 → 4.26.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 (382) hide show
  1. package/dist/a2a/index.cjs +10 -171
  2. package/dist/a2a/index.cjs.map +1 -1
  3. package/dist/a2a/index.js +3 -170
  4. package/dist/a2a/index.js.map +1 -1
  5. package/dist/agent-factory-registry-UU46BUMU.cjs +16 -0
  6. package/dist/agent-factory-registry-UU46BUMU.cjs.map +1 -0
  7. package/dist/agent-factory-registry-ZVTABLEY.js +3 -0
  8. package/dist/agent-factory-registry-ZVTABLEY.js.map +1 -0
  9. package/dist/auth/index.cjs +63 -367
  10. package/dist/auth/index.cjs.map +1 -1
  11. package/dist/auth/index.js +6 -342
  12. package/dist/auth/index.js.map +1 -1
  13. package/dist/batch-2FSD2UNL.cjs +244 -0
  14. package/dist/batch-2FSD2UNL.cjs.map +1 -0
  15. package/dist/batch-MR2HKYMS.js +241 -0
  16. package/dist/batch-MR2HKYMS.js.map +1 -0
  17. package/dist/chunk-2HRYBRD7.cjs +31 -0
  18. package/dist/chunk-2HRYBRD7.cjs.map +1 -0
  19. package/dist/chunk-2MF3IE2D.cjs +2863 -0
  20. package/dist/chunk-2MF3IE2D.cjs.map +1 -0
  21. package/dist/chunk-2ONFGMBV.js +6 -0
  22. package/dist/chunk-2ONFGMBV.js.map +1 -0
  23. package/dist/chunk-2SFBB54R.js +23 -0
  24. package/dist/chunk-2SFBB54R.js.map +1 -0
  25. package/dist/chunk-2XLKLVVR.js +18 -0
  26. package/dist/chunk-2XLKLVVR.js.map +1 -0
  27. package/dist/chunk-4SXHEZIV.cjs +240 -0
  28. package/dist/chunk-4SXHEZIV.cjs.map +1 -0
  29. package/dist/chunk-4VPXM6UU.js +10 -0
  30. package/dist/chunk-4VPXM6UU.js.map +1 -0
  31. package/dist/chunk-4WL52CXU.cjs +148 -0
  32. package/dist/chunk-4WL52CXU.cjs.map +1 -0
  33. package/dist/chunk-5NBUH3NO.js +39 -0
  34. package/dist/chunk-5NBUH3NO.js.map +1 -0
  35. package/dist/chunk-5PZMMF4H.js +43 -0
  36. package/dist/chunk-5PZMMF4H.js.map +1 -0
  37. package/dist/chunk-6CLRANZA.js +289 -0
  38. package/dist/chunk-6CLRANZA.js.map +1 -0
  39. package/dist/chunk-6JSIEDKL.cjs +121 -0
  40. package/dist/chunk-6JSIEDKL.cjs.map +1 -0
  41. package/dist/chunk-6M4ODB2V.cjs +145 -0
  42. package/dist/chunk-6M4ODB2V.cjs.map +1 -0
  43. package/dist/chunk-6X6ID4MO.js +20 -0
  44. package/dist/chunk-6X6ID4MO.js.map +1 -0
  45. package/dist/chunk-77FOZCOT.js +165 -0
  46. package/dist/chunk-77FOZCOT.js.map +1 -0
  47. package/dist/chunk-7AD3ZTZL.js +25 -0
  48. package/dist/chunk-7AD3ZTZL.js.map +1 -0
  49. package/dist/chunk-7GFX45DD.js +57 -0
  50. package/dist/chunk-7GFX45DD.js.map +1 -0
  51. package/dist/chunk-7S7KKUO6.cjs +45 -0
  52. package/dist/chunk-7S7KKUO6.cjs.map +1 -0
  53. package/dist/chunk-7W7ZWMLQ.js +99 -0
  54. package/dist/chunk-7W7ZWMLQ.js.map +1 -0
  55. package/dist/chunk-A44COQJJ.cjs +353 -0
  56. package/dist/chunk-A44COQJJ.cjs.map +1 -0
  57. package/dist/chunk-AKSBP7OO.js +185 -0
  58. package/dist/chunk-AKSBP7OO.js.map +1 -0
  59. package/dist/chunk-ANIZEWTU.cjs +196 -0
  60. package/dist/chunk-ANIZEWTU.cjs.map +1 -0
  61. package/dist/chunk-BEURCLDV.cjs +139 -0
  62. package/dist/chunk-BEURCLDV.cjs.map +1 -0
  63. package/dist/chunk-BFWPZMG7.js +379 -0
  64. package/dist/chunk-BFWPZMG7.js.map +1 -0
  65. package/dist/chunk-BUUUWQMB.cjs +34 -0
  66. package/dist/chunk-BUUUWQMB.cjs.map +1 -0
  67. package/dist/chunk-BV2MWEMV.cjs +26 -0
  68. package/dist/chunk-BV2MWEMV.cjs.map +1 -0
  69. package/dist/chunk-BWT67BI4.cjs +268 -0
  70. package/dist/chunk-BWT67BI4.cjs.map +1 -0
  71. package/dist/chunk-BXV2QUIC.js +191 -0
  72. package/dist/chunk-BXV2QUIC.js.map +1 -0
  73. package/dist/chunk-C6Y6CWYD.cjs +44 -0
  74. package/dist/chunk-C6Y6CWYD.cjs.map +1 -0
  75. package/dist/chunk-C7PICHRF.cjs +68 -0
  76. package/dist/chunk-C7PICHRF.cjs.map +1 -0
  77. package/dist/chunk-CAH3G4IS.js +13 -0
  78. package/dist/chunk-CAH3G4IS.js.map +1 -0
  79. package/dist/chunk-D42XHI4O.cjs +565 -0
  80. package/dist/chunk-D42XHI4O.cjs.map +1 -0
  81. package/dist/chunk-DGRZNMTU.js +104 -0
  82. package/dist/chunk-DGRZNMTU.js.map +1 -0
  83. package/dist/chunk-DUK5WMKJ.js +71 -0
  84. package/dist/chunk-DUK5WMKJ.js.map +1 -0
  85. package/dist/chunk-EEZ7CFMM.js +14 -0
  86. package/dist/chunk-EEZ7CFMM.js.map +1 -0
  87. package/dist/chunk-EPYZOCOL.cjs +82 -0
  88. package/dist/chunk-EPYZOCOL.cjs.map +1 -0
  89. package/dist/chunk-EVADEGM7.cjs +168 -0
  90. package/dist/chunk-EVADEGM7.cjs.map +1 -0
  91. package/dist/chunk-FD2UT76F.js +3 -0
  92. package/dist/chunk-FD2UT76F.js.map +1 -0
  93. package/dist/chunk-FV3YEMQ7.js +179 -0
  94. package/dist/chunk-FV3YEMQ7.js.map +1 -0
  95. package/dist/chunk-G2F67XUR.cjs +184 -0
  96. package/dist/chunk-G2F67XUR.cjs.map +1 -0
  97. package/dist/chunk-G6GO6BXD.js +994 -0
  98. package/dist/chunk-G6GO6BXD.js.map +1 -0
  99. package/dist/chunk-GIW4L6HY.cjs +27 -0
  100. package/dist/chunk-GIW4L6HY.cjs.map +1 -0
  101. package/dist/chunk-GJAGKFTR.js +74 -0
  102. package/dist/chunk-GJAGKFTR.js.map +1 -0
  103. package/dist/chunk-HFPGOTVF.cjs +324 -0
  104. package/dist/chunk-HFPGOTVF.cjs.map +1 -0
  105. package/dist/chunk-HRA3CPGG.js +486 -0
  106. package/dist/chunk-HRA3CPGG.js.map +1 -0
  107. package/dist/chunk-HZQEDNF6.js +66 -0
  108. package/dist/chunk-HZQEDNF6.js.map +1 -0
  109. package/dist/chunk-IT3PWBW4.cjs +19 -0
  110. package/dist/chunk-IT3PWBW4.cjs.map +1 -0
  111. package/dist/chunk-JD74LN7R.cjs +171 -0
  112. package/dist/chunk-JD74LN7R.cjs.map +1 -0
  113. package/dist/chunk-JTFYYKDT.js +135 -0
  114. package/dist/chunk-JTFYYKDT.js.map +1 -0
  115. package/dist/chunk-K2BQQ445.js +30 -0
  116. package/dist/chunk-K2BQQ445.js.map +1 -0
  117. package/dist/chunk-KAP4GJHO.js +546 -0
  118. package/dist/chunk-KAP4GJHO.js.map +1 -0
  119. package/dist/chunk-KDNBTPY2.js +458 -0
  120. package/dist/chunk-KDNBTPY2.js.map +1 -0
  121. package/dist/chunk-KIO7QFIV.cjs +223 -0
  122. package/dist/chunk-KIO7QFIV.cjs.map +1 -0
  123. package/dist/chunk-KSKU6JY6.cjs +71 -0
  124. package/dist/chunk-KSKU6JY6.cjs.map +1 -0
  125. package/dist/chunk-LSLPF6OI.cjs +192 -0
  126. package/dist/chunk-LSLPF6OI.cjs.map +1 -0
  127. package/dist/chunk-LU7VALW5.js +312 -0
  128. package/dist/chunk-LU7VALW5.js.map +1 -0
  129. package/dist/chunk-LUSXDZPV.cjs +296 -0
  130. package/dist/chunk-LUSXDZPV.cjs.map +1 -0
  131. package/dist/chunk-M72RJVPC.js +69 -0
  132. package/dist/chunk-M72RJVPC.js.map +1 -0
  133. package/dist/chunk-MQLCZ4HJ.cjs +1010 -0
  134. package/dist/chunk-MQLCZ4HJ.cjs.map +1 -0
  135. package/dist/chunk-MUUQ2WFJ.cjs +4 -0
  136. package/dist/chunk-MUUQ2WFJ.cjs.map +1 -0
  137. package/dist/chunk-MZ5ZRORA.cjs +496 -0
  138. package/dist/chunk-MZ5ZRORA.cjs.map +1 -0
  139. package/dist/chunk-N24XBYNX.cjs +140 -0
  140. package/dist/chunk-N24XBYNX.cjs.map +1 -0
  141. package/dist/chunk-NINIJCHU.cjs +23 -0
  142. package/dist/chunk-NINIJCHU.cjs.map +1 -0
  143. package/dist/chunk-NRSH7RJY.js +2841 -0
  144. package/dist/chunk-NRSH7RJY.js.map +1 -0
  145. package/dist/chunk-OIYQBUW4.cjs +111 -0
  146. package/dist/chunk-OIYQBUW4.cjs.map +1 -0
  147. package/dist/chunk-PNVDQL5Y.cjs +15 -0
  148. package/dist/chunk-PNVDQL5Y.cjs.map +1 -0
  149. package/dist/chunk-POQT2OIF.js +214 -0
  150. package/dist/chunk-POQT2OIF.js.map +1 -0
  151. package/dist/chunk-PSJN532Q.js +10573 -0
  152. package/dist/chunk-PSJN532Q.js.map +1 -0
  153. package/dist/chunk-QUTUJ6P6.cjs +76 -0
  154. package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
  155. package/dist/chunk-R43CNCES.cjs +460 -0
  156. package/dist/chunk-R43CNCES.cjs.map +1 -0
  157. package/dist/chunk-S2BBRVQX.js +68 -0
  158. package/dist/chunk-S2BBRVQX.js.map +1 -0
  159. package/dist/chunk-S5RCBTSF.js +145 -0
  160. package/dist/chunk-S5RCBTSF.js.map +1 -0
  161. package/dist/chunk-S7OEXQMI.cjs +136 -0
  162. package/dist/chunk-S7OEXQMI.cjs.map +1 -0
  163. package/dist/chunk-SKWVAQAY.js +129 -0
  164. package/dist/chunk-SKWVAQAY.js.map +1 -0
  165. package/dist/chunk-SQLZ7ONU.js +152 -0
  166. package/dist/chunk-SQLZ7ONU.js.map +1 -0
  167. package/dist/chunk-TIZ4TS5V.cjs +72 -0
  168. package/dist/chunk-TIZ4TS5V.cjs.map +1 -0
  169. package/dist/chunk-TQKCU7CL.js +142 -0
  170. package/dist/chunk-TQKCU7CL.js.map +1 -0
  171. package/dist/chunk-U54XCYG3.js +116 -0
  172. package/dist/chunk-U54XCYG3.js.map +1 -0
  173. package/dist/chunk-U6QGZHPN.js +29 -0
  174. package/dist/chunk-U6QGZHPN.js.map +1 -0
  175. package/dist/chunk-UCFONJBG.js +79 -0
  176. package/dist/chunk-UCFONJBG.js.map +1 -0
  177. package/dist/chunk-UJ7IQJAG.js +141 -0
  178. package/dist/chunk-UJ7IQJAG.js.map +1 -0
  179. package/dist/chunk-UVNG67DG.js +253 -0
  180. package/dist/chunk-UVNG67DG.js.map +1 -0
  181. package/dist/chunk-V4XRLPEF.js +25 -0
  182. package/dist/chunk-V4XRLPEF.js.map +1 -0
  183. package/dist/chunk-VJ26EKGJ.cjs +28 -0
  184. package/dist/chunk-VJ26EKGJ.cjs.map +1 -0
  185. package/dist/chunk-VK7MAV65.cjs +90 -0
  186. package/dist/chunk-VK7MAV65.cjs.map +1 -0
  187. package/dist/chunk-VYCKUKPA.cjs +106 -0
  188. package/dist/chunk-VYCKUKPA.cjs.map +1 -0
  189. package/dist/chunk-VYHJZVL5.cjs +29 -0
  190. package/dist/chunk-VYHJZVL5.cjs.map +1 -0
  191. package/dist/chunk-WA3FO4R7.js +155 -0
  192. package/dist/chunk-WA3FO4R7.js.map +1 -0
  193. package/dist/chunk-WJVHMTKB.cjs +12 -0
  194. package/dist/chunk-WJVHMTKB.cjs.map +1 -0
  195. package/dist/chunk-WLKFWQSJ.js +333 -0
  196. package/dist/chunk-WLKFWQSJ.js.map +1 -0
  197. package/dist/chunk-WPZTYOUX.cjs +59 -0
  198. package/dist/chunk-WPZTYOUX.cjs.map +1 -0
  199. package/dist/chunk-X2FR4OIT.js +27 -0
  200. package/dist/chunk-X2FR4OIT.js.map +1 -0
  201. package/dist/chunk-XIG2IE3L.js +134 -0
  202. package/dist/chunk-XIG2IE3L.js.map +1 -0
  203. package/dist/chunk-YLQQX5W2.cjs +20 -0
  204. package/dist/chunk-YLQQX5W2.cjs.map +1 -0
  205. package/dist/chunk-YPEPCZHF.cjs +147 -0
  206. package/dist/chunk-YPEPCZHF.cjs.map +1 -0
  207. package/dist/chunk-YPQF26X7.cjs +8 -0
  208. package/dist/chunk-YPQF26X7.cjs.map +1 -0
  209. package/dist/chunk-YU6KON2I.cjs +160 -0
  210. package/dist/chunk-YU6KON2I.cjs.map +1 -0
  211. package/dist/chunk-Z2OC3UIW.cjs +388 -0
  212. package/dist/chunk-Z2OC3UIW.cjs.map +1 -0
  213. package/dist/chunk-ZUBIEQJF.cjs +10590 -0
  214. package/dist/chunk-ZUBIEQJF.cjs.map +1 -0
  215. package/dist/chunk-ZZWTY3RX.js +230 -0
  216. package/dist/chunk-ZZWTY3RX.js.map +1 -0
  217. package/dist/compact-session-OO2GD76G.js +17 -0
  218. package/dist/compact-session-OO2GD76G.js.map +1 -0
  219. package/dist/compact-session-OO7NVWPB.cjs +54 -0
  220. package/dist/compact-session-OO7NVWPB.cjs.map +1 -0
  221. package/dist/compaction.cjs +54 -303
  222. package/dist/compaction.cjs.map +1 -1
  223. package/dist/compaction.js +3 -292
  224. package/dist/compaction.js.map +1 -1
  225. package/dist/concurrency.cjs +9 -81
  226. package/dist/concurrency.cjs.map +1 -1
  227. package/dist/concurrency.js +5 -80
  228. package/dist/concurrency.js.map +1 -1
  229. package/dist/context-GWANQLX4.js +5 -0
  230. package/dist/context-GWANQLX4.js.map +1 -0
  231. package/dist/context-KNWVTZSY.cjs +22 -0
  232. package/dist/context-KNWVTZSY.cjs.map +1 -0
  233. package/dist/{cron-x3muPNgg.d.cts → cron-D0JKR-yX.d.cts} +2 -1
  234. package/dist/{cron-B_NkE_VM.d.ts → cron-DivRaEmN.d.ts} +2 -1
  235. package/dist/cron.cjs +44 -20676
  236. package/dist/cron.cjs.map +1 -1
  237. package/dist/cron.d.cts +1 -1
  238. package/dist/cron.d.ts +1 -1
  239. package/dist/cron.js +38 -20676
  240. package/dist/cron.js.map +1 -1
  241. package/dist/errors.cjs +78 -470
  242. package/dist/errors.cjs.map +1 -1
  243. package/dist/errors.d.ts +3 -424
  244. package/dist/errors.js +2 -455
  245. package/dist/errors.js.map +1 -1
  246. package/dist/eval.cjs +72 -20411
  247. package/dist/eval.cjs.map +1 -1
  248. package/dist/eval.js +59 -20402
  249. package/dist/eval.js.map +1 -1
  250. package/dist/executor-ORJS5GV2.js +981 -0
  251. package/dist/executor-ORJS5GV2.js.map +1 -0
  252. package/dist/executor-Y4MKPIUD.cjs +985 -0
  253. package/dist/executor-Y4MKPIUD.cjs.map +1 -0
  254. package/dist/filesystem/index.cjs +7 -112
  255. package/dist/filesystem/index.cjs.map +1 -1
  256. package/dist/filesystem/index.js +4 -109
  257. package/dist/filesystem/index.js.map +1 -1
  258. package/dist/fork-agent-RSV4E3EA.js +61 -0
  259. package/dist/fork-agent-RSV4E3EA.js.map +1 -0
  260. package/dist/fork-agent-Y2IK2RYU.cjs +64 -0
  261. package/dist/fork-agent-Y2IK2RYU.cjs.map +1 -0
  262. package/dist/fs-session-store-KAUQYSGI.cjs +17 -0
  263. package/dist/fs-session-store-KAUQYSGI.cjs.map +1 -0
  264. package/dist/fs-session-store-ZKB5NN37.js +8 -0
  265. package/dist/fs-session-store-ZKB5NN37.js.map +1 -0
  266. package/dist/generate-object-H3RNAM6S.cjs +20 -0
  267. package/dist/generate-object-H3RNAM6S.cjs.map +1 -0
  268. package/dist/generate-object-YJPDV5BS.js +7 -0
  269. package/dist/generate-object-YJPDV5BS.js.map +1 -0
  270. package/dist/index-manager-CB6I7XFQ.cjs +19 -0
  271. package/dist/index-manager-CB6I7XFQ.cjs.map +1 -0
  272. package/dist/index-manager-L27Q3QAC.js +10 -0
  273. package/dist/index-manager-L27Q3QAC.js.map +1 -0
  274. package/dist/index.cjs +371 -22888
  275. package/dist/index.cjs.map +1 -1
  276. package/dist/index.d.cts +16 -21
  277. package/dist/index.d.ts +16 -21
  278. package/dist/index.js +92 -22713
  279. package/dist/index.js.map +1 -1
  280. package/dist/inject-session-6MJUSGZP.cjs +27 -0
  281. package/dist/inject-session-6MJUSGZP.cjs.map +1 -0
  282. package/dist/inject-session-KOFHS5K3.js +25 -0
  283. package/dist/inject-session-KOFHS5K3.js.map +1 -0
  284. package/dist/internal/judge/judge-call.d.ts +32 -19
  285. package/dist/internal/persistence/index.cjs +93 -508
  286. package/dist/internal/persistence/index.cjs.map +1 -1
  287. package/dist/internal/persistence/index.js +11 -489
  288. package/dist/internal/persistence/index.js.map +1 -1
  289. package/dist/internal/security/index.cjs +44 -361
  290. package/dist/internal/security/index.cjs.map +1 -1
  291. package/dist/internal/security/index.js +4 -355
  292. package/dist/internal/security/index.js.map +1 -1
  293. package/dist/judge-call-CEQ3FYYD.js +126 -0
  294. package/dist/judge-call-CEQ3FYYD.js.map +1 -0
  295. package/dist/judge-call-QG4WZ7F3.cjs +130 -0
  296. package/dist/judge-call-QG4WZ7F3.cjs.map +1 -0
  297. package/dist/models.cjs +24 -919
  298. package/dist/models.cjs.map +1 -1
  299. package/dist/models.js +11 -907
  300. package/dist/models.js.map +1 -1
  301. package/dist/oauth-transaction-store-7CKHPQRN.cjs +32 -0
  302. package/dist/oauth-transaction-store-7CKHPQRN.cjs.map +1 -0
  303. package/dist/oauth-transaction-store-W74I6EFD.js +3 -0
  304. package/dist/oauth-transaction-store-W74I6EFD.js.map +1 -0
  305. package/dist/path-safety.cjs +31 -200
  306. package/dist/path-safety.cjs.map +1 -1
  307. package/dist/path-safety.js +3 -197
  308. package/dist/path-safety.js.map +1 -1
  309. package/dist/persistence.cjs +73 -393
  310. package/dist/persistence.cjs.map +1 -1
  311. package/dist/persistence.js +9 -381
  312. package/dist/persistence.js.map +1 -1
  313. package/dist/project.cjs +8 -112
  314. package/dist/project.cjs.map +1 -1
  315. package/dist/project.js +6 -110
  316. package/dist/project.js.map +1 -1
  317. package/dist/registry-34IWWDQQ.js +9 -0
  318. package/dist/registry-34IWWDQQ.js.map +1 -0
  319. package/dist/registry-APYDISL6.cjs +46 -0
  320. package/dist/registry-APYDISL6.cjs.map +1 -0
  321. package/dist/retry.cjs +7 -87
  322. package/dist/retry.cjs.map +1 -1
  323. package/dist/retry.js +3 -90
  324. package/dist/retry.js.map +1 -1
  325. package/dist/run-to-completion-J73I6IY4.cjs +48 -0
  326. package/dist/run-to-completion-J73I6IY4.cjs.map +1 -0
  327. package/dist/run-to-completion-JDPIUKSH.js +3 -0
  328. package/dist/run-to-completion-JDPIUKSH.js.map +1 -0
  329. package/dist/run-until-PNO3QQLI.cjs +180 -0
  330. package/dist/run-until-PNO3QQLI.cjs.map +1 -0
  331. package/dist/run-until-XLHEHRQM.js +177 -0
  332. package/dist/run-until-XLHEHRQM.js.map +1 -0
  333. package/dist/sandbox/index.cjs +35 -337
  334. package/dist/sandbox/index.cjs.map +1 -1
  335. package/dist/sandbox/index.js +7 -323
  336. package/dist/sandbox/index.js.map +1 -1
  337. package/dist/sanitize/index.cjs +5 -112
  338. package/dist/sanitize/index.cjs.map +1 -1
  339. package/dist/sanitize/index.js +1 -114
  340. package/dist/sanitize/index.js.map +1 -1
  341. package/dist/server/auth/index.cjs +35 -175
  342. package/dist/server/auth/index.cjs.map +1 -1
  343. package/dist/server/auth/index.js +7 -161
  344. package/dist/server/auth/index.js.map +1 -1
  345. package/dist/server/errors-envelope.cjs +17 -328
  346. package/dist/server/errors-envelope.cjs.map +1 -1
  347. package/dist/server/errors-envelope.js +4 -317
  348. package/dist/server/errors-envelope.js.map +1 -1
  349. package/dist/session-transcript-LPNZR3YS.cjs +46 -0
  350. package/dist/session-transcript-LPNZR3YS.cjs.map +1 -0
  351. package/dist/session-transcript-T7LGJUGW.js +5 -0
  352. package/dist/session-transcript-T7LGJUGW.js.map +1 -0
  353. package/dist/skills.cjs +12 -280
  354. package/dist/skills.cjs.map +1 -1
  355. package/dist/skills.js +4 -282
  356. package/dist/skills.js.map +1 -1
  357. package/dist/stream-object-QEQJJDTI.cjs +20 -0
  358. package/dist/stream-object-QEQJJDTI.cjs.map +1 -0
  359. package/dist/stream-object-WUQSSRY2.js +7 -0
  360. package/dist/stream-object-WUQSSRY2.js.map +1 -0
  361. package/dist/stream-to-completion-DFJ5T3BK.js +30 -0
  362. package/dist/stream-to-completion-DFJ5T3BK.js.map +1 -0
  363. package/dist/stream-to-completion-H2MHISSK.cjs +32 -0
  364. package/dist/stream-to-completion-H2MHISSK.cjs.map +1 -0
  365. package/dist/subagents.cjs +2 -8
  366. package/dist/subagents.cjs.map +1 -1
  367. package/dist/subagents.js +1 -7
  368. package/dist/subagents.js.map +1 -1
  369. package/dist/subscription/index.cjs +4 -17
  370. package/dist/subscription/index.cjs.map +1 -1
  371. package/dist/subscription/index.js +3 -16
  372. package/dist/subscription/index.js.map +1 -1
  373. package/dist/task-store.cjs +16 -258
  374. package/dist/task-store.cjs.map +1 -1
  375. package/dist/task-store.js +4 -259
  376. package/dist/task-store.js.map +1 -1
  377. package/dist/types/goal-events.d.ts +2 -1
  378. package/dist/workflow.cjs +71 -2797
  379. package/dist/workflow.cjs.map +1 -1
  380. package/dist/workflow.js +8 -2812
  381. package/dist/workflow.js.map +1 -1
  382. package/package.json +1 -1
@@ -0,0 +1,152 @@
1
+ import { sessions, transcriptKey, hydratedKeys } from './chunk-EEZ7CFMM.js';
2
+ import { reconstructMessages, SessionTranscript } from './chunk-ZZWTY3RX.js';
3
+
4
+ // src/internal/session/agent-session-store.ts
5
+ function seedTranscript(prior, opts) {
6
+ return SessionTranscript.fromRecords(prior, opts);
7
+ }
8
+ function mapAgentTurn(steps) {
9
+ const assistant = {};
10
+ const toolResults = [];
11
+ const toolCalls = [];
12
+ for (const step of steps) {
13
+ if (step.type === "thinkingMessage") assistant.thinking = step.message.text;
14
+ else if (step.type === "assistantMessage") assistant.text = step.message.text;
15
+ else if (step.type === "toolCall")
16
+ toolCalls.push({
17
+ id: step.message.callId,
18
+ name: step.message.name,
19
+ input: step.message.args ?? {}
20
+ });
21
+ else
22
+ toolResults.push({
23
+ toolUseId: step.message.callId,
24
+ content: step.message.result,
25
+ isError: step.message.isError
26
+ });
27
+ }
28
+ if (toolCalls.length > 0) assistant.toolCalls = toolCalls;
29
+ return { assistant, toolResults };
30
+ }
31
+ function hasAssistantContent(a) {
32
+ return a.text !== void 0 || a.thinking !== void 0 || (a.toolCalls?.length ?? 0) > 0;
33
+ }
34
+ function appendConversation(transcript, conversation) {
35
+ for (const ct of conversation) {
36
+ if (ct.type !== "agentConversationTurn") continue;
37
+ const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);
38
+ if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);
39
+ if (toolResults.length > 0) transcript.appendToolResults(toolResults);
40
+ }
41
+ }
42
+ async function readSessionMessages(store, agentId) {
43
+ const records = await store.readRecords(agentId);
44
+ return reconstructMessages(records).map(narrowToSessionMessage);
45
+ }
46
+ function partToText(p) {
47
+ if (p.type === "text") return p.text ?? "";
48
+ if (p.type === "tool_use") return `[tool call] ${p.name ?? ""}`;
49
+ if (p.type === "tool_result") {
50
+ const body = typeof p.content === "string" ? p.content : JSON.stringify(p.content);
51
+ return `[tool result] ${body}`;
52
+ }
53
+ return "";
54
+ }
55
+ function narrowToSessionMessage(m) {
56
+ const role = m.role === "user" ? "user" : "assistant";
57
+ const text = m.content.map(partToText).filter((s) => s.length > 0).join("\n");
58
+ return { role, text };
59
+ }
60
+ function deltaRecords(transcript, priorLength) {
61
+ return transcript.records().slice(priorLength);
62
+ }
63
+ async function persistTurn(store, loc, sessionId, turn) {
64
+ const prior = await store.readRecords(loc.agentId);
65
+ const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });
66
+ transcript.appendUserTurn(turn.userText);
67
+ appendConversation(transcript, turn.conversation);
68
+ await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));
69
+ }
70
+
71
+ // src/internal/session/agent-session.ts
72
+ var pendingWrites = /* @__PURE__ */ new Map();
73
+ var recordCounts = /* @__PURE__ */ new Map();
74
+ function appendSessionMessage(agentId, message) {
75
+ const existing = sessions.get(agentId) ?? [];
76
+ existing.push(message);
77
+ sessions.set(agentId, existing);
78
+ }
79
+ function getSessionMessages(agentId) {
80
+ return sessions.get(agentId) ?? [];
81
+ }
82
+ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
83
+ const key = transcriptKey(loc.cwd, loc.agentId);
84
+ const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {
85
+ try {
86
+ await persistTurn(store, loc, sessionId, turn);
87
+ const count = (recordCounts.get(key) ?? 0) + 1;
88
+ recordCounts.set(key, count);
89
+ if (turn.autoCompact !== void 0) {
90
+ const { autoCompactIfNeeded } = await import('./compact-session-OO2GD76G.js');
91
+ const fired = await autoCompactIfNeeded({
92
+ store,
93
+ loc,
94
+ sessionId,
95
+ usageTotal: turn.autoCompact.usageTotal,
96
+ contextWindow: turn.autoCompact.contextWindow,
97
+ turnCount: count,
98
+ summarize: turn.autoCompact.summarize
99
+ });
100
+ if (fired) onCompact?.();
101
+ }
102
+ } catch (cause) {
103
+ const msg = cause instanceof Error ? cause.message : String(cause);
104
+ process.stderr.write(
105
+ `[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}
106
+ `
107
+ );
108
+ }
109
+ });
110
+ pendingWrites.set(
111
+ key,
112
+ chained.then(
113
+ () => void 0,
114
+ () => void 0
115
+ )
116
+ );
117
+ }
118
+ async function hydrateSession(agentId, loc) {
119
+ const key = transcriptKey(loc.cwd, agentId);
120
+ if (hydratedKeys.has(key)) return;
121
+ hydratedKeys.add(key);
122
+ const persisted = await readSessionMessages(loc.store, agentId);
123
+ if (persisted.length === 0) return;
124
+ sessions.set(agentId, persisted);
125
+ }
126
+ async function flushSessionWrites() {
127
+ while (pendingWrites.size > 0) {
128
+ const all = Array.from(pendingWrites.values());
129
+ pendingWrites.clear();
130
+ await Promise.all(all);
131
+ }
132
+ }
133
+ function clearSession(agentId) {
134
+ sessions.delete(agentId);
135
+ }
136
+ function enqueueSessionWrite(cwd, agentId, fn) {
137
+ const key = transcriptKey(cwd, agentId);
138
+ const prior = pendingWrites.get(key) ?? Promise.resolve();
139
+ const result = prior.then(fn);
140
+ pendingWrites.set(
141
+ key,
142
+ result.then(
143
+ () => void 0,
144
+ () => void 0
145
+ )
146
+ );
147
+ return result;
148
+ }
149
+
150
+ export { appendSessionMessage, clearSession, enqueueSessionWrite, flushSessionWrites, getSessionMessages, hydrateSession, persistTurnToTranscript };
151
+ //# sourceMappingURL=chunk-SQLZ7ONU.js.map
152
+ //# sourceMappingURL=chunk-SQLZ7ONU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/session/agent-session-store.ts","../src/internal/session/agent-session.ts"],"names":[],"mappings":";;;;AA8BA,SAAS,cAAA,CACP,OACA,IAAA,EACmB;AACnB,EAAA,OAAO,iBAAA,CAAkB,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA;AAClD;AAyBA,SAAS,aAAa,KAAA,EAAgD;AACpE,EAAA,MAAM,YAA2B,EAAC;AAClC,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,YAAqD,EAAC;AAC5D,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,KAAK,IAAA,KAAS,iBAAA,EAAmB,SAAA,CAAU,QAAA,GAAW,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAC9D,KAAK,IAAA,KAAS,kBAAA,EAAoB,SAAA,CAAU,IAAA,GAAO,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAChE,KAAK,IAAA,KAAS,UAAA;AACrB,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,EAAA,EAAI,KAAK,OAAA,CAAQ,MAAA;AAAA,QACjB,IAAA,EAAM,KAAK,OAAA,CAAQ,IAAA;AAAA,QACnB,KAAA,EAAQ,IAAA,CAAK,OAAA,CAAQ,IAAA,IAAgD;AAAC,OACvE,CAAA;AAAA;AAED,MAAA,WAAA,CAAY,IAAA,CAAK;AAAA,QACf,SAAA,EAAW,KAAK,OAAA,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,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAEO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-SQLZ7ONU.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") assistant.thinking = step.message.text;\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = { type: string; text?: string; content?: unknown; name?: string };\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n return { role, text };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n","import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — o cache mora numa folha; ver session-cache.ts para a razao (quebra de ciclo por extracao).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n sessions.set(agentId, existing);\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n // de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n // pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n // arriscado. Rastreado em usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`,\n );\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
@@ -0,0 +1,72 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var promises = require('fs/promises');
5
+ var path = require('path');
6
+
7
+ // src/internal/persistence/atomic-write.ts
8
+ var NETWORK_FS_MAGIC = /* @__PURE__ */ new Map([
9
+ [26985, "nfs"],
10
+ [20859, "smb"],
11
+ [4283649346, "cifs"],
12
+ [1702057286, "fuse"]
13
+ ]);
14
+ function detectNetworkFsName(typeMagic) {
15
+ return NETWORK_FS_MAGIC.get(typeMagic) ?? null;
16
+ }
17
+ var warnedNfsDirs = /* @__PURE__ */ new Set();
18
+ async function warnOnNetworkFsOnce(dirPath, label) {
19
+ const key = `${dirPath}\0${label}`;
20
+ if (warnedNfsDirs.has(key)) return;
21
+ warnedNfsDirs.add(key);
22
+ try {
23
+ const info = await promises.statfs(dirPath);
24
+ const fsName = detectNetworkFsName(info.type);
25
+ if (fsName === null) return;
26
+ process.stderr.write(
27
+ `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} \u2014 rename() atomicity guarantees may be weaker than expected.
28
+ `
29
+ );
30
+ } catch {
31
+ }
32
+ }
33
+ async function replaceFileAtomic(filePath, content) {
34
+ await warnOnNetworkFsOnce(path.dirname(filePath), "atomic-write");
35
+ const suffix = crypto.randomBytes(8).toString("hex");
36
+ const tmp = `${filePath}.${process.pid}.${suffix}.tmp`;
37
+ const handle = await promises.open(tmp, "w", 384);
38
+ try {
39
+ await handle.writeFile(content, "utf8");
40
+ await handle.sync();
41
+ } finally {
42
+ await handle.close();
43
+ }
44
+ try {
45
+ await promises.rename(tmp, filePath);
46
+ } catch (cause) {
47
+ await promises.unlink(tmp).catch(() => void 0);
48
+ throw cause;
49
+ }
50
+ }
51
+ async function atomicWriteJson(filePath, data, options) {
52
+ const indent = options?.indent ?? 2;
53
+ const trailingNewline = options?.trailingNewline ?? true;
54
+ const json = JSON.stringify(data, null, indent);
55
+ if (json === void 0) {
56
+ throw new TypeError("atomicWriteJson: cannot serialize undefined");
57
+ }
58
+ const content = trailingNewline ? `${json}
59
+ ` : json;
60
+ await promises.mkdir(path.dirname(filePath), { recursive: true });
61
+ await replaceFileAtomic(filePath, content);
62
+ }
63
+ async function atomicWriteText(filePath, content) {
64
+ await promises.mkdir(path.dirname(filePath), { recursive: true });
65
+ await replaceFileAtomic(filePath, content);
66
+ }
67
+
68
+ exports.atomicWriteJson = atomicWriteJson;
69
+ exports.atomicWriteText = atomicWriteText;
70
+ exports.replaceFileAtomic = replaceFileAtomic;
71
+ //# sourceMappingURL=chunk-TIZ4TS5V.cjs.map
72
+ //# sourceMappingURL=chunk-TIZ4TS5V.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":["statfs","dirname","randomBytes","open","rename","unlink","mkdir"],"mappings":";;;;;;;AASA,IAAM,gBAAA,uBAAoD,GAAA,CAAI;AAAA,EAC5D,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,YAAY,MAAM,CAAA;AAAA,EACnB,CAAC,YAAY,MAAM;AACrB,CAAC,CAAA;AAUD,SAAS,oBAAoB,SAAA,EAAkC;AAC7D,EAAA,OAAO,gBAAA,CAAiB,GAAA,CAAI,SAAS,CAAA,IAAK,IAAA;AAC5C;AAEA,IAAM,aAAA,uBAAoB,GAAA,EAAY;AAWtC,eAAe,mBAAA,CAAoB,SAAiB,KAAA,EAA8B;AAChF,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,OAAO,CAAA,EAAA,EAAK,KAAK,CAAA,CAAA;AAChC,EAAA,IAAI,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,EAAG;AAC5B,EAAA,aAAA,CAAc,IAAI,GAAG,CAAA;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,MAAMA,eAAA,CAAO,OAAO,CAAA;AACjC,IAAA,MAAM,MAAA,GAAS,mBAAA,CAAoB,IAAA,CAAK,IAAI,CAAA;AAC5C,IAAA,IAAI,WAAW,IAAA,EAAM;AACrB,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,MACb,CAAA,cAAA,EAAiB,KAAK,CAAA,uBAAA,EAA0B,MAAM,QAAQ,OAAO,CAAA;AAAA;AAAA,KAEvE;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAGR;AACF;AAuCA,eAAsB,iBAAA,CAAkB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AAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C;AAUA,eAAsB,eAAA,CAAgB,UAAkB,OAAA,EAAgC;AACtF,EAAA,MAAMK,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-TIZ4TS5V.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n process.stderr.write(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `referencia/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * @internal\n */\nexport async function replaceFileAtomic(filePath: string, content: string): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = `${filePath}.${process.pid}.${suffix}.tmp`;\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, \"w\", 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n * @internal\n */\nexport interface AtomicWriteJsonOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n * @internal\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n * @internal\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
@@ -0,0 +1,142 @@
1
+ import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-GJAGKFTR.js';
2
+
3
+ // src/generate-object.ts
4
+ var GenerateObjectError = class extends Error {
5
+ name = "GenerateObjectError";
6
+ code;
7
+ cause;
8
+ constructor(code, message, cause) {
9
+ super(message);
10
+ this.code = code;
11
+ if (cause !== void 0) this.cause = cause;
12
+ }
13
+ };
14
+ function salvagePartial(schema, raw) {
15
+ if (typeof raw !== "object" || raw === null) return raw;
16
+ const shape = schema.shape;
17
+ if (shape === void 0 || typeof shape !== "object") return raw;
18
+ const rawObj = raw;
19
+ const out = {};
20
+ for (const [key, fieldSchema] of Object.entries(shape)) {
21
+ if (typeof fieldSchema?.safeParse !== "function") continue;
22
+ const parsed = fieldSchema.safeParse(rawObj[key]);
23
+ if (parsed.success) out[key] = parsed.data;
24
+ }
25
+ return out;
26
+ }
27
+ async function runReasoningPhase(options, deps) {
28
+ const reasoningOptions = {
29
+ model: options.model,
30
+ local: options.local,
31
+ ...options.systemPrompt !== void 0 ? { systemPrompt: options.systemPrompt } : {},
32
+ ...options.apiKey !== void 0 ? { apiKey: options.apiKey } : {},
33
+ ...options.providers !== void 0 ? { providers: options.providers } : {}
34
+ };
35
+ const reasoningAgent = await deps.create(reasoningOptions);
36
+ try {
37
+ const run = await reasoningAgent.send(options.prompt);
38
+ const result = await run.wait();
39
+ const text = result.result;
40
+ return typeof text === "string" ? text : options.prompt;
41
+ } finally {
42
+ await disposeAndDeleteTransient(reasoningAgent, deps.delete);
43
+ }
44
+ }
45
+ async function generateObjectImpl(options, deps) {
46
+ const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(
47
+ options.schema,
48
+ options.maxRetries
49
+ );
50
+ let capturedRaw;
51
+ let lastUsage = initialUsage;
52
+ const sentinel = /* @__PURE__ */ Symbol("generate-object-sentinel");
53
+ class CaptureSentinel extends Error {
54
+ constructor(captured) {
55
+ super("generate-object-capture");
56
+ this.captured = captured;
57
+ }
58
+ captured;
59
+ [sentinel] = true;
60
+ }
61
+ const outputTool = makeOutputTool(jsonSchema, (input) => {
62
+ if (capturedRaw === void 0) {
63
+ capturedRaw = input;
64
+ }
65
+ throw new CaptureSentinel(input);
66
+ });
67
+ const reasoningText = options.structuringModel !== void 0 ? await runReasoningPhase(options, deps) : void 0;
68
+ const structuringModel = options.structuringModel ?? options.model;
69
+ const structuringPrompt = reasoningText ?? options.prompt;
70
+ const agentOptions = buildTransientAgentOptions({
71
+ model: structuringModel,
72
+ local: options.local,
73
+ outputTool,
74
+ ...options.systemPrompt !== void 0 ? { systemPrompt: options.systemPrompt } : {},
75
+ ...options.apiKey !== void 0 ? { apiKey: options.apiKey } : {},
76
+ ...options.providers !== void 0 ? { providers: options.providers } : {}
77
+ });
78
+ const agent = await deps.create(agentOptions);
79
+ try {
80
+ const userMessage = buildToolPrompt(structuringPrompt);
81
+ let lastParseError;
82
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
83
+ capturedRaw = void 0;
84
+ const run = await agent.send(userMessage);
85
+ const result = await run.wait();
86
+ lastUsage = extractUsage(result);
87
+ if (capturedRaw === void 0) {
88
+ if (result.status === "error" && result.error !== void 0) {
89
+ throw new GenerateObjectError(
90
+ "no_tool_call",
91
+ `Agent run failed before the model could reply: ${result.error.message ?? "unknown error"} [${result.error.code ?? "?"}]`,
92
+ result.error
93
+ );
94
+ }
95
+ if (attempt === maxRetries) {
96
+ throw new GenerateObjectError(
97
+ "no_tool_call",
98
+ "The model returned text instead of calling the `output` tool."
99
+ );
100
+ }
101
+ continue;
102
+ }
103
+ const parsed = options.schema.safeParse(capturedRaw);
104
+ if (parsed.success) {
105
+ return {
106
+ object: parsed.data,
107
+ raw: capturedRaw,
108
+ usage: lastUsage,
109
+ finishReason: "tool_use"
110
+ };
111
+ }
112
+ lastParseError = parsed.error;
113
+ }
114
+ if (options.errorStrategy === "return-raw") {
115
+ return {
116
+ object: capturedRaw,
117
+ raw: capturedRaw,
118
+ usage: lastUsage,
119
+ finishReason: "tool_use"
120
+ };
121
+ }
122
+ if (options.errorStrategy === "return-partial") {
123
+ return {
124
+ object: salvagePartial(options.schema, capturedRaw),
125
+ raw: capturedRaw,
126
+ usage: lastUsage,
127
+ finishReason: "tool_use"
128
+ };
129
+ }
130
+ throw new GenerateObjectError(
131
+ "parse_failed",
132
+ "Schema parse failed after all retries.",
133
+ lastParseError
134
+ );
135
+ } finally {
136
+ await disposeAndDeleteTransient(agent, deps.delete);
137
+ }
138
+ }
139
+
140
+ export { GenerateObjectError, generateObjectImpl };
141
+ //# sourceMappingURL=chunk-TQKCU7CL.js.map
142
+ //# sourceMappingURL=chunk-TQKCU7CL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generate-object.ts"],"names":[],"mappings":";;;AAyFO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC3B,IAAA,GAAO,qBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAA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EAAY;AAC1B,UAAA,MAAM,IAAI,mBAAA;AAAA,YACR,cAAA;AAAA,YACA;AAAA,WACF;AAAA,QACF;AACA,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,SAAA,CAAU,WAAW,CAAA;AACnD,MAAA,IAAI,OAAO,OAAA,EAAS;AAClB,QAAA,OAAO;AAAA,UACL,QAAQ,MAAA,CAAO,IAAA;AAAA,UACf,GAAA,EAAK,WAAA;AAAA,UACL,KAAA,EAAO,SAAA;AAAA,UACP,YAAA,EAAc;AAAA,SAChB;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,MAAA,CAAO,KAAA;AAAA,IAC1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACA,wCAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAM,yBAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-TQKCU7CL.js","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n /**\n * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends Error {\n override readonly name = \"GenerateObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n *\n * @internal\n */\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
@@ -0,0 +1,116 @@
1
+ import { createRequire } from 'module';
2
+
3
+ // src/sanitize/coerce.ts
4
+ var cachedJsonrepair;
5
+ function loadJsonrepair() {
6
+ if (cachedJsonrepair === void 0) {
7
+ const req = createRequire(import.meta.url);
8
+ cachedJsonrepair = req("jsonrepair").jsonrepair;
9
+ }
10
+ return cachedJsonrepair;
11
+ }
12
+ function isPlainObject(v) {
13
+ return v !== null && typeof v === "object" && !Array.isArray(v);
14
+ }
15
+ function toFiniteNumber(raw) {
16
+ if (raw === "") return void 0;
17
+ const n = Number(raw);
18
+ return Number.isFinite(n) && String(n) === raw ? n : void 0;
19
+ }
20
+ function tryJson(raw, repair) {
21
+ const t = raw.trimStart();
22
+ if (!(t.startsWith("{") || t.startsWith("["))) return void 0;
23
+ try {
24
+ return JSON.parse(repair ? loadJsonrepair()(t) : t);
25
+ } catch {
26
+ return void 0;
27
+ }
28
+ }
29
+ function heuristicCoerce(raw, repairJson) {
30
+ if (raw === "true") return true;
31
+ if (raw === "false") return false;
32
+ if (raw === "null") return null;
33
+ const n = toFiniteNumber(raw);
34
+ if (n !== void 0) return n;
35
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
36
+ return json === void 0 ? raw : json;
37
+ }
38
+ function coerceCandidates(raw, repairJson) {
39
+ const out = [];
40
+ if (raw === "true") out.push(true);
41
+ else if (raw === "false") out.push(false);
42
+ else if (raw === "null") out.push(null);
43
+ const n = toFiniteNumber(raw);
44
+ if (n !== void 0) out.push(n);
45
+ const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : void 0);
46
+ if (json !== void 0) out.push(json);
47
+ out.push(raw);
48
+ return out;
49
+ }
50
+ function objectShape(schema) {
51
+ const shape = schema?.shape;
52
+ return shape !== null && typeof shape === "object" ? shape : void 0;
53
+ }
54
+
55
+ // src/sanitize/sanitize-tool-input.ts
56
+ function applyTrim(key, value, ctx) {
57
+ const trimmed = value.trim();
58
+ if (trimmed !== value) ctx.notes.push(`trimmed "${key}"`);
59
+ return trimmed;
60
+ }
61
+ function applyCoerce(key, raw, ctx) {
62
+ const field = ctx.shape?.[key];
63
+ let coerced = raw;
64
+ if (field) {
65
+ for (const candidate of coerceCandidates(raw, ctx.repairJson)) {
66
+ if (field.safeParse(candidate).success) {
67
+ coerced = candidate;
68
+ break;
69
+ }
70
+ }
71
+ } else {
72
+ coerced = heuristicCoerce(raw, ctx.repairJson);
73
+ }
74
+ if (coerced !== raw) ctx.notes.push(`coerced "${key}"`);
75
+ return coerced;
76
+ }
77
+ function applyRepair(key, value, ctx) {
78
+ const repaired = tryJson(value, true);
79
+ if (repaired === void 0) return value;
80
+ ctx.notes.push(`repaired json "${key}"`);
81
+ return repaired;
82
+ }
83
+ function sanitizeString(key, value, ctx) {
84
+ let out = ctx.trim ? applyTrim(key, value, ctx) : value;
85
+ if (ctx.coerce && typeof out === "string") out = applyCoerce(key, out, ctx);
86
+ if (ctx.repairJson && !ctx.coerce && typeof out === "string") out = applyRepair(key, out, ctx);
87
+ return out;
88
+ }
89
+ function walk(input, ctx, depth) {
90
+ const out = {};
91
+ for (const [key, value] of Object.entries(input)) {
92
+ if (typeof value === "string") out[key] = sanitizeString(key, value, ctx);
93
+ else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))
94
+ out[key] = walk(value, ctx, depth + 1);
95
+ else out[key] = value;
96
+ }
97
+ return out;
98
+ }
99
+ function sanitizeToolInput(input, options) {
100
+ if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };
101
+ const ctx = {
102
+ trim: options?.trim ?? true,
103
+ coerce: options?.coerce ?? false,
104
+ repairJson: options?.repairJson ?? false,
105
+ deep: options?.deep ?? false,
106
+ maxDepth: options?.maxDepth ?? 8,
107
+ shape: objectShape(options?.schema),
108
+ notes: []
109
+ };
110
+ const value = walk(input, ctx, 0);
111
+ return { value, changed: ctx.notes.length > 0, notes: ctx.notes };
112
+ }
113
+
114
+ export { isPlainObject, sanitizeToolInput, tryJson };
115
+ //# sourceMappingURL=chunk-U54XCYG3.js.map
116
+ //# sourceMappingURL=chunk-U54XCYG3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sanitize/coerce.ts","../src/sanitize/sanitize-tool-input.ts"],"names":[],"mappings":";;;AAQA,IAAI,gBAAA;AACJ,SAAS,cAAA,GAA2C;AAClD,EAAA,IAAI,qBAAqB,MAAA,EAAW;AAClC,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,gBAAA,GAAoB,GAAA,CAAI,YAAY,CAAA,CAA4C,UAAA;AAAA,EAClF;AACA,EAAA,OAAO,gBAAA;AACT;AAGO,SAAS,cAAc,CAAA,EAA0C;AACtE,EAAA,OAAO,CAAA,KAAM,QAAQ,OAAO,CAAA,KAAM,YAAY,CAAC,KAAA,CAAM,Q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AO,GAAA,EAAK,CAAC,CAAA;AAChC,EAAA,OAAO,EAAE,OAAO,OAAA,EAAS,GAAA,CAAI,MAAM,MAAA,GAAS,CAAA,EAAG,KAAA,EAAO,GAAA,CAAI,KAAA,EAAM;AAClE","file":"chunk-U54XCYG3.js","sourcesContent":["import { createRequire } from \"node:module\";\n\nimport type { ZodType } from \"zod\";\n\n// `jsonrepair` is loaded lazily — consumers who never set `repairJson: true` never pay its\n// module-parse cost. Unlike `zod` (an optional peer dep), `jsonrepair` is a direct dependency and\n// is always installed; the lazy load is a startup-cost optimization, not an optional-install story.\n// Cached after the first repair.\nlet cachedJsonrepair: ((text: string) => string) | undefined;\nfunction loadJsonrepair(): (text: string) => string {\n if (cachedJsonrepair === undefined) {\n const req = createRequire(import.meta.url);\n cachedJsonrepair = (req(\"jsonrepair\") as { jsonrepair: (t: string) => string }).jsonrepair;\n }\n return cachedJsonrepair;\n}\n\n/** @internal */\nexport function isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/** Number coercion with a round-trip + finite guard: rejects big-ints, leading-zeros, `NaN`,\n * `Infinity`, and non-canonical forms (`\"1e3\"`), preventing silent ID/precision corruption (EC-2). */\nfunction toFiniteNumber(raw: string): number | undefined {\n if (raw === \"\") return undefined;\n const n = Number(raw);\n return Number.isFinite(n) && String(n) === raw ? n : undefined;\n}\n\n/** Parse a value ONLY when it looks like a JSON object/array (EC-3 guard; leading whitespace\n * ignored so `trim:false` inputs are still gated correctly). `repair` routes it through\n * `jsonrepair` first. Returns `undefined` when not JSON-looking or on parse failure.\n * @internal */\nexport function tryJson(raw: string, repair: boolean): unknown {\n const t = raw.trimStart();\n if (!(t.startsWith(\"{\") || t.startsWith(\"[\"))) return undefined;\n try {\n return JSON.parse(repair ? loadJsonrepair()(t) : t);\n } catch {\n return undefined;\n }\n}\n\n/** Heuristic scalar/JSON coercion (agentfw `coerceParameter` shape) used when there is no\n * per-field schema. Returns the coerced value, or the raw string when nothing applies.\n * @internal */\nexport function heuristicCoerce(raw: string, repairJson: boolean): unknown {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n if (raw === \"null\") return null;\n const n = toFiniteNumber(raw);\n if (n !== undefined) return n;\n const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : undefined);\n return json === undefined ? raw : json;\n}\n\n/** Candidates a raw string could coerce to, most-specific first. Used for schema-aware coercion:\n * the field schema selects the first candidate it accepts (so a string field keeps `\"5\"`).\n * @internal */\nexport function coerceCandidates(raw: string, repairJson: boolean): unknown[] {\n const out: unknown[] = [];\n if (raw === \"true\") out.push(true);\n else if (raw === \"false\") out.push(false);\n else if (raw === \"null\") out.push(null);\n const n = toFiniteNumber(raw);\n if (n !== undefined) out.push(n);\n const json = tryJson(raw, false) ?? (repairJson ? tryJson(raw, true) : undefined);\n if (json !== undefined) out.push(json);\n out.push(raw); // raw string is always the last-resort candidate\n return out;\n}\n\n/** True for a Zod schema that exposes a per-key `.shape` (a `z.object`, incl. Zod-v4\n * `.refine()`/`.default()` which keep `.shape`); non-object schemas (union/record) return\n * `undefined` so callers fall back to heuristic coercion (EC-4).\n * @internal */\nexport function objectShape(schema: ZodType | undefined): Record<string, ZodType> | undefined {\n const shape = (schema as unknown as { shape?: unknown } | undefined)?.shape;\n return shape !== null && typeof shape === \"object\"\n ? (shape as Record<string, ZodType>)\n : undefined;\n}\n","import type { ZodType } from \"zod\";\n\nimport {\n coerceCandidates,\n heuristicCoerce,\n isPlainObject,\n objectShape,\n tryJson,\n} from \"./coerce.js\";\nimport type { SanitizeOptions, SanitizeResult } from \"./types.js\";\n\ninterface Ctx {\n trim: boolean;\n coerce: boolean;\n repairJson: boolean;\n deep: boolean;\n maxDepth: number;\n shape: Record<string, ZodType> | undefined;\n notes: string[];\n}\n\n/** Trim rung — returns the trimmed string, noting the change. */\nfunction applyTrim(key: string, value: string, ctx: Ctx): string {\n const trimmed = value.trim();\n if (trimmed !== value) ctx.notes.push(`trimmed \"${key}\"`);\n return trimmed;\n}\n\n/** Coerce rung — schema-aware when a field schema exists (pick the first accepted candidate),\n * else heuristic. Returns the coerced value (or the raw string), noting the change. */\nfunction applyCoerce(key: string, raw: string, ctx: Ctx): unknown {\n const field = ctx.shape?.[key];\n let coerced: unknown = raw;\n if (field) {\n for (const candidate of coerceCandidates(raw, ctx.repairJson)) {\n if (field.safeParse(candidate).success) {\n coerced = candidate;\n break;\n }\n }\n } else {\n coerced = heuristicCoerce(raw, ctx.repairJson);\n }\n if (coerced !== raw) ctx.notes.push(`coerced \"${key}\"`);\n return coerced;\n}\n\n/** Repair rung — repair-then-parse a JSON-looking string, noting the change. */\nfunction applyRepair(key: string, value: string, ctx: Ctx): unknown {\n const repaired = tryJson(value, true);\n if (repaired === undefined) return value;\n ctx.notes.push(`repaired json \"${key}\"`);\n return repaired;\n}\n\n/** Sanitize one string value through the enabled rungs (trim → coerce → repair). */\nfunction sanitizeString(key: string, value: string, ctx: Ctx): unknown {\n let out: unknown = ctx.trim ? applyTrim(key, value, ctx) : value;\n if (ctx.coerce && typeof out === \"string\") out = applyCoerce(key, out, ctx);\n // Standalone repair runs ONLY when coerce is off. When coerce is on it already embedded the\n // repair candidate (via coerceCandidates / heuristicCoerce), and a schema-confirmed raw string\n // (e.g. a JSON string a `z.string()` field accepted) must not be clobbered back into an object.\n if (ctx.repairJson && !ctx.coerce && typeof out === \"string\") out = applyRepair(key, out, ctx);\n return out;\n}\n\nfunction walk(input: Record<string, unknown>, ctx: Ctx, depth: number): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n if (typeof value === \"string\") out[key] = sanitizeString(key, value, ctx);\n else if (ctx.deep && depth < ctx.maxDepth && isPlainObject(value))\n out[key] = walk(value, ctx, depth + 1);\n else out[key] = value;\n }\n return out;\n}\n\n/**\n * Sanitize the raw arguments a model emitted for a tool call — trim (default), optionally coerce\n * string values toward their expected type, optionally repair malformed JSON. Pure, synchronous,\n * and TOTAL: it never throws (non-object input is returned unchanged) and never changes a value's\n * meaning — only its hygiene/representation. Reused internally by the leaked-dialect recovery so\n * the public primitive and the internal path never diverge.\n *\n * @public\n */\nexport function sanitizeToolInput(\n input: Record<string, unknown>,\n options?: SanitizeOptions,\n): SanitizeResult {\n // EC-1 — total contract: a non-object (null / array / primitive) is returned as-is, never thrown on.\n if (!isPlainObject(input)) return { value: input, changed: false, notes: [] };\n const ctx: Ctx = {\n trim: options?.trim ?? true,\n coerce: options?.coerce ?? false,\n repairJson: options?.repairJson ?? false,\n deep: options?.deep ?? false,\n maxDepth: options?.maxDepth ?? 8,\n shape: objectShape(options?.schema),\n notes: [],\n };\n const value = walk(input, ctx, 0);\n return { value, changed: ctx.notes.length > 0, notes: ctx.notes };\n}\n"]}
@@ -0,0 +1,29 @@
1
+ import { withFileLock } from './chunk-HZQEDNF6.js';
2
+ import { readTranscript, transcriptPath, writeTranscript } from './chunk-ZZWTY3RX.js';
3
+ import { mkdir } from 'fs/promises';
4
+ import { dirname } from 'path';
5
+
6
+ var FsSessionStore = class {
7
+ #baseDir;
8
+ #cwd;
9
+ constructor(options) {
10
+ this.#baseDir = options.baseDir;
11
+ this.#cwd = options.cwd;
12
+ }
13
+ async readRecords(agentId) {
14
+ return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));
15
+ }
16
+ async appendRecords(agentId, records) {
17
+ if (records.length === 0) return;
18
+ const path = transcriptPath(this.#baseDir, this.#cwd, agentId);
19
+ await mkdir(dirname(path), { recursive: true });
20
+ await withFileLock(path, async () => {
21
+ const prior = await readTranscript(path);
22
+ await writeTranscript(path, [...prior, ...records]);
23
+ });
24
+ }
25
+ };
26
+
27
+ export { FsSessionStore };
28
+ //# sourceMappingURL=chunk-U6QGZHPN.js.map
29
+ //# sourceMappingURL=chunk-U6QGZHPN.js.map