@theokit/sdk 4.62.0 → 4.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/a2a/index.cjs +2 -2
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/{agent-DIu6FooJ.d.ts → agent-BFno7Sfn.d.ts} +36 -21
  5. package/dist/agent-WK7MKIMH.cjs +66 -0
  6. package/dist/{agent-VYPUO4UB.cjs.map → agent-WK7MKIMH.cjs.map} +1 -1
  7. package/dist/{agent-D3Xr_-6Z.d.cts → agent-X0DKA943.d.cts} +36 -21
  8. package/dist/agent-YWMBM7LX.js +57 -0
  9. package/dist/{agent-NVBFTY5H.js.map → agent-YWMBM7LX.js.map} +1 -1
  10. package/dist/agent-session-store-6EL5NPA4.cjs +24 -0
  11. package/dist/{agent-session-store-WAKLOKWK.cjs.map → agent-session-store-6EL5NPA4.cjs.map} +1 -1
  12. package/dist/agent-session-store-OPGRB4XM.js +7 -0
  13. package/dist/{agent-session-store-G2BMUZQV.js.map → agent-session-store-OPGRB4XM.js.map} +1 -1
  14. package/dist/auth/index.cjs +18 -18
  15. package/dist/auth/index.js +6 -6
  16. package/dist/{batch-ND32UKZS.cjs → batch-BXYTW2DP.cjs} +27 -27
  17. package/dist/{batch-ND32UKZS.cjs.map → batch-BXYTW2DP.cjs.map} +1 -1
  18. package/dist/{batch-2TGJMNCJ.js → batch-L4ZXS46M.js} +10 -10
  19. package/dist/{batch-2TGJMNCJ.js.map → batch-L4ZXS46M.js.map} +1 -1
  20. package/dist/{chunk-VF7EWVDG.js → chunk-2GUYQR5P.js} +3 -3
  21. package/dist/{chunk-VF7EWVDG.js.map → chunk-2GUYQR5P.js.map} +1 -1
  22. package/dist/{chunk-J2UROOIG.cjs → chunk-2HVF2WJY.cjs} +8 -8
  23. package/dist/{chunk-J2UROOIG.cjs.map → chunk-2HVF2WJY.cjs.map} +1 -1
  24. package/dist/{chunk-44MBDIHG.js → chunk-2QDYBS2A.js} +3 -3
  25. package/dist/{chunk-44MBDIHG.js.map → chunk-2QDYBS2A.js.map} +1 -1
  26. package/dist/{chunk-NGESVVJN.cjs → chunk-3FFAEAUJ.cjs} +17 -17
  27. package/dist/{chunk-NGESVVJN.cjs.map → chunk-3FFAEAUJ.cjs.map} +1 -1
  28. package/dist/{chunk-GWC3HADL.cjs → chunk-3NSS2OIZ.cjs} +4 -4
  29. package/dist/{chunk-GWC3HADL.cjs.map → chunk-3NSS2OIZ.cjs.map} +1 -1
  30. package/dist/{chunk-CV7XMBHP.js → chunk-3O42QOMJ.js} +3 -3
  31. package/dist/{chunk-CV7XMBHP.js.map → chunk-3O42QOMJ.js.map} +1 -1
  32. package/dist/{chunk-IWBGCBR6.cjs → chunk-4CLOXP6H.cjs} +4 -4
  33. package/dist/{chunk-IWBGCBR6.cjs.map → chunk-4CLOXP6H.cjs.map} +1 -1
  34. package/dist/{chunk-YEXA3PGR.js → chunk-4FFBAUFS.js} +5 -5
  35. package/dist/{chunk-YEXA3PGR.js.map → chunk-4FFBAUFS.js.map} +1 -1
  36. package/dist/{chunk-HY57ULY2.cjs → chunk-4PYZ5AX3.cjs} +5 -5
  37. package/dist/{chunk-HY57ULY2.cjs.map → chunk-4PYZ5AX3.cjs.map} +1 -1
  38. package/dist/{chunk-OC4NTGMN.js → chunk-4QZSA2HJ.js} +3 -3
  39. package/dist/{chunk-OC4NTGMN.js.map → chunk-4QZSA2HJ.js.map} +1 -1
  40. package/dist/{chunk-K3FW2XZD.cjs → chunk-4ZHTIJNE.cjs} +9 -9
  41. package/dist/{chunk-K3FW2XZD.cjs.map → chunk-4ZHTIJNE.cjs.map} +1 -1
  42. package/dist/{chunk-BUIK7GUA.cjs → chunk-5HEG4CQH.cjs} +8 -8
  43. package/dist/{chunk-BUIK7GUA.cjs.map → chunk-5HEG4CQH.cjs.map} +1 -1
  44. package/dist/{chunk-SKXBJ2NU.cjs → chunk-5VB22SYX.cjs} +7 -54
  45. package/dist/chunk-5VB22SYX.cjs.map +1 -0
  46. package/dist/{chunk-5USCYPPI.cjs → chunk-6HKGLTJI.cjs} +8 -8
  47. package/dist/{chunk-5USCYPPI.cjs.map → chunk-6HKGLTJI.cjs.map} +1 -1
  48. package/dist/chunk-6RKUO7AW.cjs +864 -0
  49. package/dist/chunk-6RKUO7AW.cjs.map +1 -0
  50. package/dist/{chunk-5JLFFPCH.js → chunk-7YGCPMGB.js} +4 -4
  51. package/dist/{chunk-5JLFFPCH.js.map → chunk-7YGCPMGB.js.map} +1 -1
  52. package/dist/{chunk-SUKXXLWD.js → chunk-A46SWMIF.js} +6 -6
  53. package/dist/{chunk-SUKXXLWD.js.map → chunk-A46SWMIF.js.map} +1 -1
  54. package/dist/{chunk-F7AQV62G.js → chunk-A4JVILQU.js} +5 -5
  55. package/dist/{chunk-F7AQV62G.js.map → chunk-A4JVILQU.js.map} +1 -1
  56. package/dist/chunk-A4RAL2ER.cjs +51 -0
  57. package/dist/chunk-A4RAL2ER.cjs.map +1 -0
  58. package/dist/{chunk-44JAAH4X.js → chunk-B3IMEBOA.js} +3 -3
  59. package/dist/{chunk-44JAAH4X.js.map → chunk-B3IMEBOA.js.map} +1 -1
  60. package/dist/{chunk-QDED6YO6.cjs → chunk-B4EOJWOY.cjs} +5 -5
  61. package/dist/{chunk-QDED6YO6.cjs.map → chunk-B4EOJWOY.cjs.map} +1 -1
  62. package/dist/{chunk-YJDH3CKG.js → chunk-BP46RJ5X.js} +5 -5
  63. package/dist/{chunk-YJDH3CKG.js.map → chunk-BP46RJ5X.js.map} +1 -1
  64. package/dist/{chunk-QRSUA2CV.js → chunk-BU4KFWXF.js} +3 -3
  65. package/dist/{chunk-QRSUA2CV.js.map → chunk-BU4KFWXF.js.map} +1 -1
  66. package/dist/{chunk-IBYRA5PM.js → chunk-BVJJ3DRV.js} +6 -6
  67. package/dist/{chunk-IBYRA5PM.js.map → chunk-BVJJ3DRV.js.map} +1 -1
  68. package/dist/{chunk-AQLGBKNT.js → chunk-BZRFXJHA.js} +3 -3
  69. package/dist/{chunk-AQLGBKNT.js.map → chunk-BZRFXJHA.js.map} +1 -1
  70. package/dist/{chunk-UQGQFBRL.js → chunk-C3NT3PVE.js} +3 -3
  71. package/dist/{chunk-UQGQFBRL.js.map → chunk-C3NT3PVE.js.map} +1 -1
  72. package/dist/{chunk-UC3HT2S4.js → chunk-C72AZW7J.js} +3 -3
  73. package/dist/{chunk-UC3HT2S4.js.map → chunk-C72AZW7J.js.map} +1 -1
  74. package/dist/{chunk-WNTAPVU5.cjs → chunk-CQBXOJ6U.cjs} +13 -13
  75. package/dist/{chunk-WNTAPVU5.cjs.map → chunk-CQBXOJ6U.cjs.map} +1 -1
  76. package/dist/{chunk-T7XEKOVW.js → chunk-D4CUGAKZ.js} +3 -3
  77. package/dist/{chunk-T7XEKOVW.js.map → chunk-D4CUGAKZ.js.map} +1 -1
  78. package/dist/chunk-DKD3MH6A.js +194 -0
  79. package/dist/chunk-DKD3MH6A.js.map +1 -0
  80. package/dist/{chunk-YXGAW7BB.js → chunk-DN2PACRI.js} +10 -10
  81. package/dist/{chunk-YXGAW7BB.js.map → chunk-DN2PACRI.js.map} +1 -1
  82. package/dist/{chunk-XSX2UU6Y.cjs → chunk-DXGZ2NUG.cjs} +10 -10
  83. package/dist/{chunk-XSX2UU6Y.cjs.map → chunk-DXGZ2NUG.cjs.map} +1 -1
  84. package/dist/{chunk-NUKRL3I6.cjs → chunk-EG4QM7ZJ.cjs} +18 -2
  85. package/dist/chunk-EG4QM7ZJ.cjs.map +1 -0
  86. package/dist/chunk-GEEXBYFL.js +831 -0
  87. package/dist/chunk-GEEXBYFL.js.map +1 -0
  88. package/dist/chunk-GKEFRLU7.cjs +21 -0
  89. package/dist/chunk-GKEFRLU7.cjs.map +1 -0
  90. package/dist/{chunk-NIRE5CNO.cjs → chunk-HCZD23VS.cjs} +13 -13
  91. package/dist/{chunk-NIRE5CNO.cjs.map → chunk-HCZD23VS.cjs.map} +1 -1
  92. package/dist/chunk-HOXVQ5FR.cjs +201 -0
  93. package/dist/chunk-HOXVQ5FR.cjs.map +1 -0
  94. package/dist/{chunk-QARJGQSA.js → chunk-HS7AVXTF.js} +3 -3
  95. package/dist/{chunk-QARJGQSA.js.map → chunk-HS7AVXTF.js.map} +1 -1
  96. package/dist/{chunk-4I55V454.cjs → chunk-I6HGWHPU.cjs} +4 -4
  97. package/dist/{chunk-4I55V454.cjs.map → chunk-I6HGWHPU.cjs.map} +1 -1
  98. package/dist/{chunk-T73NA43R.js → chunk-IPYYKCRC.js} +3 -3
  99. package/dist/{chunk-T73NA43R.js.map → chunk-IPYYKCRC.js.map} +1 -1
  100. package/dist/{chunk-6OBIWHDR.cjs → chunk-ITYQ6VBP.cjs} +24 -365
  101. package/dist/chunk-ITYQ6VBP.cjs.map +1 -0
  102. package/dist/chunk-JPBKYL3B.cjs +18 -0
  103. package/dist/{chunk-6HTXPPHK.cjs.map → chunk-JPBKYL3B.cjs.map} +1 -1
  104. package/dist/{chunk-MZ2FGBLZ.js → chunk-K5OJUYSZ.js} +4 -4
  105. package/dist/{chunk-MZ2FGBLZ.js.map → chunk-K5OJUYSZ.js.map} +1 -1
  106. package/dist/{chunk-SKOCYA55.js → chunk-KIH6IZ43.js} +90 -88
  107. package/dist/chunk-KIH6IZ43.js.map +1 -0
  108. package/dist/{chunk-EI2Q7SJ5.cjs → chunk-KQ7TS7WW.cjs} +10 -10
  109. package/dist/{chunk-EI2Q7SJ5.cjs.map → chunk-KQ7TS7WW.cjs.map} +1 -1
  110. package/dist/{chunk-RUDY2GTT.js → chunk-KQRW2GPZ.js} +5 -5
  111. package/dist/{chunk-RUDY2GTT.js.map → chunk-KQRW2GPZ.js.map} +1 -1
  112. package/dist/{chunk-P5LCASTC.cjs → chunk-KYAJINUI.cjs} +125 -125
  113. package/dist/{chunk-P5LCASTC.cjs.map → chunk-KYAJINUI.cjs.map} +1 -1
  114. package/dist/{chunk-CQ2TQ32Y.js → chunk-LWGSI6M3.js} +5 -50
  115. package/dist/chunk-LWGSI6M3.js.map +1 -0
  116. package/dist/{chunk-ZHPWGIUX.js → chunk-LXI4XZEC.js} +5 -5
  117. package/dist/{chunk-ZHPWGIUX.js.map → chunk-LXI4XZEC.js.map} +1 -1
  118. package/dist/{chunk-AG5JPQIY.js → chunk-LXQ6HKPS.js} +3 -3
  119. package/dist/{chunk-AG5JPQIY.js.map → chunk-LXQ6HKPS.js.map} +1 -1
  120. package/dist/{chunk-ROYPRJH4.cjs → chunk-LYRDF5TQ.cjs} +9 -9
  121. package/dist/{chunk-ROYPRJH4.cjs.map → chunk-LYRDF5TQ.cjs.map} +1 -1
  122. package/dist/{chunk-G24KZRSA.js → chunk-N2U4AZGB.js} +3 -3
  123. package/dist/{chunk-G24KZRSA.js.map → chunk-N2U4AZGB.js.map} +1 -1
  124. package/dist/{chunk-4ERPXIVB.js → chunk-O73J46PV.js} +5 -5
  125. package/dist/{chunk-4ERPXIVB.js.map → chunk-O73J46PV.js.map} +1 -1
  126. package/dist/{chunk-F3YZMOAU.cjs → chunk-O7DK5PBJ.cjs} +4 -4
  127. package/dist/{chunk-F3YZMOAU.cjs.map → chunk-O7DK5PBJ.cjs.map} +1 -1
  128. package/dist/{chunk-Z4BCLVTI.cjs → chunk-O7LZFG6O.cjs} +5 -5
  129. package/dist/{chunk-Z4BCLVTI.cjs.map → chunk-O7LZFG6O.cjs.map} +1 -1
  130. package/dist/{chunk-3YJNUKYN.cjs → chunk-OHLDPWTA.cjs} +15 -15
  131. package/dist/{chunk-3YJNUKYN.cjs.map → chunk-OHLDPWTA.cjs.map} +1 -1
  132. package/dist/{chunk-FUL2I7G5.js → chunk-OSEG74VJ.js} +8 -8
  133. package/dist/{chunk-FUL2I7G5.js.map → chunk-OSEG74VJ.js.map} +1 -1
  134. package/dist/{chunk-UCBJBJ27.js → chunk-PUAEFLYK.js} +4 -4
  135. package/dist/{chunk-UCBJBJ27.js.map → chunk-PUAEFLYK.js.map} +1 -1
  136. package/dist/{chunk-CWHTMNNK.cjs → chunk-Q7LPTOD6.cjs} +24 -24
  137. package/dist/{chunk-CWHTMNNK.cjs.map → chunk-Q7LPTOD6.cjs.map} +1 -1
  138. package/dist/{chunk-2C72DXQF.cjs → chunk-RFMBZPOW.cjs} +9 -9
  139. package/dist/{chunk-2C72DXQF.cjs.map → chunk-RFMBZPOW.cjs.map} +1 -1
  140. package/dist/{chunk-NLTVXLGT.js → chunk-RFXWMRFC.js} +3 -3
  141. package/dist/{chunk-NLTVXLGT.js.map → chunk-RFXWMRFC.js.map} +1 -1
  142. package/dist/{chunk-2DG7KW4L.cjs → chunk-RMWTPV3M.cjs} +8 -8
  143. package/dist/{chunk-2DG7KW4L.cjs.map → chunk-RMWTPV3M.cjs.map} +1 -1
  144. package/dist/{chunk-P6A3M6VD.cjs → chunk-SZVR77EJ.cjs} +10 -10
  145. package/dist/{chunk-P6A3M6VD.cjs.map → chunk-SZVR77EJ.cjs.map} +1 -1
  146. package/dist/{chunk-3E77SX4H.js → chunk-TAZVKYWJ.js} +3 -3
  147. package/dist/{chunk-3E77SX4H.js.map → chunk-TAZVKYWJ.js.map} +1 -1
  148. package/dist/{chunk-WKRSH2VR.js → chunk-U6IFHFWK.js} +3 -3
  149. package/dist/{chunk-WKRSH2VR.js.map → chunk-U6IFHFWK.js.map} +1 -1
  150. package/dist/{chunk-I6TGFUCO.cjs → chunk-UALX2J2Q.cjs} +4 -4
  151. package/dist/{chunk-I6TGFUCO.cjs.map → chunk-UALX2J2Q.cjs.map} +1 -1
  152. package/dist/{chunk-XN7NOENA.js → chunk-UBDMVMBZ.js} +5 -5
  153. package/dist/{chunk-XN7NOENA.js.map → chunk-UBDMVMBZ.js.map} +1 -1
  154. package/dist/{chunk-QEKI3YKI.js → chunk-UEXIJTLC.js} +14 -349
  155. package/dist/chunk-UEXIJTLC.js.map +1 -0
  156. package/dist/{chunk-DQKERTND.cjs → chunk-UGT7GK7I.cjs} +11 -11
  157. package/dist/{chunk-DQKERTND.cjs.map → chunk-UGT7GK7I.cjs.map} +1 -1
  158. package/dist/{chunk-FKMUFNQE.js → chunk-UMP6OJIM.js} +4 -4
  159. package/dist/{chunk-FKMUFNQE.js.map → chunk-UMP6OJIM.js.map} +1 -1
  160. package/dist/{chunk-AEOZTXVW.js → chunk-UNYXQ4M5.js} +3 -3
  161. package/dist/{chunk-AEOZTXVW.js.map → chunk-UNYXQ4M5.js.map} +1 -1
  162. package/dist/{chunk-2BDH744Z.js → chunk-UTSRIDKZ.js} +3 -3
  163. package/dist/{chunk-2BDH744Z.js.map → chunk-UTSRIDKZ.js.map} +1 -1
  164. package/dist/{chunk-2ADR2GSO.cjs → chunk-UU36SHFY.cjs} +5 -5
  165. package/dist/{chunk-2ADR2GSO.cjs.map → chunk-UU36SHFY.cjs.map} +1 -1
  166. package/dist/{chunk-R3UPQFKK.cjs → chunk-V2BOS4WF.cjs} +9 -9
  167. package/dist/{chunk-R3UPQFKK.cjs.map → chunk-V2BOS4WF.cjs.map} +1 -1
  168. package/dist/chunk-WE22OXQA.js +48 -0
  169. package/dist/chunk-WE22OXQA.js.map +1 -0
  170. package/dist/{chunk-Q4CMI2LP.js → chunk-WLQNMXQE.js} +5 -5
  171. package/dist/{chunk-Q4CMI2LP.js.map → chunk-WLQNMXQE.js.map} +1 -1
  172. package/dist/{chunk-XWL6O3SW.cjs → chunk-WNO3C3N2.cjs} +4 -4
  173. package/dist/{chunk-XWL6O3SW.cjs.map → chunk-WNO3C3N2.cjs.map} +1 -1
  174. package/dist/{chunk-T7O6K6PX.js → chunk-XEQ3TM66.js} +18 -3
  175. package/dist/chunk-XEQ3TM66.js.map +1 -0
  176. package/dist/{chunk-BVZW2B5V.cjs → chunk-XJCXEKMD.cjs} +4 -4
  177. package/dist/{chunk-BVZW2B5V.cjs.map → chunk-XJCXEKMD.cjs.map} +1 -1
  178. package/dist/{chunk-JTB5Q42C.cjs → chunk-XL7Q7HB2.cjs} +4 -4
  179. package/dist/{chunk-JTB5Q42C.cjs.map → chunk-XL7Q7HB2.cjs.map} +1 -1
  180. package/dist/chunk-XO4SOZN6.js +19 -0
  181. package/dist/chunk-XO4SOZN6.js.map +1 -0
  182. package/dist/{chunk-CQGYNZ3K.cjs → chunk-XWTLIGO3.cjs} +4 -4
  183. package/dist/{chunk-CQGYNZ3K.cjs.map → chunk-XWTLIGO3.cjs.map} +1 -1
  184. package/dist/{chunk-6SBW4QR2.cjs → chunk-YML4ME27.cjs} +11 -11
  185. package/dist/{chunk-6SBW4QR2.cjs.map → chunk-YML4ME27.cjs.map} +1 -1
  186. package/dist/{chunk-P6H23T43.cjs → chunk-ZCIRZE37.cjs} +11 -11
  187. package/dist/{chunk-P6H23T43.cjs.map → chunk-ZCIRZE37.cjs.map} +1 -1
  188. package/dist/{chunk-QI7WE46I.cjs → chunk-ZLQSWSJ2.cjs} +11 -11
  189. package/dist/{chunk-QI7WE46I.cjs.map → chunk-ZLQSWSJ2.cjs.map} +1 -1
  190. package/dist/{chunk-AH6WD7JR.cjs → chunk-ZMRD5DZQ.cjs} +362 -360
  191. package/dist/chunk-ZMRD5DZQ.cjs.map +1 -0
  192. package/dist/{chunk-ILCGLTSA.cjs → chunk-ZSWPZ23K.cjs} +4 -4
  193. package/dist/{chunk-ILCGLTSA.cjs.map → chunk-ZSWPZ23K.cjs.map} +1 -1
  194. package/dist/{chunk-IDCKSLYH.js → chunk-ZZMZWBR6.js} +3 -3
  195. package/dist/{chunk-IDCKSLYH.js.map → chunk-ZZMZWBR6.js.map} +1 -1
  196. package/dist/compact-session-QV57KR66.cjs +59 -0
  197. package/dist/{compact-session-GJXJD73F.cjs.map → compact-session-QV57KR66.cjs.map} +1 -1
  198. package/dist/compact-session-RIGOWC4Y.js +22 -0
  199. package/dist/{compact-session-TSMQOIHO.js.map → compact-session-RIGOWC4Y.js.map} +1 -1
  200. package/dist/compaction.cjs +17 -17
  201. package/dist/compaction.js +4 -4
  202. package/dist/concurrency.cjs +7 -7
  203. package/dist/concurrency.js +5 -5
  204. package/dist/context-AGQ3DIZU.cjs +24 -0
  205. package/dist/{context-LCKNH2XI.cjs.map → context-AGQ3DIZU.cjs.map} +1 -1
  206. package/dist/context-GQRFBCLP.js +7 -0
  207. package/dist/{context-MZSKGKYR.js.map → context-GQRFBCLP.js.map} +1 -1
  208. package/dist/{cron-BcWmzWzT.d.cts → cron-BuiRPrvt.d.cts} +1 -1
  209. package/dist/{cron-De6hzWCF.d.ts → cron-C2SIi31n.d.ts} +1 -1
  210. package/dist/cron.cjs +37 -35
  211. package/dist/cron.d.cts +2 -2
  212. package/dist/cron.d.ts +2 -2
  213. package/dist/cron.js +36 -34
  214. package/dist/errors.cjs +22 -22
  215. package/dist/errors.js +3 -3
  216. package/dist/eval.cjs +42 -40
  217. package/dist/eval.cjs.map +1 -1
  218. package/dist/eval.js +36 -34
  219. package/dist/eval.js.map +1 -1
  220. package/dist/{executor-ZERJ3DGN.cjs → executor-6CYCA7MI.cjs} +25 -25
  221. package/dist/{executor-ZERJ3DGN.cjs.map → executor-6CYCA7MI.cjs.map} +1 -1
  222. package/dist/{executor-BMEHFOXZ.js → executor-QSEC3MRH.js} +8 -8
  223. package/dist/{executor-BMEHFOXZ.js.map → executor-QSEC3MRH.js.map} +1 -1
  224. package/dist/filesystem/index.cjs +8 -8
  225. package/dist/filesystem/index.js +4 -4
  226. package/dist/fs-session-store-4PIHT5UX.cjs +20 -0
  227. package/dist/{fs-session-store-XZ7ZTB3A.cjs.map → fs-session-store-4PIHT5UX.cjs.map} +1 -1
  228. package/dist/fs-session-store-NM6YSTE2.js +11 -0
  229. package/dist/{fs-session-store-4BHGIWRE.js.map → fs-session-store-NM6YSTE2.js.map} +1 -1
  230. package/dist/generate-object-GUNAUVBX.js +8 -0
  231. package/dist/{generate-object-N5MDZUJI.js.map → generate-object-GUNAUVBX.js.map} +1 -1
  232. package/dist/generate-object-R7HTMW7F.cjs +21 -0
  233. package/dist/{generate-object-PGSP5U7N.cjs.map → generate-object-R7HTMW7F.cjs.map} +1 -1
  234. package/dist/index-manager-RBDHP3PM.js +17 -0
  235. package/dist/{index-manager-AHAYJ33H.js.map → index-manager-RBDHP3PM.js.map} +1 -1
  236. package/dist/index-manager-UZBF22BJ.cjs +26 -0
  237. package/dist/{index-manager-RHPFVFSC.cjs.map → index-manager-UZBF22BJ.cjs.map} +1 -1
  238. package/dist/index.cjs +146 -319
  239. package/dist/index.cjs.map +1 -1
  240. package/dist/index.d.cts +8 -3
  241. package/dist/index.d.ts +8 -3
  242. package/dist/index.js +62 -235
  243. package/dist/index.js.map +1 -1
  244. package/dist/{inject-session-ZCQUB3IT.js → inject-session-DAR7OUCW.js} +8 -8
  245. package/dist/{inject-session-ZCQUB3IT.js.map → inject-session-DAR7OUCW.js.map} +1 -1
  246. package/dist/{inject-session-PPSO2IDD.cjs → inject-session-WQKMC3GR.cjs} +10 -10
  247. package/dist/{inject-session-PPSO2IDD.cjs.map → inject-session-WQKMC3GR.cjs.map} +1 -1
  248. package/dist/internal/memory/active-memory.d.ts +8 -1
  249. package/dist/internal/memory/adapters/index.cjs +9 -9
  250. package/dist/internal/memory/adapters/index.js +8 -8
  251. package/dist/internal/memory/dreaming/diary.d.ts +39 -2
  252. package/dist/internal/memory/index-db.d.ts +44 -1
  253. package/dist/internal/memory/index-manager-contract.d.ts +10 -0
  254. package/dist/internal/memory/index-manager-helpers.d.ts +20 -1
  255. package/dist/internal/memory/index-manager.d.ts +1 -1
  256. package/dist/internal/memory/lance-index.d.ts +15 -1
  257. package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +43 -0
  258. package/dist/internal/memory/storage/index.cjs +101 -18
  259. package/dist/internal/memory/storage/index.d.cts +11 -1
  260. package/dist/internal/memory/storage/index.d.ts +11 -1
  261. package/dist/internal/memory/storage/index.js +10 -7
  262. package/dist/internal/memory/storage/markdown-store.d.cts +13 -42
  263. package/dist/internal/memory/storage/markdown-store.d.ts +13 -42
  264. package/dist/internal/memory/storage/memory-root.d.cts +93 -0
  265. package/dist/internal/memory/storage/memory-root.d.ts +93 -0
  266. package/dist/internal/memory/storage/session-loader.d.cts +35 -1
  267. package/dist/internal/memory/storage/session-loader.d.ts +35 -1
  268. package/dist/internal/memory/storage/session-summary-writer.d.cts +50 -2
  269. package/dist/internal/memory/storage/session-summary-writer.d.ts +50 -2
  270. package/dist/internal/memory/storage/transcript-store.d.cts +38 -1
  271. package/dist/internal/memory/storage/transcript-store.d.ts +38 -1
  272. package/dist/internal/memory/storage/wiki-loader.d.cts +27 -2
  273. package/dist/internal/memory/storage/wiki-loader.d.ts +27 -2
  274. package/dist/internal/memory/tools.d.ts +8 -1
  275. package/dist/internal/memory/types.d.ts +5 -0
  276. package/dist/internal/persistence/index.cjs +29 -28
  277. package/dist/internal/persistence/index.cjs.map +1 -1
  278. package/dist/internal/persistence/index.js +8 -7
  279. package/dist/internal/persistence/index.js.map +1 -1
  280. package/dist/internal/persistence/session-dir.d.cts +0 -15
  281. package/dist/internal/persistence/session-dir.d.ts +0 -15
  282. package/dist/internal/runtime/memory/memory-store.d.ts +2 -2
  283. package/dist/internal/security/index.cjs +14 -14
  284. package/dist/internal/security/index.js +4 -4
  285. package/dist/judge-call-LAHMBJ57.cjs +23 -0
  286. package/dist/{judge-call-EGYRC2RE.cjs.map → judge-call-LAHMBJ57.cjs.map} +1 -1
  287. package/dist/judge-call-LVXABPS3.js +6 -0
  288. package/dist/{judge-call-DWHAJATE.js.map → judge-call-LVXABPS3.js.map} +1 -1
  289. package/dist/mcp-auth.cjs +15 -15
  290. package/dist/mcp-auth.js +5 -5
  291. package/dist/models.cjs +22 -22
  292. package/dist/models.js +7 -7
  293. package/dist/path-safety.cjs +11 -11
  294. package/dist/path-safety.js +4 -4
  295. package/dist/persistence.cjs +33 -32
  296. package/dist/persistence.cjs.map +1 -1
  297. package/dist/persistence.js +10 -9
  298. package/dist/persistence.js.map +1 -1
  299. package/dist/project.cjs +6 -6
  300. package/dist/project.js +4 -4
  301. package/dist/providers.cjs +9 -9
  302. package/dist/providers.js +7 -7
  303. package/dist/registry-75W33OGL.js +10 -0
  304. package/dist/{registry-VFP3WWQP.js.map → registry-75W33OGL.js.map} +1 -1
  305. package/dist/registry-V7BDQ6QB.cjs +47 -0
  306. package/dist/{registry-VFKX7WOP.cjs.map → registry-V7BDQ6QB.cjs.map} +1 -1
  307. package/dist/retry.cjs +5 -5
  308. package/dist/retry.js +4 -4
  309. package/dist/sandbox/index.cjs +7 -7
  310. package/dist/sandbox/index.js +3 -3
  311. package/dist/server/errors-envelope.cjs +15 -15
  312. package/dist/server/errors-envelope.js +4 -4
  313. package/dist/session-transcript-6WNITKRE.cjs +63 -0
  314. package/dist/{session-transcript-HF5GEU5M.cjs.map → session-transcript-6WNITKRE.cjs.map} +1 -1
  315. package/dist/session-transcript-XAEKW6P7.js +6 -0
  316. package/dist/{session-transcript-P462ZRHX.js.map → session-transcript-XAEKW6P7.js.map} +1 -1
  317. package/dist/skills.cjs +8 -8
  318. package/dist/skills.js +6 -6
  319. package/dist/stream-object-UF4QRQRU.js +8 -0
  320. package/dist/{stream-object-L57K4OFS.js.map → stream-object-UF4QRQRU.js.map} +1 -1
  321. package/dist/stream-object-ZJTQNKY3.cjs +21 -0
  322. package/dist/{stream-object-BUCF5PHO.cjs.map → stream-object-ZJTQNKY3.cjs.map} +1 -1
  323. package/dist/subagents-loader-CRT5LLL3.js +8 -0
  324. package/dist/{subagents-loader-6ATCDEKN.js.map → subagents-loader-CRT5LLL3.js.map} +1 -1
  325. package/dist/subagents-loader-YEUFFPAL.cjs +17 -0
  326. package/dist/{subagents-loader-X5QKODCL.cjs.map → subagents-loader-YEUFFPAL.cjs.map} +1 -1
  327. package/dist/subagents-loader.cjs +7 -7
  328. package/dist/subagents-loader.d.cts +1 -1
  329. package/dist/subagents-loader.d.ts +1 -1
  330. package/dist/subagents-loader.js +5 -5
  331. package/dist/subscription/index.cjs +4 -4
  332. package/dist/subscription/index.js +3 -3
  333. package/dist/task-store.cjs +8 -8
  334. package/dist/task-store.js +5 -5
  335. package/dist/types/agent.d.ts +11 -0
  336. package/dist/types/memory-provider.d.ts +8 -0
  337. package/dist/workflow.cjs +28 -28
  338. package/dist/workflow.js +7 -7
  339. package/docs/error-codes.md +10 -9
  340. package/docs/harness-capability-map.md +57 -17
  341. package/docs/memory-decisions.md +44 -7
  342. package/package.json +1 -1
  343. package/dist/agent-NVBFTY5H.js +0 -55
  344. package/dist/agent-VYPUO4UB.cjs +0 -64
  345. package/dist/agent-session-store-G2BMUZQV.js +0 -7
  346. package/dist/agent-session-store-WAKLOKWK.cjs +0 -24
  347. package/dist/chunk-2UCFUSPW.cjs +0 -468
  348. package/dist/chunk-2UCFUSPW.cjs.map +0 -1
  349. package/dist/chunk-6HTXPPHK.cjs +0 -18
  350. package/dist/chunk-6OBIWHDR.cjs.map +0 -1
  351. package/dist/chunk-AH6WD7JR.cjs.map +0 -1
  352. package/dist/chunk-CQ2TQ32Y.js.map +0 -1
  353. package/dist/chunk-NUKRL3I6.cjs.map +0 -1
  354. package/dist/chunk-QEKI3YKI.js.map +0 -1
  355. package/dist/chunk-SKOCYA55.js.map +0 -1
  356. package/dist/chunk-SKXBJ2NU.cjs.map +0 -1
  357. package/dist/chunk-T7O6K6PX.js.map +0 -1
  358. package/dist/chunk-WCLDJSMY.js +0 -456
  359. package/dist/chunk-WCLDJSMY.js.map +0 -1
  360. package/dist/compact-session-GJXJD73F.cjs +0 -59
  361. package/dist/compact-session-TSMQOIHO.js +0 -22
  362. package/dist/context-LCKNH2XI.cjs +0 -24
  363. package/dist/context-MZSKGKYR.js +0 -7
  364. package/dist/fs-session-store-4BHGIWRE.js +0 -11
  365. package/dist/fs-session-store-XZ7ZTB3A.cjs +0 -20
  366. package/dist/generate-object-N5MDZUJI.js +0 -8
  367. package/dist/generate-object-PGSP5U7N.cjs +0 -21
  368. package/dist/index-manager-AHAYJ33H.js +0 -16
  369. package/dist/index-manager-RHPFVFSC.cjs +0 -25
  370. package/dist/judge-call-DWHAJATE.js +0 -6
  371. package/dist/judge-call-EGYRC2RE.cjs +0 -23
  372. package/dist/registry-VFKX7WOP.cjs +0 -47
  373. package/dist/registry-VFP3WWQP.js +0 -10
  374. package/dist/session-transcript-HF5GEU5M.cjs +0 -63
  375. package/dist/session-transcript-P462ZRHX.js +0 -6
  376. package/dist/stream-object-BUCF5PHO.cjs +0 -21
  377. package/dist/stream-object-L57K4OFS.js +0 -8
  378. package/dist/subagents-loader-6ATCDEKN.js +0 -8
  379. package/dist/subagents-loader-X5QKODCL.cjs +0 -17
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkQDED6YO6_cjs = require('./chunk-QDED6YO6.cjs');
3
+ var chunkB4EOJWOY_cjs = require('./chunk-B4EOJWOY.cjs');
4
4
 
5
5
  // src/generate-object.ts
6
6
  var GenerateObjectError = class extends Error {
@@ -41,11 +41,11 @@ async function runReasoningPhase(options, deps) {
41
41
  const text = result.result;
42
42
  return typeof text === "string" ? text : options.prompt;
43
43
  } finally {
44
- await chunkQDED6YO6_cjs.disposeAndDeleteTransient(reasoningAgent, deps.delete);
44
+ await chunkB4EOJWOY_cjs.disposeAndDeleteTransient(reasoningAgent, deps.delete);
45
45
  }
46
46
  }
47
47
  async function generateObjectImpl(options, deps) {
48
- const { jsonSchema, maxRetries, initialUsage } = chunkQDED6YO6_cjs.setupStructuredOutput(
48
+ const { jsonSchema, maxRetries, initialUsage } = chunkB4EOJWOY_cjs.setupStructuredOutput(
49
49
  options.schema,
50
50
  options.maxRetries
51
51
  );
@@ -60,7 +60,7 @@ async function generateObjectImpl(options, deps) {
60
60
  captured;
61
61
  [sentinel] = true;
62
62
  }
63
- const outputTool = chunkQDED6YO6_cjs.makeOutputTool(jsonSchema, (input) => {
63
+ const outputTool = chunkB4EOJWOY_cjs.makeOutputTool(jsonSchema, (input) => {
64
64
  if (capturedRaw === void 0) {
65
65
  capturedRaw = input;
66
66
  }
@@ -69,7 +69,7 @@ async function generateObjectImpl(options, deps) {
69
69
  const reasoningText = options.structuringModel !== void 0 ? await runReasoningPhase(options, deps) : void 0;
70
70
  const structuringModel = options.structuringModel ?? options.model;
71
71
  const structuringPrompt = reasoningText ?? options.prompt;
72
- const agentOptions = chunkQDED6YO6_cjs.buildTransientAgentOptions({
72
+ const agentOptions = chunkB4EOJWOY_cjs.buildTransientAgentOptions({
73
73
  model: structuringModel,
74
74
  local: options.local,
75
75
  outputTool,
@@ -79,13 +79,13 @@ async function generateObjectImpl(options, deps) {
79
79
  });
80
80
  const agent = await deps.create(agentOptions);
81
81
  try {
82
- const userMessage = chunkQDED6YO6_cjs.buildToolPrompt(structuringPrompt);
82
+ const userMessage = chunkB4EOJWOY_cjs.buildToolPrompt(structuringPrompt);
83
83
  let lastParseError;
84
84
  for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
85
85
  capturedRaw = void 0;
86
86
  const run = await agent.send(userMessage);
87
87
  const result = await run.wait();
88
- lastUsage = chunkQDED6YO6_cjs.extractUsage(result);
88
+ lastUsage = chunkB4EOJWOY_cjs.extractUsage(result);
89
89
  if (capturedRaw === void 0) {
90
90
  if (result.status === "error" && result.error !== void 0) {
91
91
  throw new GenerateObjectError(
@@ -135,11 +135,11 @@ async function generateObjectImpl(options, deps) {
135
135
  lastParseError
136
136
  );
137
137
  } finally {
138
- await chunkQDED6YO6_cjs.disposeAndDeleteTransient(agent, deps.delete);
138
+ await chunkB4EOJWOY_cjs.disposeAndDeleteTransient(agent, deps.delete);
139
139
  }
140
140
  }
141
141
 
142
142
  exports.GenerateObjectError = GenerateObjectError;
143
143
  exports.generateObjectImpl = generateObjectImpl;
144
- //# sourceMappingURL=chunk-P6A3M6VD.cjs.map
145
- //# sourceMappingURL=chunk-P6A3M6VD.cjs.map
144
+ //# sourceMappingURL=chunk-SZVR77EJ.cjs.map
145
+ //# sourceMappingURL=chunk-SZVR77EJ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generate-object.ts"],"names":["disposeAndDeleteTransient","setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","build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,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,MAAML,2CAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-P6A3M6VD.cjs","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 * 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/**\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// 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"]}
1
+ {"version":3,"sources":["../src/generate-object.ts"],"names":["disposeAndDeleteTransient","setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage"],"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,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,WAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AACtD,IAAA,IAAI,OAAO,WAAA,EAAa,SAAA,KAAc,UAAA,EAAY;AAClD,IAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAChD,IAAA,IAAI,MAAA,CAAO,OAAA,EAAS,GAAA,CAAI,GAAG,IAAI,MAAA,CAAO,IAAA;AAAA,EACxC;AACA,EAAA,O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A,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,MAAML,2CAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-SZVR77EJ.cjs","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 * 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/**\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// 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"]}
@@ -1,5 +1,5 @@
1
1
  import { withCwdMutex } from './chunk-Q5EWJPRY.js';
2
- import { ConfigurationError } from './chunk-IDCKSLYH.js';
2
+ import { ConfigurationError } from './chunk-ZZMZWBR6.js';
3
3
  import { AsyncLocalStorage } from 'async_hooks';
4
4
 
5
5
  // src/internal/llm/credential-pool-types.ts
@@ -285,5 +285,5 @@ function currentCredentialPool(provider) {
285
285
  }
286
286
 
287
287
  export { CredentialPool, computeBackoffMs, currentCredentialPool, newPooledCredential, sleepWithAbort, withCredentialPool };
288
- //# sourceMappingURL=chunk-3E77SX4H.js.map
289
- //# sourceMappingURL=chunk-3E77SX4H.js.map
288
+ //# sourceMappingURL=chunk-TAZVKYWJ.js.map
289
+ //# sourceMappingURL=chunk-TAZVKYWJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["picked"],"mappings":";;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AA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BAAA;AACtB,MAAA,IAAI,OAAA,KAAY,MAAA,IAAa,GAAA,IAAO,OAAA,EAAS;AAC3C,QAAA,KAAA,CAAM,UAAA,GAAa,IAAA;AACnB,QAAA,KAAA,CAAM,YAAA,GAAe,MAAA;AACrB,QAAA,KAAA,CAAM,aAAA,GAAgB,MAAA;AACtB,QAAA,KAAA,CAAM,gBAAA,GAAmB,MAAA;AACzB,QAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;AAMA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAA0B,EAAC;AACjC,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAI,iBAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-3E77SX4H.js","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["picked"],"mappings":";;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AAchB,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,MAAM,IAAA,GAAO,KAAK,MAAA,IAAU,eAAA;AAC5B,EAAA,MAAM,GAAA,GAAM,KAAK,KAAA,IAAS,cAAA;AAC1B,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,IAAA,CAAK,MAAA;AAC7B,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,IAAa,IAAA,CAAK,gBAAgB,CAAA,EAAG;AAC7D,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAM,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,YAAY,CAAC,CAAA;AAAA,EACxD;AACA,EAAA,MAAM,UAAU,IAAA,CAAK,GAAA,CAAI,KAAK,IAAA,GAAO,CAAA,IAAK,KAAK,OAAO,CAAA;AACtD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,EAAI,GAAI,OAAO,CAAA;AACnC;AASO,SAAS,cAAA,CAAe,IAAY,MAAA,EAAoC;AAC7E,EAAA,IAAI,MAAM,CAAA,IAAK,MAAA,CAAO,OAAA,EAAS,OAAO,QAAQ,OA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M,mBAAA,GAAsB,IAAI,iBAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-TAZVKYWJ.js","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-AEOZTXVW.js';
1
+ import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-UNYXQ4M5.js';
2
2
 
3
3
  // src/stream-object.ts
4
4
  var StreamObjectError = class extends Error {
@@ -141,5 +141,5 @@ function bestEffortPartialParse(text, schema) {
141
141
  }
142
142
 
143
143
  export { StreamObjectError, streamObjectImpl };
144
- //# sourceMappingURL=chunk-WKRSH2VR.js.map
145
- //# sourceMappingURL=chunk-WKRSH2VR.js.map
144
+ //# sourceMappingURL=chunk-U6IFHFWK.js.map
145
+ //# sourceMappingURL=chunk-U6IFHFWK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stream-object.ts"],"names":[],"mappings":";;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA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AAI,MAAA;AACrF,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAM,CAAA;AAC3C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"chunk-WKRSH2VR.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.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\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\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\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 StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * REACHED BY DYNAMIC IMPORT — do not delete on a dead-code report (B-140).\n * `agent.ts` loads this module lazily to keep it off the eager path:\n *\n * streamObjectImport ??= import(\"./stream-object.js\");\n * const { streamObjectImpl } = await streamObjectImport;\n *\n * `knip` resolves imports statically and does not follow a destructure off a\n * dynamic-import promise, so it reports this export as unused on every run. It\n * is not: removing it breaks `Agent.streamObject`. That is why this file is\n * named in `knip.json`'s ignore list rather than cleaned up — the entry is a\n * tool limitation, not a suppression of a real finding, and the difference is\n * the whole reason this comment exists.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\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 const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\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 StreamObjectError(\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 if (attempt === maxRetries) {\n throw new StreamObjectError(\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 yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
1
+ {"version":3,"sources":["../src/stream-object.ts"],"names":[],"mappings":";;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;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;AA6BA,gBAAuB,gBAAA,CACrB,SACA,IAAA,EACsE;AACtE,EAAA,MAAM,EAAE,UAAA,EAAY,UAAA,EAAY,YAAA,EAAa,GAAI,qBAAA;AAAA,IAC/C,OAAA,CAAQ,MAAA;AAAA,IACR,OAAA,CAAQ;AAAA,GACV;AACA,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,SAAA,GAAY,YAAA;AAEhB,EAAA,MAAM,UAAA,GAAa,cAAA,CAAe,UAAA,EAAY,CAAC,KAAA,KAAU;AAEvD,IAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,MAAA,WAAA,GAAc,KAAA;AAAA,IAChB;AACA,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,EACpC,CAAC,CAAA;AAED,EAAA,MAAM,eAA6B,0BAAA,CAA2B;AAAA,IAC5D,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,UAAA;AAAA,IACA,GAAI,QAAQ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AAO,MAAM,CAAC,CAAA;AAC3C,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,SAAS,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,MAAM,eAAgB,MAAA,CAAkD,OAAA;AACxE,EAAA,MAAM,cAAc,OAAO,YAAA,KAAiB,aAAa,YAAA,CAAa,IAAA,CAAK,MAAM,CAAA,GAAI,MAAA;AACrF,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAM,CAAA;AAC3C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"chunk-U6IFHFWK.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.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\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\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\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 StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * REACHED BY DYNAMIC IMPORT — do not delete on a dead-code report (B-140).\n * `agent.ts` loads this module lazily to keep it off the eager path:\n *\n * streamObjectImport ??= import(\"./stream-object.js\");\n * const { streamObjectImpl } = await streamObjectImport;\n *\n * `knip` resolves imports statically and does not follow a destructure off a\n * dynamic-import promise, so it reports this export as unused on every run. It\n * is not: removing it breaks `Agent.streamObject`. That is why this file is\n * named in `knip.json`'s ignore list rather than cleaned up — the entry is a\n * tool limitation, not a suppression of a real finding, and the difference is\n * the whole reason this comment exists.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\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 const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\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 StreamObjectError(\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 if (attempt === maxRetries) {\n throw new StreamObjectError(\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 yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
3
+ var chunkEG4QM7ZJ_cjs = require('./chunk-EG4QM7ZJ.cjs');
4
4
  var crypto = require('crypto');
5
5
  var promises = require('fs/promises');
6
6
  var path = require('path');
@@ -23,7 +23,7 @@ async function warnOnNetworkFsOnce(dirPath, label) {
23
23
  const info = await promises.statfs(dirPath);
24
24
  const fsName = detectNetworkFsName(info.type);
25
25
  if (fsName === null) return;
26
- chunkNUKRL3I6_cjs.diag(
26
+ chunkEG4QM7ZJ_cjs.diag(
27
27
  `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} \u2014 rename() atomicity guarantees may be weaker than expected.
28
28
  `
29
29
  );
@@ -77,5 +77,5 @@ exports.atomicWriteJson = atomicWriteJson;
77
77
  exports.atomicWriteTempTarget = atomicWriteTempTarget;
78
78
  exports.atomicWriteText = atomicWriteText;
79
79
  exports.replaceFileAtomic = replaceFileAtomic;
80
- //# sourceMappingURL=chunk-I6TGFUCO.cjs.map
81
- //# sourceMappingURL=chunk-I6TGFUCO.cjs.map
80
+ //# sourceMappingURL=chunk-UALX2J2Q.cjs.map
81
+ //# sourceMappingURL=chunk-UALX2J2Q.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":["statfs","diag","dirname","randomBytes","open","rename","unlink","mkdir"],"mappings":";;;;;;;AAUA,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,IAAAC,sBAAA;AAAA,MACE,CAAA,cAAA,EAAiB,KAAK,CAAA,uBAAA,EAA0B,MAAM,QAAQ,OAAO,CAAA;AAAA;AAAA,KAEvE;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAGR;AACF;AAiDA,SAAS,mBAAA,CAAoB,QAAA,EAAkB,GAAA,EAAa,MAAA,EAAwB;AAClF,EAAA,OAAO,GAAG,QAAQ,CAAA,CAAA,EAA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;AACf,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,CAAA;AAClC,EAAA,MAAM,eAAA,GAAkB,SAAS,eAAA,IAAmB,IAAA;AACpD,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAA,EAAM,MAAM,MAAM,CAAA;AAC9C,EAAA,IAAI,SAAS,MAAA,EAAW;AACtB,IAAA,MAAM,IAAI,UAAU,6CAA6C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,OAAA,GAAU,eAAA,GAAkB,CAAA,EAAG,IAAI;AAAA,CAAA,GAAO,IAAA;AAChD,EAAA,MAAMC,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AACpD;AASA,eAAsB,eAAA,CAAgB,UAAkB,OAAA,EAAgC;AACtF,EAAA,MAAMK,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-I6TGFUCO.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { diag } from \"../diagnostics.js\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n diag(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * M107 — temp-file creation control, shared by `replaceFileAtomic`,\n * `atomicWriteJson` e `atomicWriteText`.\n *\n * Both fields are OPTIONAL and the default is byte-identical to the behavior\n * before M107. See `replaceFileAtomic` for why the mode reassertion\n * is conditional.\n *\n */\nexport interface AtomicWriteFileOptions {\n /**\n * Permission bits of the created file. Default: `0o600`, the previous fixed\n * literal — filtered by the `umask`, as it always was. When provided, the mode is\n * reasserted on the descriptor, so the `umask` cannot silently\n * clearing bits the caller asked for.\n */\n mode?: number;\n /**\n * Create the temp file with `wx` (exclusive creation) instead of `w`. Default:\n * `false` — the previous flag. With `true`, a pre-existing temp file becomes\n * `EEXIST` instead of being truncated.\n */\n exclusive?: boolean;\n}\n\n/** The one place the temp-path format is written. `atomicWriteTempTarget` reverses it. */\nfunction atomicWriteTempPath(filePath: string, pid: number, suffix: string): string {\n return `${filePath}.${String(pid)}.${suffix}.tmp`;\n}\n\n/** Reverses {@link atomicWriteTempPath}: `<file>.<pid>.<hex>.tmp` → `<file>`. */\nconst TEMP_PATTERN = /^(.+)\\.\\d+\\.[0-9a-f]{16}\\.tmp$/;\n\n/**\n * U-9 — the file a leftover temp was replacing, or `undefined` if this is not one of ours.\n *\n * A crash between the open and the rename leaves `<file>.<pid>.<hex>.tmp` behind, and nothing here\n * collects it: this module creates temps and has no opinion about sweeping them. A consumer that\n * wants to has to know the format — which lived only in the implementation, so one copied it out of\n * a compiled chunk as a regex. That copy would have gone on reporting \"nothing to collect\" the day\n * the format changed, which is the quietest possible way for a cleanup to stop working.\n *\n * Deliberately strict: the pid must be digits and the suffix exactly 16 hex characters. Matching any\n * `.tmp` would claim editors' swap files and other tools' scratch, on a path whose purpose is\n * deleting them.\n */\nexport function atomicWriteTempTarget(name: string): string | undefined {\n return TEMP_PATTERN.exec(name)?.[1];\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `reference/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * ## M107 — `options` is optional, and the default is byte-identical\n *\n * The third parameter is additive: every earlier caller still compiles and\n * writing exactly the same bytes, with the same mode, to the same path.\n *\n * The mode reassertion (`handle.chmod`) is **conditional on `mode !== undefined`**,\n * and that is not cosmetic. `open`'s mode argument is filtered by the `umask`,\n * which only CLEARS bits — measured in this codebase before the change:\n *\n * ```\n * umask 0o002 -> 0o600 umask 0o022 -> 0o600 umask 0o200 -> 0o400\n * ```\n *\n * An unconditional `chmod` would take the third case from `0o400` to `0o600` — a\n * an on-disk change for every caller that asked for nothing, including external\n * consumers. When the caller DOES ask for a mode, however, letting the `umask` decide\n * silently is the defect this parameter exists to close; hence the reassertion.\n *\n * It goes on the DESCRIPTOR, before the `rename`, never after: chmod-ing the final\n * final one would leave a window where it carries the `umask`'s mode — a known anti-pattern.\n * The chosen shape passes the mode as an `open` argument.\n *\n */\nexport async function replaceFileAtomic(\n filePath: string,\n content: string,\n options?: AtomicWriteFileOptions,\n): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = atomicWriteTempPath(filePath, process.pid, suffix);\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, options?.exclusive === true ? \"wx\" : \"w\", options?.mode ?? 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n // Conditional by measurement, not by taste — see this function's docblock.\n if (options?.mode !== undefined) await handle.chmod(options.mode);\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n */\nexport interface AtomicWriteJsonOptions extends AtomicWriteFileOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content, options);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":["statfs","diag","dirname","randomBytes","open","rename","unlink","mkdir"],"mappings":";;;;;;;AAUA,IAAM,gBAAA,uBAAoD,GAAA,CAAI;AAAA,EAC5D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B,IAAA,MAAM,IAAI,UAAU,6CAA6C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,OAAA,GAAU,eAAA,GAAkB,CAAA,EAAG,IAAI;AAAA,CAAA,GAAO,IAAA;AAChD,EAAA,MAAMC,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AACpD;AASA,eAAsB,eAAA,CAAgB,UAAkB,OAAA,EAAgC;AACtF,EAAA,MAAMK,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-UALX2J2Q.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { diag } from \"../diagnostics.js\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n diag(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * M107 — temp-file creation control, shared by `replaceFileAtomic`,\n * `atomicWriteJson` e `atomicWriteText`.\n *\n * Both fields are OPTIONAL and the default is byte-identical to the behavior\n * before M107. See `replaceFileAtomic` for why the mode reassertion\n * is conditional.\n *\n */\nexport interface AtomicWriteFileOptions {\n /**\n * Permission bits of the created file. Default: `0o600`, the previous fixed\n * literal — filtered by the `umask`, as it always was. When provided, the mode is\n * reasserted on the descriptor, so the `umask` cannot silently\n * clearing bits the caller asked for.\n */\n mode?: number;\n /**\n * Create the temp file with `wx` (exclusive creation) instead of `w`. Default:\n * `false` — the previous flag. With `true`, a pre-existing temp file becomes\n * `EEXIST` instead of being truncated.\n */\n exclusive?: boolean;\n}\n\n/** The one place the temp-path format is written. `atomicWriteTempTarget` reverses it. */\nfunction atomicWriteTempPath(filePath: string, pid: number, suffix: string): string {\n return `${filePath}.${String(pid)}.${suffix}.tmp`;\n}\n\n/** Reverses {@link atomicWriteTempPath}: `<file>.<pid>.<hex>.tmp` → `<file>`. */\nconst TEMP_PATTERN = /^(.+)\\.\\d+\\.[0-9a-f]{16}\\.tmp$/;\n\n/**\n * U-9 — the file a leftover temp was replacing, or `undefined` if this is not one of ours.\n *\n * A crash between the open and the rename leaves `<file>.<pid>.<hex>.tmp` behind, and nothing here\n * collects it: this module creates temps and has no opinion about sweeping them. A consumer that\n * wants to has to know the format — which lived only in the implementation, so one copied it out of\n * a compiled chunk as a regex. That copy would have gone on reporting \"nothing to collect\" the day\n * the format changed, which is the quietest possible way for a cleanup to stop working.\n *\n * Deliberately strict: the pid must be digits and the suffix exactly 16 hex characters. Matching any\n * `.tmp` would claim editors' swap files and other tools' scratch, on a path whose purpose is\n * deleting them.\n */\nexport function atomicWriteTempTarget(name: string): string | undefined {\n return TEMP_PATTERN.exec(name)?.[1];\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `reference/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * ## M107 — `options` is optional, and the default is byte-identical\n *\n * The third parameter is additive: every earlier caller still compiles and\n * writing exactly the same bytes, with the same mode, to the same path.\n *\n * The mode reassertion (`handle.chmod`) is **conditional on `mode !== undefined`**,\n * and that is not cosmetic. `open`'s mode argument is filtered by the `umask`,\n * which only CLEARS bits — measured in this codebase before the change:\n *\n * ```\n * umask 0o002 -> 0o600 umask 0o022 -> 0o600 umask 0o200 -> 0o400\n * ```\n *\n * An unconditional `chmod` would take the third case from `0o400` to `0o600` — a\n * an on-disk change for every caller that asked for nothing, including external\n * consumers. When the caller DOES ask for a mode, however, letting the `umask` decide\n * silently is the defect this parameter exists to close; hence the reassertion.\n *\n * It goes on the DESCRIPTOR, before the `rename`, never after: chmod-ing the final\n * final one would leave a window where it carries the `umask`'s mode — a known anti-pattern.\n * The chosen shape passes the mode as an `open` argument.\n *\n */\nexport async function replaceFileAtomic(\n filePath: string,\n content: string,\n options?: AtomicWriteFileOptions,\n): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = atomicWriteTempPath(filePath, process.pid, suffix);\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, options?.exclusive === true ? \"wx\" : \"w\", options?.mode ?? 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n // Conditional by measurement, not by taste — see this function's docblock.\n if (options?.mode !== undefined) await handle.chmod(options.mode);\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n */\nexport interface AtomicWriteJsonOptions extends AtomicWriteFileOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content, options);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { globalEmbeddingCache } from './chunk-H73MEMQB.js';
2
- import { mapOpenAICompatibleError } from './chunk-5JLFFPCH.js';
3
- import { mapWithConcurrency } from './chunk-UC3HT2S4.js';
4
- import { AuthenticationError, ConfigurationError, NetworkError } from './chunk-IDCKSLYH.js';
2
+ import { mapOpenAICompatibleError } from './chunk-7YGCPMGB.js';
3
+ import { mapWithConcurrency } from './chunk-C72AZW7J.js';
4
+ import { AuthenticationError, ConfigurationError, NetworkError } from './chunk-ZZMZWBR6.js';
5
5
  import { createHash } from 'crypto';
6
6
 
7
7
  var MAX_BATCH = 100;
@@ -193,5 +193,5 @@ function sleep(ms) {
193
193
  }
194
194
 
195
195
  export { createOpenAiCompatibleRuntime };
196
- //# sourceMappingURL=chunk-XN7NOENA.js.map
197
- //# sourceMappingURL=chunk-XN7NOENA.js.map
196
+ //# sourceMappingURL=chunk-UBDMVMBZ.js.map
197
+ //# sourceMappingURL=chunk-UBDMVMBZ.js.map