@theokit/sdk 4.24.0 → 4.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (382) hide show
  1. package/dist/a2a/index.cjs +10 -171
  2. package/dist/a2a/index.cjs.map +1 -1
  3. package/dist/a2a/index.js +3 -170
  4. package/dist/a2a/index.js.map +1 -1
  5. package/dist/agent-factory-registry-UU46BUMU.cjs +16 -0
  6. package/dist/agent-factory-registry-UU46BUMU.cjs.map +1 -0
  7. package/dist/agent-factory-registry-ZVTABLEY.js +3 -0
  8. package/dist/agent-factory-registry-ZVTABLEY.js.map +1 -0
  9. package/dist/auth/index.cjs +63 -367
  10. package/dist/auth/index.cjs.map +1 -1
  11. package/dist/auth/index.js +6 -342
  12. package/dist/auth/index.js.map +1 -1
  13. package/dist/batch-2FSD2UNL.cjs +244 -0
  14. package/dist/batch-2FSD2UNL.cjs.map +1 -0
  15. package/dist/batch-MR2HKYMS.js +241 -0
  16. package/dist/batch-MR2HKYMS.js.map +1 -0
  17. package/dist/chunk-2HRYBRD7.cjs +31 -0
  18. package/dist/chunk-2HRYBRD7.cjs.map +1 -0
  19. package/dist/chunk-2MF3IE2D.cjs +2863 -0
  20. package/dist/chunk-2MF3IE2D.cjs.map +1 -0
  21. package/dist/chunk-2ONFGMBV.js +6 -0
  22. package/dist/chunk-2ONFGMBV.js.map +1 -0
  23. package/dist/chunk-2SFBB54R.js +23 -0
  24. package/dist/chunk-2SFBB54R.js.map +1 -0
  25. package/dist/chunk-2XLKLVVR.js +18 -0
  26. package/dist/chunk-2XLKLVVR.js.map +1 -0
  27. package/dist/chunk-4SXHEZIV.cjs +240 -0
  28. package/dist/chunk-4SXHEZIV.cjs.map +1 -0
  29. package/dist/chunk-4VPXM6UU.js +10 -0
  30. package/dist/chunk-4VPXM6UU.js.map +1 -0
  31. package/dist/chunk-4WL52CXU.cjs +148 -0
  32. package/dist/chunk-4WL52CXU.cjs.map +1 -0
  33. package/dist/chunk-5NBUH3NO.js +39 -0
  34. package/dist/chunk-5NBUH3NO.js.map +1 -0
  35. package/dist/chunk-5PZMMF4H.js +43 -0
  36. package/dist/chunk-5PZMMF4H.js.map +1 -0
  37. package/dist/chunk-6CLRANZA.js +289 -0
  38. package/dist/chunk-6CLRANZA.js.map +1 -0
  39. package/dist/chunk-6JSIEDKL.cjs +121 -0
  40. package/dist/chunk-6JSIEDKL.cjs.map +1 -0
  41. package/dist/chunk-6M4ODB2V.cjs +145 -0
  42. package/dist/chunk-6M4ODB2V.cjs.map +1 -0
  43. package/dist/chunk-6X6ID4MO.js +20 -0
  44. package/dist/chunk-6X6ID4MO.js.map +1 -0
  45. package/dist/chunk-77FOZCOT.js +165 -0
  46. package/dist/chunk-77FOZCOT.js.map +1 -0
  47. package/dist/chunk-7AD3ZTZL.js +25 -0
  48. package/dist/chunk-7AD3ZTZL.js.map +1 -0
  49. package/dist/chunk-7GFX45DD.js +57 -0
  50. package/dist/chunk-7GFX45DD.js.map +1 -0
  51. package/dist/chunk-7S7KKUO6.cjs +45 -0
  52. package/dist/chunk-7S7KKUO6.cjs.map +1 -0
  53. package/dist/chunk-7W7ZWMLQ.js +99 -0
  54. package/dist/chunk-7W7ZWMLQ.js.map +1 -0
  55. package/dist/chunk-A44COQJJ.cjs +353 -0
  56. package/dist/chunk-A44COQJJ.cjs.map +1 -0
  57. package/dist/chunk-AKSBP7OO.js +185 -0
  58. package/dist/chunk-AKSBP7OO.js.map +1 -0
  59. package/dist/chunk-ANIZEWTU.cjs +196 -0
  60. package/dist/chunk-ANIZEWTU.cjs.map +1 -0
  61. package/dist/chunk-BEURCLDV.cjs +139 -0
  62. package/dist/chunk-BEURCLDV.cjs.map +1 -0
  63. package/dist/chunk-BFWPZMG7.js +379 -0
  64. package/dist/chunk-BFWPZMG7.js.map +1 -0
  65. package/dist/chunk-BUUUWQMB.cjs +34 -0
  66. package/dist/chunk-BUUUWQMB.cjs.map +1 -0
  67. package/dist/chunk-BV2MWEMV.cjs +26 -0
  68. package/dist/chunk-BV2MWEMV.cjs.map +1 -0
  69. package/dist/chunk-BWT67BI4.cjs +268 -0
  70. package/dist/chunk-BWT67BI4.cjs.map +1 -0
  71. package/dist/chunk-BXV2QUIC.js +191 -0
  72. package/dist/chunk-BXV2QUIC.js.map +1 -0
  73. package/dist/chunk-C6Y6CWYD.cjs +44 -0
  74. package/dist/chunk-C6Y6CWYD.cjs.map +1 -0
  75. package/dist/chunk-C7PICHRF.cjs +68 -0
  76. package/dist/chunk-C7PICHRF.cjs.map +1 -0
  77. package/dist/chunk-CAH3G4IS.js +13 -0
  78. package/dist/chunk-CAH3G4IS.js.map +1 -0
  79. package/dist/chunk-D42XHI4O.cjs +565 -0
  80. package/dist/chunk-D42XHI4O.cjs.map +1 -0
  81. package/dist/chunk-DGRZNMTU.js +104 -0
  82. package/dist/chunk-DGRZNMTU.js.map +1 -0
  83. package/dist/chunk-DUK5WMKJ.js +71 -0
  84. package/dist/chunk-DUK5WMKJ.js.map +1 -0
  85. package/dist/chunk-EEZ7CFMM.js +14 -0
  86. package/dist/chunk-EEZ7CFMM.js.map +1 -0
  87. package/dist/chunk-EPYZOCOL.cjs +82 -0
  88. package/dist/chunk-EPYZOCOL.cjs.map +1 -0
  89. package/dist/chunk-EVADEGM7.cjs +168 -0
  90. package/dist/chunk-EVADEGM7.cjs.map +1 -0
  91. package/dist/chunk-FD2UT76F.js +3 -0
  92. package/dist/chunk-FD2UT76F.js.map +1 -0
  93. package/dist/chunk-FV3YEMQ7.js +179 -0
  94. package/dist/chunk-FV3YEMQ7.js.map +1 -0
  95. package/dist/chunk-G2F67XUR.cjs +184 -0
  96. package/dist/chunk-G2F67XUR.cjs.map +1 -0
  97. package/dist/chunk-G6GO6BXD.js +994 -0
  98. package/dist/chunk-G6GO6BXD.js.map +1 -0
  99. package/dist/chunk-GIW4L6HY.cjs +27 -0
  100. package/dist/chunk-GIW4L6HY.cjs.map +1 -0
  101. package/dist/chunk-GJAGKFTR.js +74 -0
  102. package/dist/chunk-GJAGKFTR.js.map +1 -0
  103. package/dist/chunk-HFPGOTVF.cjs +324 -0
  104. package/dist/chunk-HFPGOTVF.cjs.map +1 -0
  105. package/dist/chunk-HRA3CPGG.js +486 -0
  106. package/dist/chunk-HRA3CPGG.js.map +1 -0
  107. package/dist/chunk-HZQEDNF6.js +66 -0
  108. package/dist/chunk-HZQEDNF6.js.map +1 -0
  109. package/dist/chunk-IT3PWBW4.cjs +19 -0
  110. package/dist/chunk-IT3PWBW4.cjs.map +1 -0
  111. package/dist/chunk-JD74LN7R.cjs +171 -0
  112. package/dist/chunk-JD74LN7R.cjs.map +1 -0
  113. package/dist/chunk-JTFYYKDT.js +135 -0
  114. package/dist/chunk-JTFYYKDT.js.map +1 -0
  115. package/dist/chunk-K2BQQ445.js +30 -0
  116. package/dist/chunk-K2BQQ445.js.map +1 -0
  117. package/dist/chunk-KAP4GJHO.js +546 -0
  118. package/dist/chunk-KAP4GJHO.js.map +1 -0
  119. package/dist/chunk-KDNBTPY2.js +458 -0
  120. package/dist/chunk-KDNBTPY2.js.map +1 -0
  121. package/dist/chunk-KIO7QFIV.cjs +223 -0
  122. package/dist/chunk-KIO7QFIV.cjs.map +1 -0
  123. package/dist/chunk-KSKU6JY6.cjs +71 -0
  124. package/dist/chunk-KSKU6JY6.cjs.map +1 -0
  125. package/dist/chunk-LSLPF6OI.cjs +192 -0
  126. package/dist/chunk-LSLPF6OI.cjs.map +1 -0
  127. package/dist/chunk-LU7VALW5.js +312 -0
  128. package/dist/chunk-LU7VALW5.js.map +1 -0
  129. package/dist/chunk-LUSXDZPV.cjs +296 -0
  130. package/dist/chunk-LUSXDZPV.cjs.map +1 -0
  131. package/dist/chunk-M72RJVPC.js +69 -0
  132. package/dist/chunk-M72RJVPC.js.map +1 -0
  133. package/dist/chunk-MQLCZ4HJ.cjs +1010 -0
  134. package/dist/chunk-MQLCZ4HJ.cjs.map +1 -0
  135. package/dist/chunk-MUUQ2WFJ.cjs +4 -0
  136. package/dist/chunk-MUUQ2WFJ.cjs.map +1 -0
  137. package/dist/chunk-MZ5ZRORA.cjs +496 -0
  138. package/dist/chunk-MZ5ZRORA.cjs.map +1 -0
  139. package/dist/chunk-N24XBYNX.cjs +140 -0
  140. package/dist/chunk-N24XBYNX.cjs.map +1 -0
  141. package/dist/chunk-NINIJCHU.cjs +23 -0
  142. package/dist/chunk-NINIJCHU.cjs.map +1 -0
  143. package/dist/chunk-NRSH7RJY.js +2841 -0
  144. package/dist/chunk-NRSH7RJY.js.map +1 -0
  145. package/dist/chunk-OIYQBUW4.cjs +111 -0
  146. package/dist/chunk-OIYQBUW4.cjs.map +1 -0
  147. package/dist/chunk-PNVDQL5Y.cjs +15 -0
  148. package/dist/chunk-PNVDQL5Y.cjs.map +1 -0
  149. package/dist/chunk-POQT2OIF.js +214 -0
  150. package/dist/chunk-POQT2OIF.js.map +1 -0
  151. package/dist/chunk-PSJN532Q.js +10573 -0
  152. package/dist/chunk-PSJN532Q.js.map +1 -0
  153. package/dist/chunk-QUTUJ6P6.cjs +76 -0
  154. package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
  155. package/dist/chunk-R43CNCES.cjs +460 -0
  156. package/dist/chunk-R43CNCES.cjs.map +1 -0
  157. package/dist/chunk-S2BBRVQX.js +68 -0
  158. package/dist/chunk-S2BBRVQX.js.map +1 -0
  159. package/dist/chunk-S5RCBTSF.js +145 -0
  160. package/dist/chunk-S5RCBTSF.js.map +1 -0
  161. package/dist/chunk-S7OEXQMI.cjs +136 -0
  162. package/dist/chunk-S7OEXQMI.cjs.map +1 -0
  163. package/dist/chunk-SKWVAQAY.js +129 -0
  164. package/dist/chunk-SKWVAQAY.js.map +1 -0
  165. package/dist/chunk-SQLZ7ONU.js +152 -0
  166. package/dist/chunk-SQLZ7ONU.js.map +1 -0
  167. package/dist/chunk-TIZ4TS5V.cjs +72 -0
  168. package/dist/chunk-TIZ4TS5V.cjs.map +1 -0
  169. package/dist/chunk-TQKCU7CL.js +142 -0
  170. package/dist/chunk-TQKCU7CL.js.map +1 -0
  171. package/dist/chunk-U54XCYG3.js +116 -0
  172. package/dist/chunk-U54XCYG3.js.map +1 -0
  173. package/dist/chunk-U6QGZHPN.js +29 -0
  174. package/dist/chunk-U6QGZHPN.js.map +1 -0
  175. package/dist/chunk-UCFONJBG.js +79 -0
  176. package/dist/chunk-UCFONJBG.js.map +1 -0
  177. package/dist/chunk-UJ7IQJAG.js +141 -0
  178. package/dist/chunk-UJ7IQJAG.js.map +1 -0
  179. package/dist/chunk-UVNG67DG.js +253 -0
  180. package/dist/chunk-UVNG67DG.js.map +1 -0
  181. package/dist/chunk-V4XRLPEF.js +25 -0
  182. package/dist/chunk-V4XRLPEF.js.map +1 -0
  183. package/dist/chunk-VJ26EKGJ.cjs +28 -0
  184. package/dist/chunk-VJ26EKGJ.cjs.map +1 -0
  185. package/dist/chunk-VK7MAV65.cjs +90 -0
  186. package/dist/chunk-VK7MAV65.cjs.map +1 -0
  187. package/dist/chunk-VYCKUKPA.cjs +106 -0
  188. package/dist/chunk-VYCKUKPA.cjs.map +1 -0
  189. package/dist/chunk-VYHJZVL5.cjs +29 -0
  190. package/dist/chunk-VYHJZVL5.cjs.map +1 -0
  191. package/dist/chunk-WA3FO4R7.js +155 -0
  192. package/dist/chunk-WA3FO4R7.js.map +1 -0
  193. package/dist/chunk-WJVHMTKB.cjs +12 -0
  194. package/dist/chunk-WJVHMTKB.cjs.map +1 -0
  195. package/dist/chunk-WLKFWQSJ.js +333 -0
  196. package/dist/chunk-WLKFWQSJ.js.map +1 -0
  197. package/dist/chunk-WPZTYOUX.cjs +59 -0
  198. package/dist/chunk-WPZTYOUX.cjs.map +1 -0
  199. package/dist/chunk-X2FR4OIT.js +27 -0
  200. package/dist/chunk-X2FR4OIT.js.map +1 -0
  201. package/dist/chunk-XIG2IE3L.js +134 -0
  202. package/dist/chunk-XIG2IE3L.js.map +1 -0
  203. package/dist/chunk-YLQQX5W2.cjs +20 -0
  204. package/dist/chunk-YLQQX5W2.cjs.map +1 -0
  205. package/dist/chunk-YPEPCZHF.cjs +147 -0
  206. package/dist/chunk-YPEPCZHF.cjs.map +1 -0
  207. package/dist/chunk-YPQF26X7.cjs +8 -0
  208. package/dist/chunk-YPQF26X7.cjs.map +1 -0
  209. package/dist/chunk-YU6KON2I.cjs +160 -0
  210. package/dist/chunk-YU6KON2I.cjs.map +1 -0
  211. package/dist/chunk-Z2OC3UIW.cjs +388 -0
  212. package/dist/chunk-Z2OC3UIW.cjs.map +1 -0
  213. package/dist/chunk-ZUBIEQJF.cjs +10590 -0
  214. package/dist/chunk-ZUBIEQJF.cjs.map +1 -0
  215. package/dist/chunk-ZZWTY3RX.js +230 -0
  216. package/dist/chunk-ZZWTY3RX.js.map +1 -0
  217. package/dist/compact-session-OO2GD76G.js +17 -0
  218. package/dist/compact-session-OO2GD76G.js.map +1 -0
  219. package/dist/compact-session-OO7NVWPB.cjs +54 -0
  220. package/dist/compact-session-OO7NVWPB.cjs.map +1 -0
  221. package/dist/compaction.cjs +54 -303
  222. package/dist/compaction.cjs.map +1 -1
  223. package/dist/compaction.js +3 -292
  224. package/dist/compaction.js.map +1 -1
  225. package/dist/concurrency.cjs +9 -81
  226. package/dist/concurrency.cjs.map +1 -1
  227. package/dist/concurrency.js +5 -80
  228. package/dist/concurrency.js.map +1 -1
  229. package/dist/context-GWANQLX4.js +5 -0
  230. package/dist/context-GWANQLX4.js.map +1 -0
  231. package/dist/context-KNWVTZSY.cjs +22 -0
  232. package/dist/context-KNWVTZSY.cjs.map +1 -0
  233. package/dist/{cron-x3muPNgg.d.cts → cron-D0JKR-yX.d.cts} +2 -1
  234. package/dist/{cron-B_NkE_VM.d.ts → cron-DivRaEmN.d.ts} +2 -1
  235. package/dist/cron.cjs +44 -20676
  236. package/dist/cron.cjs.map +1 -1
  237. package/dist/cron.d.cts +1 -1
  238. package/dist/cron.d.ts +1 -1
  239. package/dist/cron.js +38 -20676
  240. package/dist/cron.js.map +1 -1
  241. package/dist/errors.cjs +78 -470
  242. package/dist/errors.cjs.map +1 -1
  243. package/dist/errors.d.ts +3 -424
  244. package/dist/errors.js +2 -455
  245. package/dist/errors.js.map +1 -1
  246. package/dist/eval.cjs +72 -20411
  247. package/dist/eval.cjs.map +1 -1
  248. package/dist/eval.js +59 -20402
  249. package/dist/eval.js.map +1 -1
  250. package/dist/executor-ORJS5GV2.js +981 -0
  251. package/dist/executor-ORJS5GV2.js.map +1 -0
  252. package/dist/executor-Y4MKPIUD.cjs +985 -0
  253. package/dist/executor-Y4MKPIUD.cjs.map +1 -0
  254. package/dist/filesystem/index.cjs +7 -112
  255. package/dist/filesystem/index.cjs.map +1 -1
  256. package/dist/filesystem/index.js +4 -109
  257. package/dist/filesystem/index.js.map +1 -1
  258. package/dist/fork-agent-RSV4E3EA.js +61 -0
  259. package/dist/fork-agent-RSV4E3EA.js.map +1 -0
  260. package/dist/fork-agent-Y2IK2RYU.cjs +64 -0
  261. package/dist/fork-agent-Y2IK2RYU.cjs.map +1 -0
  262. package/dist/fs-session-store-KAUQYSGI.cjs +17 -0
  263. package/dist/fs-session-store-KAUQYSGI.cjs.map +1 -0
  264. package/dist/fs-session-store-ZKB5NN37.js +8 -0
  265. package/dist/fs-session-store-ZKB5NN37.js.map +1 -0
  266. package/dist/generate-object-H3RNAM6S.cjs +20 -0
  267. package/dist/generate-object-H3RNAM6S.cjs.map +1 -0
  268. package/dist/generate-object-YJPDV5BS.js +7 -0
  269. package/dist/generate-object-YJPDV5BS.js.map +1 -0
  270. package/dist/index-manager-CB6I7XFQ.cjs +19 -0
  271. package/dist/index-manager-CB6I7XFQ.cjs.map +1 -0
  272. package/dist/index-manager-L27Q3QAC.js +10 -0
  273. package/dist/index-manager-L27Q3QAC.js.map +1 -0
  274. package/dist/index.cjs +371 -22888
  275. package/dist/index.cjs.map +1 -1
  276. package/dist/index.d.cts +16 -21
  277. package/dist/index.d.ts +16 -21
  278. package/dist/index.js +92 -22713
  279. package/dist/index.js.map +1 -1
  280. package/dist/inject-session-6MJUSGZP.cjs +27 -0
  281. package/dist/inject-session-6MJUSGZP.cjs.map +1 -0
  282. package/dist/inject-session-KOFHS5K3.js +25 -0
  283. package/dist/inject-session-KOFHS5K3.js.map +1 -0
  284. package/dist/internal/judge/judge-call.d.ts +32 -19
  285. package/dist/internal/persistence/index.cjs +93 -508
  286. package/dist/internal/persistence/index.cjs.map +1 -1
  287. package/dist/internal/persistence/index.js +11 -489
  288. package/dist/internal/persistence/index.js.map +1 -1
  289. package/dist/internal/security/index.cjs +44 -361
  290. package/dist/internal/security/index.cjs.map +1 -1
  291. package/dist/internal/security/index.js +4 -355
  292. package/dist/internal/security/index.js.map +1 -1
  293. package/dist/judge-call-CEQ3FYYD.js +126 -0
  294. package/dist/judge-call-CEQ3FYYD.js.map +1 -0
  295. package/dist/judge-call-QG4WZ7F3.cjs +130 -0
  296. package/dist/judge-call-QG4WZ7F3.cjs.map +1 -0
  297. package/dist/models.cjs +24 -919
  298. package/dist/models.cjs.map +1 -1
  299. package/dist/models.js +11 -907
  300. package/dist/models.js.map +1 -1
  301. package/dist/oauth-transaction-store-7CKHPQRN.cjs +32 -0
  302. package/dist/oauth-transaction-store-7CKHPQRN.cjs.map +1 -0
  303. package/dist/oauth-transaction-store-W74I6EFD.js +3 -0
  304. package/dist/oauth-transaction-store-W74I6EFD.js.map +1 -0
  305. package/dist/path-safety.cjs +31 -200
  306. package/dist/path-safety.cjs.map +1 -1
  307. package/dist/path-safety.js +3 -197
  308. package/dist/path-safety.js.map +1 -1
  309. package/dist/persistence.cjs +73 -393
  310. package/dist/persistence.cjs.map +1 -1
  311. package/dist/persistence.js +9 -381
  312. package/dist/persistence.js.map +1 -1
  313. package/dist/project.cjs +8 -112
  314. package/dist/project.cjs.map +1 -1
  315. package/dist/project.js +6 -110
  316. package/dist/project.js.map +1 -1
  317. package/dist/registry-34IWWDQQ.js +9 -0
  318. package/dist/registry-34IWWDQQ.js.map +1 -0
  319. package/dist/registry-APYDISL6.cjs +46 -0
  320. package/dist/registry-APYDISL6.cjs.map +1 -0
  321. package/dist/retry.cjs +7 -87
  322. package/dist/retry.cjs.map +1 -1
  323. package/dist/retry.js +3 -90
  324. package/dist/retry.js.map +1 -1
  325. package/dist/run-to-completion-J73I6IY4.cjs +48 -0
  326. package/dist/run-to-completion-J73I6IY4.cjs.map +1 -0
  327. package/dist/run-to-completion-JDPIUKSH.js +3 -0
  328. package/dist/run-to-completion-JDPIUKSH.js.map +1 -0
  329. package/dist/run-until-PNO3QQLI.cjs +180 -0
  330. package/dist/run-until-PNO3QQLI.cjs.map +1 -0
  331. package/dist/run-until-XLHEHRQM.js +177 -0
  332. package/dist/run-until-XLHEHRQM.js.map +1 -0
  333. package/dist/sandbox/index.cjs +35 -337
  334. package/dist/sandbox/index.cjs.map +1 -1
  335. package/dist/sandbox/index.js +7 -323
  336. package/dist/sandbox/index.js.map +1 -1
  337. package/dist/sanitize/index.cjs +5 -112
  338. package/dist/sanitize/index.cjs.map +1 -1
  339. package/dist/sanitize/index.js +1 -114
  340. package/dist/sanitize/index.js.map +1 -1
  341. package/dist/server/auth/index.cjs +35 -175
  342. package/dist/server/auth/index.cjs.map +1 -1
  343. package/dist/server/auth/index.js +7 -161
  344. package/dist/server/auth/index.js.map +1 -1
  345. package/dist/server/errors-envelope.cjs +17 -328
  346. package/dist/server/errors-envelope.cjs.map +1 -1
  347. package/dist/server/errors-envelope.js +4 -317
  348. package/dist/server/errors-envelope.js.map +1 -1
  349. package/dist/session-transcript-LPNZR3YS.cjs +46 -0
  350. package/dist/session-transcript-LPNZR3YS.cjs.map +1 -0
  351. package/dist/session-transcript-T7LGJUGW.js +5 -0
  352. package/dist/session-transcript-T7LGJUGW.js.map +1 -0
  353. package/dist/skills.cjs +12 -280
  354. package/dist/skills.cjs.map +1 -1
  355. package/dist/skills.js +4 -282
  356. package/dist/skills.js.map +1 -1
  357. package/dist/stream-object-QEQJJDTI.cjs +20 -0
  358. package/dist/stream-object-QEQJJDTI.cjs.map +1 -0
  359. package/dist/stream-object-WUQSSRY2.js +7 -0
  360. package/dist/stream-object-WUQSSRY2.js.map +1 -0
  361. package/dist/stream-to-completion-DFJ5T3BK.js +30 -0
  362. package/dist/stream-to-completion-DFJ5T3BK.js.map +1 -0
  363. package/dist/stream-to-completion-H2MHISSK.cjs +32 -0
  364. package/dist/stream-to-completion-H2MHISSK.cjs.map +1 -0
  365. package/dist/subagents.cjs +2 -8
  366. package/dist/subagents.cjs.map +1 -1
  367. package/dist/subagents.js +1 -7
  368. package/dist/subagents.js.map +1 -1
  369. package/dist/subscription/index.cjs +4 -17
  370. package/dist/subscription/index.cjs.map +1 -1
  371. package/dist/subscription/index.js +3 -16
  372. package/dist/subscription/index.js.map +1 -1
  373. package/dist/task-store.cjs +16 -258
  374. package/dist/task-store.cjs.map +1 -1
  375. package/dist/task-store.js +4 -259
  376. package/dist/task-store.js.map +1 -1
  377. package/dist/types/goal-events.d.ts +2 -1
  378. package/dist/workflow.cjs +71 -2797
  379. package/dist/workflow.cjs.map +1 -1
  380. package/dist/workflow.js +8 -2812
  381. package/dist/workflow.js.map +1 -1
  382. package/package.json +1 -1
package/dist/workflow.cjs CHANGED
@@ -1,2825 +1,99 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
- var promises = require('fs/promises');
5
- var path = require('path');
6
- var module$1 = require('module');
7
- var fs = require('fs');
8
- var async_hooks = require('async_hooks');
9
- var zod = require('zod');
3
+ var chunkZ2OC3UIW_cjs = require('./chunk-Z2OC3UIW.cjs');
4
+ var chunkBWT67BI4_cjs = require('./chunk-BWT67BI4.cjs');
5
+ require('./chunk-PNVDQL5Y.cjs');
6
+ require('./chunk-WJVHMTKB.cjs');
7
+ require('./chunk-KIO7QFIV.cjs');
8
+ require('./chunk-TIZ4TS5V.cjs');
9
+ require('./chunk-A44COQJJ.cjs');
10
+ require('./chunk-BEURCLDV.cjs');
10
11
 
11
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
- var __defProp = Object.defineProperty;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __esm = (fn2, res) => function __init() {
15
- return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res;
16
- };
17
- var __export = (target, all) => {
18
- for (var name in all)
19
- __defProp(target, name, { get: all[name], enumerable: true });
20
- };
21
12
 
22
- // src/internal/security/redact.ts
23
- function readEnvOnce() {
24
- const raw = process.env.THEOKIT_REDACT_SECRETS;
25
- if (raw === void 0) return true;
26
- return ["1", "true", "yes", "on"].includes(raw.toLowerCase());
27
- }
28
- function maskToken(token) {
29
- if (token.length < 18) return "***";
30
- return `${token.slice(0, 6)}...${token.slice(-4)}`;
31
- }
32
- function coerceToString(value) {
33
- if (typeof value === "string") return value;
34
- if (value === null || value === void 0) return null;
35
- if (typeof value === "object") {
36
- try {
37
- const s = JSON.stringify(value);
38
- return s === void 0 ? null : s;
39
- } catch {
40
- return "[unredactable: circular]";
41
- }
42
- }
43
- return String(value);
44
- }
45
- function redactSecrets(text, opts) {
46
- const coerced = coerceToString(text);
47
- if (coerced === null) return "";
48
- if (!REDACT_ENABLED) return coerced;
49
- let s = coerced;
50
- for (const re of BUILTIN_PATTERNS) {
51
- s = s.replace(re, (m) => maskToken(m));
52
- }
53
- for (const re of _extraPatterns) {
54
- s = s.replace(re, (m) => maskToken(m));
55
- }
56
- {
57
- s = s.replace(BEARER_PATTERN, (_, prefix) => `${prefix}***`);
58
- s = s.replace(PARAM_PATTERN, (whole, prefix, value) => {
59
- if (MASK_SHAPE.test(value)) return whole;
60
- return `${prefix}***`;
61
- });
62
- }
63
- return s;
64
- }
65
- var REDACT_ENABLED, warnedOptOut, BUILTIN_PATTERNS, BEARER_PATTERN, PARAM_PATTERN, _extraPatterns, MASK_SHAPE;
66
- var init_redact = __esm({
67
- "src/internal/security/redact.ts"() {
68
- REDACT_ENABLED = readEnvOnce();
69
- warnedOptOut = false;
70
- if (!REDACT_ENABLED && !warnedOptOut) {
71
- process.stderr.write(
72
- "[theokit-sdk] Secret redaction is DISABLED via THEOKIT_REDACT_SECRETS. Credentials may leak into errors, telemetry, logs, transcripts.\n"
73
- );
74
- warnedOptOut = true;
75
- }
76
- BUILTIN_PATTERNS = [
77
- // T5.4: 30+ vendor prefixes (was 12 pre-T5.4). Order matters — more
78
- // specific prefixes precede generic ones (e.g., sk-ant-admin01 before
79
- // sk-ant-, sk-proj- before sk-). PEM block deliberately first so its
80
- // multi-line span runs before any per-line patterns can fire.
81
- /-----BEGIN[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----[\s\S]+?-----END[ ]+(?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----/g,
82
- // JWT — exact 3-segment base64url. Dotted; the body floor of 4 chars per
83
- // segment matches the minimum legal payload while skipping `a.b.c` noise.
84
- /eyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g,
85
- // Azure Storage SAS — match the sig= component (URL-encoded base64).
86
- /(?<=[?&]sig=)[A-Za-z0-9%+/]{20,}/g,
87
- // Anthropic
88
- /sk-ant-admin01-[A-Za-z0-9_-]{10,}/g,
89
- // Anthropic admin keys (must precede sk-ant-)
90
- /sk-ant-[A-Za-z0-9_-]{10,}/g,
91
- // Anthropic regular
92
- // OpenAI family + clones (sk- generic must come AFTER all sk-foo- variants)
93
- /sk-proj-[A-Za-z0-9_-]{10,}/g,
94
- // OpenAI project key (must precede sk- generic)
95
- /sk-[A-Za-z0-9_-]{10,}/g,
96
- // OpenAI / OpenRouter / DeepInfra / Together / DeepSeek
97
- // Provider prefixes (alphabetized for maintainability)
98
- /AIza[A-Za-z0-9_-]{35}/g,
99
- // Google API key
100
- /AKIA[A-Z0-9]{16}/g,
101
- // AWS access key
102
- /fw_[A-Za-z0-9]{20,}/g,
103
- // Fireworks
104
- /glpat-[A-Za-z0-9_-]{20}/g,
105
- // GitLab PAT
106
- /ghp_[A-Za-z0-9]{36}/g,
107
- // GitHub PAT classic
108
- /github_pat_[A-Za-z0-9_]{82}/g,
109
- // GitHub PAT fine-grained
110
- /gsk_[A-Za-z0-9]{20,}/g,
111
- // Groq
112
- /hf_[A-Za-z0-9]{20,}/g,
113
- // HuggingFace
114
- /\bpa-[A-Za-z0-9_-]{20,}/g,
115
- // Voyage AI (word-boundary to skip CSS / kebab IDs)
116
- /pcsk_[A-Za-z0-9_-]{20,}/g,
117
- // Pinecone
118
- /pplx-[A-Za-z0-9_-]{20,}/g,
119
- // Perplexity
120
- /r8_[A-Za-z0-9_-]{20,}/g,
121
- // Replicate
122
- /rk_live_[A-Za-z0-9]{20,}/g,
123
- // Stripe restricted
124
- /sk_live_[A-Za-z0-9]{20,}/g,
125
- // Stripe secret
126
- /sntrys_[A-Za-z0-9]{40,}/g,
127
- // Sentry user auth
128
- /xai-[A-Za-z0-9_-]{20,}/g,
129
- // xAI (Grok)
130
- /xox[bpasr]-[A-Za-z0-9-]{10,}/g,
131
- //Slack tokens
132
- // Additional unique-prefix tokens with low false-positive risk
133
- /npm_[A-Za-z0-9]{36}/g,
134
- // npm access token
135
- /SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,
136
- // SendGrid
137
- /\bSK[A-Za-z0-9]{32}\b/g,
138
- // Twilio API SID (word-boundary to skip CSS class noise)
139
- /\bkey-[a-f0-9]{32}\b/g,
140
- // Mailgun (hex-only narrows false positives)
141
- /MT[A-Za-z0-9_-]{23}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27}/g,
142
- // Discord bot
143
- /\b(?:sdk|mob)-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\b/g
144
- // LaunchDarkly
145
- ];
146
- BEARER_PATTERN = /\b(Bearer\s+)([A-Za-z0-9_\-.+/=]{8,})/g;
147
- PARAM_PATTERN = /(\b(?:access_token|api_key|api-key|client_secret|credential|credentials|id_token|jwt|password|private_key|refresh_token|secret|service_account|session_token|token|x-api-key)\b["']?\s*[:=]\s*["']?)([A-Za-z0-9_\-.+/]+)/gi;
148
- _extraPatterns = [];
149
- MASK_SHAPE = /^.{6}\.\.\..{4}$/s;
150
- }
151
- });
152
13
 
153
- // src/errors.ts
154
- var TheokitAgentError, ConfigurationError, UnsupportedRunOperationError, InvalidTaskIdError, TaskNotFoundError;
155
- var init_errors = __esm({
156
- "src/errors.ts"() {
157
- TheokitAgentError = class extends Error {
158
- name = "TheokitAgentError";
159
- isRetryable;
160
- code;
161
- protoErrorCode;
162
- metadata;
163
- constructor(message, options = {}) {
164
- super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
165
- this.isRetryable = options.isRetryable ?? false;
166
- if (options.code !== void 0) this.code = options.code;
167
- if (options.protoErrorCode !== void 0) this.protoErrorCode = options.protoErrorCode;
168
- if (options.metadata !== void 0) this.metadata = options.metadata;
169
- }
170
- };
171
- ConfigurationError = class extends TheokitAgentError {
172
- name = "ConfigurationError";
173
- constructor(message, options = {}) {
174
- super(message, { ...options, isRetryable: false });
175
- }
176
- };
177
- UnsupportedRunOperationError = class extends TheokitAgentError {
178
- name = "UnsupportedRunOperationError";
179
- operation;
180
- constructor(message, operation, options = {}) {
181
- super(message, {
182
- ...options,
183
- isRetryable: false,
184
- code: options.code ?? "unsupported_run_operation"
185
- });
186
- this.operation = operation;
187
- }
188
- };
189
- InvalidTaskIdError = class extends TheokitAgentError {
190
- name = "InvalidTaskIdError";
191
- taskId;
192
- constructor(message, taskId, options = {}) {
193
- super(message, {
194
- ...options,
195
- isRetryable: false,
196
- code: "invalid_task_id"
197
- });
198
- this.taskId = taskId;
199
- }
200
- };
201
- TaskNotFoundError = class extends TheokitAgentError {
202
- name = "TaskNotFoundError";
203
- taskId;
204
- constructor(taskId, options = {}) {
205
- super(`Task not found: ${taskId}`, {
206
- ...options,
207
- isRetryable: false,
208
- code: "task_not_found"
209
- });
210
- this.taskId = taskId;
211
- }
212
- };
213
- }
14
+ Object.defineProperty(exports, "Workflow", {
15
+ enumerable: true,
16
+ get: function () { return chunkZ2OC3UIW_cjs.Workflow; }
214
17
  });
215
-
216
- // src/types/workflow.ts
217
- exports.WorkflowDuplicateStepIdError = void 0; exports.WorkflowInputError = void 0; exports.WorkflowOutputError = void 0; exports.WorkflowStateError = void 0; exports.WorkflowNestedError = void 0; exports.WorkflowAlreadyRunningError = void 0; exports.WorkflowSnapshotNotFoundError = void 0; exports.WorkflowMaxIterationsExceededError = void 0; exports.WorkflowNotSerializableError = void 0; exports.WorkflowResumeStepNotFoundError = void 0; exports.WorkflowParallelError = void 0; exports.WorkflowCompensateNotImplementedError = void 0;
218
- var init_workflow = __esm({
219
- "src/types/workflow.ts"() {
220
- exports.WorkflowDuplicateStepIdError = class extends Error {
221
- constructor(stepId) {
222
- super(`Duplicate step id "${stepId}" in workflow.`);
223
- this.stepId = stepId;
224
- }
225
- stepId;
226
- name = "WorkflowDuplicateStepIdError";
227
- };
228
- exports.WorkflowInputError = class extends Error {
229
- constructor(workflowName, detail) {
230
- super(`Workflow "${workflowName}" input failed schema validation: ${detail}`);
231
- this.workflowName = workflowName;
232
- this.detail = detail;
233
- }
234
- workflowName;
235
- detail;
236
- name = "WorkflowInputError";
237
- };
238
- exports.WorkflowOutputError = class extends Error {
239
- constructor(workflowName, detail) {
240
- super(`Workflow "${workflowName}" output failed schema validation: ${detail}`);
241
- this.workflowName = workflowName;
242
- this.detail = detail;
243
- }
244
- workflowName;
245
- detail;
246
- name = "WorkflowOutputError";
247
- };
248
- exports.WorkflowStateError = class extends Error {
249
- constructor(workflowName, detail) {
250
- super(`Workflow "${workflowName}" state failed schema validation: ${detail}`);
251
- this.workflowName = workflowName;
252
- this.detail = detail;
253
- }
254
- workflowName;
255
- detail;
256
- name = "WorkflowStateError";
257
- };
258
- exports.WorkflowNestedError = class extends Error {
259
- constructor(stepId, childName, childStatus, childError) {
260
- super(
261
- `Nested workflow "${childName}" (step "${stepId}") ended with status "${childStatus}"${childStatus === "suspended" ? " \u2014 nested suspend/resume is not supported in v1 (use a top-level suspend)" : ""}${childError ? `: ${childError.name}: ${childError.message}` : ""}`,
262
- // Reconstruct a synthetic Error from the serialized child-error shape so
263
- // debuggers surface the nested cause chain — the original Error instance is
264
- // lost at the WorkflowRun serialization boundary, so this is the best
265
- // achievable without changing the run protocol.
266
- childError ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) } : void 0
267
- );
268
- this.stepId = stepId;
269
- this.childName = childName;
270
- this.childStatus = childStatus;
271
- this.childError = childError;
272
- }
273
- stepId;
274
- childName;
275
- childStatus;
276
- childError;
277
- name = "WorkflowNestedError";
278
- };
279
- exports.WorkflowAlreadyRunningError = class extends Error {
280
- constructor(workflowName, runId) {
281
- super(`Workflow "${workflowName}" run "${runId}" already in-flight.`);
282
- this.workflowName = workflowName;
283
- this.runId = runId;
284
- }
285
- workflowName;
286
- runId;
287
- name = "WorkflowAlreadyRunningError";
288
- };
289
- exports.WorkflowSnapshotNotFoundError = class extends Error {
290
- constructor(runId) {
291
- super(`No snapshot found for runId "${runId}". Configure persistence to enable resume.`);
292
- this.runId = runId;
293
- }
294
- runId;
295
- name = "WorkflowSnapshotNotFoundError";
296
- };
297
- exports.WorkflowMaxIterationsExceededError = class extends Error {
298
- constructor(stepId, maxIterations) {
299
- super(`Step "${stepId}" exceeded max iterations (${maxIterations}).`);
300
- this.stepId = stepId;
301
- this.maxIterations = maxIterations;
302
- }
303
- stepId;
304
- maxIterations;
305
- name = "WorkflowMaxIterationsExceededError";
306
- };
307
- exports.WorkflowNotSerializableError = class extends Error {
308
- constructor(stepId, underlying) {
309
- super(
310
- `Workflow snapshot at step "${stepId}" failed to serialize as JSON: ${underlying.message}. Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`
311
- );
312
- this.stepId = stepId;
313
- this.underlying = underlying;
314
- }
315
- stepId;
316
- underlying;
317
- name = "WorkflowNotSerializableError";
318
- };
319
- exports.WorkflowResumeStepNotFoundError = class extends Error {
320
- constructor(stepId, workflowName) {
321
- super(
322
- `Cannot resume: step "${stepId}" not found in workflow "${workflowName}". The Workflow definition diverged from the snapshot.`
323
- );
324
- this.stepId = stepId;
325
- this.workflowName = workflowName;
326
- }
327
- stepId;
328
- workflowName;
329
- name = "WorkflowResumeStepNotFoundError";
330
- };
331
- exports.WorkflowParallelError = class extends AggregateError {
332
- constructor(errors, stepId) {
333
- super(errors, `${errors.length} branch(es) failed in parallel step "${stepId}".`);
334
- this.stepId = stepId;
335
- }
336
- stepId;
337
- name = "WorkflowParallelError";
338
- };
339
- exports.WorkflowCompensateNotImplementedError = class extends Error {
340
- constructor(stepId) {
341
- super(
342
- `Step "${stepId}" defines compensate, but saga engine is deferred to v1.2. Remove compensate or implement rollback manually.`
343
- );
344
- this.stepId = stepId;
345
- }
346
- stepId;
347
- name = "WorkflowCompensateNotImplementedError";
348
- };
349
- }
18
+ Object.defineProperty(exports, "WorkflowBuilder", {
19
+ enumerable: true,
20
+ get: function () { return chunkZ2OC3UIW_cjs.WorkflowBuilder; }
350
21
  });
351
- function detectNetworkFsName(typeMagic) {
352
- return NETWORK_FS_MAGIC.get(typeMagic) ?? null;
353
- }
354
- async function warnOnNetworkFsOnce(dirPath, label) {
355
- const key2 = `${dirPath}\0${label}`;
356
- if (warnedNfsDirs.has(key2)) return;
357
- warnedNfsDirs.add(key2);
358
- try {
359
- const info = await promises.statfs(dirPath);
360
- const fsName = detectNetworkFsName(info.type);
361
- if (fsName === null) return;
362
- process.stderr.write(
363
- `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} \u2014 rename() atomicity guarantees may be weaker than expected.
364
- `
365
- );
366
- } catch {
367
- }
368
- }
369
- async function replaceFileAtomic(filePath, content) {
370
- await warnOnNetworkFsOnce(path.dirname(filePath), "atomic-write");
371
- const suffix = crypto.randomBytes(8).toString("hex");
372
- const tmp = `${filePath}.${process.pid}.${suffix}.tmp`;
373
- const handle = await promises.open(tmp, "w", 384);
374
- try {
375
- await handle.writeFile(content, "utf8");
376
- await handle.sync();
377
- } finally {
378
- await handle.close();
379
- }
380
- try {
381
- await promises.rename(tmp, filePath);
382
- } catch (cause) {
383
- await promises.unlink(tmp).catch(() => void 0);
384
- throw cause;
385
- }
386
- }
387
- async function atomicWriteText(filePath, content) {
388
- await promises.mkdir(path.dirname(filePath), { recursive: true });
389
- await replaceFileAtomic(filePath, content);
390
- }
391
- var NETWORK_FS_MAGIC, warnedNfsDirs;
392
- var init_atomic_write = __esm({
393
- "src/internal/persistence/atomic-write.ts"() {
394
- NETWORK_FS_MAGIC = /* @__PURE__ */ new Map([
395
- [26985, "nfs"],
396
- [20859, "smb"],
397
- [4283649346, "cifs"],
398
- [1702057286, "fuse"]
399
- ]);
400
- warnedNfsDirs = /* @__PURE__ */ new Set();
401
- }
22
+ Object.defineProperty(exports, "WorkflowToolError", {
23
+ enumerable: true,
24
+ get: function () { return chunkZ2OC3UIW_cjs.WorkflowToolError; }
402
25
  });
403
- function getSnapshotStoreFor(options) {
404
- if (options.persistence?.backend === "json") {
405
- const dir = options.persistence.dir;
406
- let store = jsonStores.get(dir);
407
- if (store === void 0) {
408
- store = new JsonFileWorkflowSnapshotStore(dir);
409
- jsonStores.set(dir, store);
410
- }
411
- return store;
412
- }
413
- return memoryStore;
414
- }
415
- function __resetSnapshotStoresForTests() {
416
- jsonStores.clear();
417
- memoryStore.map.clear();
418
- }
419
- var InMemoryWorkflowSnapshotStore, JsonFileWorkflowSnapshotStore, memoryStore, jsonStores;
420
- var init_snapshot_store = __esm({
421
- "src/internal/workflow/snapshot-store.ts"() {
422
- init_workflow();
423
- init_atomic_write();
424
- InMemoryWorkflowSnapshotStore = class {
425
- map = /* @__PURE__ */ new Map();
426
- async save(snapshot) {
427
- try {
428
- JSON.stringify(snapshot);
429
- } catch (err) {
430
- throw new exports.WorkflowNotSerializableError(
431
- snapshot.currentStepId,
432
- err instanceof Error ? err : new Error(String(err))
433
- );
434
- }
435
- this.map.set(snapshot.runId, snapshot);
436
- }
437
- async load(runId) {
438
- return this.map.get(runId);
439
- }
440
- async delete(runId) {
441
- this.map.delete(runId);
442
- }
443
- async list(workflowName) {
444
- return [...this.map.values()].filter((s) => workflowName === void 0 || s.workflowName === workflowName).map((s) => ({
445
- runId: s.runId,
446
- workflowName: s.workflowName,
447
- suspendedAt: s.suspendedAt
448
- }));
449
- }
450
- };
451
- JsonFileWorkflowSnapshotStore = class {
452
- constructor(dir) {
453
- this.dir = dir;
454
- }
455
- dir;
456
- filePath(runId) {
457
- return path.join(this.dir, `${runId}.json`);
458
- }
459
- async save(snapshot) {
460
- let serialized;
461
- try {
462
- serialized = JSON.stringify(snapshot);
463
- } catch (err) {
464
- throw new exports.WorkflowNotSerializableError(
465
- snapshot.currentStepId,
466
- err instanceof Error ? err : new Error(String(err))
467
- );
468
- }
469
- await promises.mkdir(this.dir, { recursive: true });
470
- await atomicWriteText(this.filePath(snapshot.runId), serialized);
471
- }
472
- async load(runId) {
473
- try {
474
- const raw = await promises.readFile(this.filePath(runId), "utf8");
475
- return JSON.parse(raw);
476
- } catch (err) {
477
- if (err.code === "ENOENT") return void 0;
478
- throw err;
479
- }
480
- }
481
- async delete(runId) {
482
- try {
483
- await (await import('fs/promises')).unlink(this.filePath(runId));
484
- } catch (err) {
485
- if (err.code !== "ENOENT") throw err;
486
- }
487
- }
488
- async readEntriesOrEmpty() {
489
- try {
490
- return await promises.readdir(this.dir);
491
- } catch (err) {
492
- if (err.code === "ENOENT") return [];
493
- throw err;
494
- }
495
- }
496
- async readSnapshotSafe(file) {
497
- try {
498
- const raw = await promises.readFile(path.join(this.dir, file), "utf8");
499
- return JSON.parse(raw);
500
- } catch {
501
- return void 0;
502
- }
503
- }
504
- async list(workflowName) {
505
- const entries = await this.readEntriesOrEmpty();
506
- const results = [];
507
- for (const file of entries) {
508
- if (!file.endsWith(".json")) continue;
509
- const snap = await this.readSnapshotSafe(file);
510
- if (snap === void 0) continue;
511
- if (workflowName !== void 0 && snap.workflowName !== workflowName) continue;
512
- results.push({
513
- runId: snap.runId,
514
- workflowName: snap.workflowName,
515
- suspendedAt: snap.suspendedAt
516
- });
517
- }
518
- return results;
519
- }
520
- };
521
- memoryStore = new InMemoryWorkflowSnapshotStore();
522
- jsonStores = /* @__PURE__ */ new Map();
523
- }
26
+ Object.defineProperty(exports, "agentStep", {
27
+ enumerable: true,
28
+ get: function () { return chunkZ2OC3UIW_cjs.agentStep; }
524
29
  });
525
-
526
- // src/internal/workflow/ctx.ts
527
- function makeStepContext(runId, signal, state2) {
528
- return {
529
- runId,
530
- signal,
531
- log: {
532
- debug: (msg, attrs) => emit("debug", runId, msg, attrs),
533
- info: (msg, attrs) => emit("info", runId, msg, attrs),
534
- warn: (msg, attrs) => emit("warn", runId, msg, attrs)
535
- },
536
- suspend: async (payload) => {
537
- throw new WorkflowSuspendedSentinel(payload);
538
- },
539
- // SE29 — read reflects the current shared state; write goes through the
540
- // controller (which validates against `stateSchema`).
541
- get state() {
542
- return state2.getState();
543
- },
544
- setState: (next) => state2.setState(next)
545
- };
546
- }
547
- function emit(level, runId, msg, attrs) {
548
- const tag = `[workflow ${runId}]`;
549
- if (attrs !== void 0) {
550
- if (level === "warn") console.warn(tag, msg, attrs);
551
- else console.log(tag, msg, attrs);
552
- } else {
553
- if (level === "warn") console.warn(tag, msg);
554
- else console.log(tag, msg);
555
- }
556
- }
557
- function combineSignals(...signals) {
558
- const valid = signals.filter((s) => s !== void 0);
559
- if (valid.length === 0) return new AbortController().signal;
560
- if (valid.length === 1) return valid[0];
561
- const ctrl = new AbortController();
562
- for (const s of valid) {
563
- if (s.aborted) {
564
- ctrl.abort(s.reason);
565
- break;
566
- }
567
- s.addEventListener("abort", () => ctrl.abort(s.reason), { once: true });
568
- }
569
- return ctrl.signal;
570
- }
571
- var WorkflowSuspendedSentinel;
572
- var init_ctx = __esm({
573
- "src/internal/workflow/ctx.ts"() {
574
- WorkflowSuspendedSentinel = class extends Error {
575
- constructor(payload) {
576
- super("__workflow_suspended__");
577
- this.payload = payload;
578
- }
579
- payload;
580
- name = "WorkflowSuspendedSentinel";
581
- };
582
- }
30
+ Object.defineProperty(exports, "cloneWorkflow", {
31
+ enumerable: true,
32
+ get: function () { return chunkZ2OC3UIW_cjs.cloneWorkflow; }
583
33
  });
584
-
585
- // src/internal/workflow/error-shape.ts
586
- function errToShape(err) {
587
- if (err instanceof Error) {
588
- return { name: err.name, message: err.message };
589
- }
590
- return { name: "Error", message: String(err) };
591
- }
592
- var init_error_shape = __esm({
593
- "src/internal/workflow/error-shape.ts"() {
594
- }
34
+ Object.defineProperty(exports, "fn", {
35
+ enumerable: true,
36
+ get: function () { return chunkZ2OC3UIW_cjs.fn; }
595
37
  });
596
-
597
- // src/internal/workflow/executor-helpers.ts
598
- function assembleRun(params) {
599
- return {
600
- id: params.runId,
601
- name: params.name,
602
- status: params.status,
603
- startedAt: params.startedAt,
604
- endedAt: Date.now(),
605
- stepResults: params.stepResults,
606
- ...params.output !== void 0 ? { output: params.output } : {},
607
- ...params.error !== void 0 ? { error: params.error } : {}
608
- };
609
- }
610
- function abortRun(name, runId, startedAt, stepResults, signal) {
611
- return assembleRun({
612
- runId,
613
- name,
614
- status: "cancelled",
615
- stepResults,
616
- startedAt,
617
- error: { name: "AbortError", message: String(signal.reason ?? "Aborted") }
618
- });
619
- }
620
- function validateWorkflowSchema(schema, value) {
621
- if (schema === void 0) return void 0;
622
- let parsed;
623
- try {
624
- parsed = schema.safeParse(value);
625
- } catch {
626
- return "schema uses async refinements, which whole-workflow validation does not support (use a synchronous Zod schema)";
627
- }
628
- if (parsed.success) return void 0;
629
- return parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
630
- }
631
- function makeStateController(options, initial) {
632
- let current = initial;
633
- return {
634
- getState: () => current,
635
- setState: (next) => {
636
- const issues = validateWorkflowSchema(options.stateSchema, next);
637
- if (issues !== void 0) throw new exports.WorkflowStateError(options.name, issues);
638
- current = next;
639
- }
640
- };
641
- }
642
- var init_executor_helpers = __esm({
643
- "src/internal/workflow/executor-helpers.ts"() {
644
- init_workflow();
645
- }
38
+ Object.defineProperty(exports, "workflowAsTool", {
39
+ enumerable: true,
40
+ get: function () { return chunkZ2OC3UIW_cjs.workflowAsTool; }
646
41
  });
647
-
648
- // src/internal/workflow/run-id.ts
649
- function mintRunId() {
650
- return `wfr-${globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
651
- }
652
- var init_run_id = __esm({
653
- "src/internal/workflow/run-id.ts"() {
654
- }
42
+ Object.defineProperty(exports, "workflowStep", {
43
+ enumerable: true,
44
+ get: function () { return chunkZ2OC3UIW_cjs.workflowStep; }
655
45
  });
656
-
657
- // src/internal/workflow/single-flight.ts
658
- function key(workflowId, runId) {
659
- return `${workflowId}:${runId}`;
660
- }
661
- function acquireSingleFlight(workflowId, runId, workflowName) {
662
- const k = key(workflowId, runId);
663
- if (registry.has(k)) {
664
- throw new exports.WorkflowAlreadyRunningError(workflowName, runId);
665
- }
666
- const controller = new AbortController();
667
- registry.set(k, { controller });
668
- return {
669
- signal: controller.signal,
670
- release: () => {
671
- registry.delete(k);
672
- }
673
- };
674
- }
675
- var registry;
676
- var init_single_flight = __esm({
677
- "src/internal/workflow/single-flight.ts"() {
678
- init_workflow();
679
- registry = /* @__PURE__ */ new Map();
680
- }
46
+ Object.defineProperty(exports, "WorkflowAlreadyRunningError", {
47
+ enumerable: true,
48
+ get: function () { return chunkBWT67BI4_cjs.WorkflowAlreadyRunningError; }
681
49
  });
682
-
683
- // src/internal/workflow/retry-policy.ts
684
- function backoffConfigFromPolicy(policy) {
685
- return {
686
- max: policy.maxAttempts,
687
- init: policy.initialBackoffMs ?? 1e3,
688
- coef: policy.backoffCoefficient ?? 2,
689
- cap: policy.maximumBackoffMs ?? 3e4,
690
- nonRetryable: new Set(policy.nonRetryableErrors ?? DEFAULT_NON_RETRYABLE)
691
- };
692
- }
693
- function throwIfAborted(signal) {
694
- if (signal.aborted) {
695
- throw new DOMException(String(signal.reason ?? "Aborted"), "AbortError");
696
- }
697
- }
698
- function shouldRethrow(err, attempt, cfg) {
699
- const errName = err instanceof Error ? err.name : "Error";
700
- return cfg.nonRetryable.has(errName) || attempt === cfg.max;
701
- }
702
- async function tryOnce(fn2, attempt, cfg, signal) {
703
- try {
704
- const value = await fn2();
705
- return { value, attempts: attempt };
706
- } catch (err) {
707
- if (shouldRethrow(err, attempt, cfg)) throw err;
708
- await abortableSleep(Math.min(cfg.init * cfg.coef ** (attempt - 1), cfg.cap), signal);
709
- return { kind: "retry" };
710
- }
711
- }
712
- async function withRetry(fn2, policy, signal) {
713
- const cfg = backoffConfigFromPolicy(policy);
714
- for (let attempt = 1; attempt <= cfg.max; attempt += 1) {
715
- throwIfAborted(signal);
716
- const result = await tryOnce(fn2, attempt, cfg, signal);
717
- if ("value" in result) return result;
718
- }
719
- throw new Error("withRetry: exhausted attempts without throwing");
720
- }
721
- async function abortableSleep(ms, signal) {
722
- if (signal.aborted) {
723
- throw new DOMException(String(signal.reason ?? "Aborted"), "AbortError");
724
- }
725
- return new Promise((resolve2, reject) => {
726
- const timer = setTimeout(() => {
727
- cleanup();
728
- resolve2();
729
- }, ms);
730
- const onAbort = () => {
731
- clearTimeout(timer);
732
- cleanup();
733
- reject(new DOMException(String(signal.reason ?? "Aborted"), "AbortError"));
734
- };
735
- const cleanup = () => {
736
- signal.removeEventListener("abort", onAbort);
737
- };
738
- signal.addEventListener("abort", onAbort, { once: true });
739
- });
740
- }
741
- var DEFAULT_NON_RETRYABLE;
742
- var init_retry_policy = __esm({
743
- "src/internal/workflow/retry-policy.ts"() {
744
- DEFAULT_NON_RETRYABLE = ["AbortError", "WorkflowSnapshotNotFoundError", "ConfigurationError"];
745
- }
50
+ Object.defineProperty(exports, "WorkflowCompensateNotImplementedError", {
51
+ enumerable: true,
52
+ get: function () { return chunkBWT67BI4_cjs.WorkflowCompensateNotImplementedError; }
746
53
  });
747
-
748
- // src/internal/workflow/step-agent.ts
749
- async function runAgentStep(step, input, ctx) {
750
- const startedAt = Date.now();
751
- const agentId = step.agent.agentId;
752
- if (typeof agentId === "string" && agentId.startsWith("bc-")) {
753
- return {
754
- stepId: step.id,
755
- kind: "agent",
756
- status: "failed",
757
- attempts: 0,
758
- durationMs: Date.now() - startedAt,
759
- error: errToShape(
760
- new UnsupportedRunOperationError(
761
- `Workflow agent steps not supported on CloudAgent yet (D244). agent="${agentId}", step="${step.id}"`,
762
- "workflow"
763
- )
764
- )
765
- };
766
- }
767
- let prompt;
768
- try {
769
- prompt = typeof step.promptTemplate === "string" ? step.promptTemplate : step.promptTemplate(input);
770
- } catch (err) {
771
- return {
772
- stepId: step.id,
773
- kind: "agent",
774
- status: "failed",
775
- attempts: 0,
776
- durationMs: Date.now() - startedAt,
777
- error: errToShape(err)
778
- };
779
- }
780
- if (typeof prompt !== "string" || prompt.length === 0) {
781
- return {
782
- stepId: step.id,
783
- kind: "agent",
784
- status: "failed",
785
- attempts: 0,
786
- durationMs: Date.now() - startedAt,
787
- error: errToShape(
788
- new Error(`agentStep "${step.id}": rendered prompt must be a non-empty string`)
789
- )
790
- };
791
- }
792
- const exec = async () => {
793
- const run = await step.agent.send(
794
- prompt,
795
- step.origin !== void 0 ? { origin: step.origin } : void 0
796
- );
797
- const result = await run.wait();
798
- if (result.status === "finished") {
799
- return result.result ?? "";
800
- }
801
- if (result.status === "error") {
802
- throw result.error ?? new Error("agent.send errored");
803
- }
804
- throw new Error(`Unexpected agent status: ${result.status}`);
805
- };
806
- try {
807
- const { value, attempts } = step.retry !== void 0 ? await withRetry(exec, step.retry, ctx.signal) : { value: await exec(), attempts: 1 };
808
- return {
809
- stepId: step.id,
810
- kind: "agent",
811
- status: "completed",
812
- attempts,
813
- durationMs: Date.now() - startedAt,
814
- output: value
815
- };
816
- } catch (err) {
817
- if (err instanceof WorkflowSuspendedSentinel) throw err;
818
- return {
819
- stepId: step.id,
820
- kind: "agent",
821
- status: "failed",
822
- attempts: 1,
823
- durationMs: Date.now() - startedAt,
824
- error: errToShape(err)
825
- };
826
- }
827
- }
828
- var init_step_agent = __esm({
829
- "src/internal/workflow/step-agent.ts"() {
830
- init_errors();
831
- init_ctx();
832
- init_error_shape();
833
- init_retry_policy();
834
- }
54
+ Object.defineProperty(exports, "WorkflowDuplicateStepIdError", {
55
+ enumerable: true,
56
+ get: function () { return chunkBWT67BI4_cjs.WorkflowDuplicateStepIdError; }
835
57
  });
836
-
837
- // src/internal/workflow/step-branch.ts
838
- async function runBranchStep(step, input, ctx, options, prevStepResults, dispatch) {
839
- const startedAt = Date.now();
840
- for (let i = 0; i < step.predicates.length; i += 1) {
841
- const pair = step.predicates[i];
842
- const [predicate, branch] = pair;
843
- let matched = false;
844
- try {
845
- matched = await Promise.resolve(predicate(input));
846
- } catch (err) {
847
- const errText = err instanceof Error ? err.message : String(err);
848
- console.warn(
849
- redactSecrets(
850
- `[workflow] branch "${step.id}" predicate ${i} threw, treating as no-match: ${errText}`
851
- )
852
- );
853
- }
854
- if (matched) {
855
- const r = await runInnerSequence(branch, input, ctx, options, prevStepResults, dispatch);
856
- return {
857
- ...r,
858
- stepId: step.id,
859
- kind: "branch",
860
- durationMs: Date.now() - startedAt
861
- };
862
- }
863
- }
864
- if (step.fallback !== void 0) {
865
- const r = await runInnerSequence(step.fallback, input, ctx, options, prevStepResults, dispatch);
866
- return {
867
- ...r,
868
- stepId: step.id,
869
- kind: "branch",
870
- durationMs: Date.now() - startedAt
871
- };
872
- }
873
- return {
874
- stepId: step.id,
875
- kind: "branch",
876
- status: "skipped",
877
- attempts: 0,
878
- durationMs: Date.now() - startedAt,
879
- output: input
880
- };
881
- }
882
- async function runInnerSequence(branch, input, ctx, options, prevStepResults, dispatch) {
883
- let acc = input;
884
- let lastAttempts = 1;
885
- for (const inner of branch) {
886
- const r = await dispatch(inner, acc, ctx, options, prevStepResults);
887
- lastAttempts = r.attempts;
888
- if (r.status === "failed") {
889
- return {
890
- stepId: inner.id,
891
- kind: "branch",
892
- status: "failed",
893
- attempts: r.attempts,
894
- durationMs: 0,
895
- error: r.error ?? errToShape(new Error("branch inner step failed"))
896
- };
897
- }
898
- acc = r.output;
899
- }
900
- return {
901
- stepId: "__branch-completed__",
902
- kind: "branch",
903
- status: "completed",
904
- attempts: lastAttempts,
905
- durationMs: 0,
906
- output: acc
907
- };
908
- }
909
- var init_step_branch = __esm({
910
- "src/internal/workflow/step-branch.ts"() {
911
- init_redact();
912
- init_error_shape();
913
- }
58
+ Object.defineProperty(exports, "WorkflowInputError", {
59
+ enumerable: true,
60
+ get: function () { return chunkBWT67BI4_cjs.WorkflowInputError; }
914
61
  });
915
-
916
- // src/internal/workflow/step-dowhile.ts
917
- async function runDowhileStep(step, input, ctx, options, prevStepResults, dispatch) {
918
- const startedAt = Date.now();
919
- const maxIter = step.maxIterations ?? 100;
920
- let acc = input;
921
- let i = 0;
922
- while (true) {
923
- if (i >= maxIter) {
924
- return {
925
- stepId: step.id,
926
- kind: "dowhile",
927
- status: "failed",
928
- attempts: i,
929
- durationMs: Date.now() - startedAt,
930
- error: errToShape(new exports.WorkflowMaxIterationsExceededError(step.id, maxIter))
931
- };
932
- }
933
- const r = await dispatch(step.step, acc, ctx, options, prevStepResults);
934
- if (r.status === "failed") {
935
- return {
936
- stepId: step.id,
937
- kind: "dowhile",
938
- status: "failed",
939
- attempts: i + 1,
940
- durationMs: Date.now() - startedAt,
941
- error: r.error
942
- };
943
- }
944
- acc = r.output;
945
- i += 1;
946
- let shouldContinue = false;
947
- try {
948
- shouldContinue = await Promise.resolve(step.condFn(acc, i));
949
- } catch (err) {
950
- return {
951
- stepId: step.id,
952
- kind: "dowhile",
953
- status: "failed",
954
- attempts: i,
955
- durationMs: Date.now() - startedAt,
956
- error: errToShape(err)
957
- };
958
- }
959
- if (!shouldContinue) break;
960
- }
961
- return {
962
- stepId: step.id,
963
- kind: "dowhile",
964
- status: "completed",
965
- attempts: i,
966
- durationMs: Date.now() - startedAt,
967
- output: acc
968
- };
969
- }
970
- var init_step_dowhile = __esm({
971
- "src/internal/workflow/step-dowhile.ts"() {
972
- init_workflow();
973
- init_error_shape();
974
- }
62
+ Object.defineProperty(exports, "WorkflowMaxIterationsExceededError", {
63
+ enumerable: true,
64
+ get: function () { return chunkBWT67BI4_cjs.WorkflowMaxIterationsExceededError; }
975
65
  });
976
-
977
- // src/internal/workflow/step-fn.ts
978
- function failedFnResult(stepId, attempts, startedAt, err) {
979
- return {
980
- stepId,
981
- kind: "fn",
982
- status: "failed",
983
- attempts,
984
- durationMs: Date.now() - startedAt,
985
- error: errToShape(err)
986
- };
987
- }
988
- function validate(schema, value) {
989
- if (schema === void 0) return void 0;
990
- schema.parse(value);
991
- return void 0;
992
- }
993
- async function execWithRetry(step, input, ctx) {
994
- const exec = async () => step.fn(input, ctx);
995
- if (step.retry !== void 0) return withRetry(exec, step.retry, ctx.signal);
996
- return { value: await exec(), attempts: 1 };
997
- }
998
- async function runFnStep(step, input, ctx) {
999
- const startedAt = Date.now();
1000
- if (step.compensate !== void 0) {
1001
- return failedFnResult(
1002
- step.id,
1003
- 0,
1004
- startedAt,
1005
- new exports.WorkflowCompensateNotImplementedError(step.id)
1006
- );
1007
- }
1008
- try {
1009
- validate(step.inputSchema, input);
1010
- } catch (err) {
1011
- return failedFnResult(step.id, 0, startedAt, err);
1012
- }
1013
- try {
1014
- const { value, attempts } = await execWithRetry(step, input, ctx);
1015
- try {
1016
- validate(step.outputSchema, value);
1017
- } catch (err) {
1018
- return failedFnResult(step.id, attempts, startedAt, err);
1019
- }
1020
- return {
1021
- stepId: step.id,
1022
- kind: "fn",
1023
- status: "completed",
1024
- attempts,
1025
- durationMs: Date.now() - startedAt,
1026
- output: value
1027
- };
1028
- } catch (err) {
1029
- if (err instanceof WorkflowSuspendedSentinel) throw err;
1030
- return failedFnResult(step.id, 1, startedAt, err);
1031
- }
1032
- }
1033
- var init_step_fn = __esm({
1034
- "src/internal/workflow/step-fn.ts"() {
1035
- init_workflow();
1036
- init_ctx();
1037
- init_error_shape();
1038
- init_retry_policy();
1039
- }
1040
- });
1041
-
1042
- // src/internal/runtime/concurrency/async-semaphore.ts
1043
- function createSemaphore(permits) {
1044
- if (!Number.isInteger(permits) || permits < 1) {
1045
- throw new ConfigurationError(
1046
- `async-semaphore: permits must be a positive integer, got ${permits}`,
1047
- { code: "invalid_concurrency" }
1048
- );
1049
- }
1050
- let active = 0;
1051
- const queue = [];
1052
- function tryGrant() {
1053
- if (active < permits && queue.length > 0) {
1054
- const resolve2 = queue.shift();
1055
- if (resolve2 !== void 0) {
1056
- active += 1;
1057
- resolve2();
1058
- }
1059
- }
1060
- }
1061
- return {
1062
- inFlight: () => active,
1063
- pending: () => queue.length + active,
1064
- async acquire() {
1065
- await new Promise((resolve2) => {
1066
- queue.push(resolve2);
1067
- tryGrant();
1068
- });
1069
- let released = false;
1070
- return () => {
1071
- if (released) return;
1072
- released = true;
1073
- active -= 1;
1074
- tryGrant();
1075
- };
1076
- }
1077
- };
1078
- }
1079
- var init_async_semaphore = __esm({
1080
- "src/internal/runtime/concurrency/async-semaphore.ts"() {
1081
- init_errors();
1082
- }
1083
- });
1084
-
1085
- // src/internal/workflow/step-foreach.ts
1086
- async function runForeachStep(step, _input, ctx, options, prevStepResults, dispatch) {
1087
- const startedAt = Date.now();
1088
- const sourceResult = prevStepResults.find((r) => r.stepId === step.iterableFrom);
1089
- if (sourceResult === void 0) {
1090
- return {
1091
- stepId: step.id,
1092
- kind: "foreach",
1093
- status: "failed",
1094
- attempts: 0,
1095
- durationMs: Date.now() - startedAt,
1096
- error: errToShape(
1097
- new Error(
1098
- `foreach.iterableFrom "${step.iterableFrom}" not found in top-level steps. It must reference an earlier top-level step ID \u2014 nested step IDs inside parallel/branch/foreach blocks are not visible here.`
1099
- )
1100
- )
1101
- };
1102
- }
1103
- const items = sourceResult.output;
1104
- if (!Array.isArray(items)) {
1105
- return {
1106
- stepId: step.id,
1107
- kind: "foreach",
1108
- status: "failed",
1109
- attempts: 0,
1110
- durationMs: Date.now() - startedAt,
1111
- error: errToShape(
1112
- new Error(
1113
- `foreach.iterableFrom "${step.iterableFrom}" output must be Array, got ${typeof items}.`
1114
- )
1115
- )
1116
- };
1117
- }
1118
- if (items.length === 0) {
1119
- return {
1120
- stepId: step.id,
1121
- kind: "foreach",
1122
- status: "completed",
1123
- attempts: 1,
1124
- durationMs: Date.now() - startedAt,
1125
- output: []
1126
- };
1127
- }
1128
- const concurrency = step.concurrency ?? 4;
1129
- const sem = createSemaphore(Math.max(1, Math.min(concurrency, items.length)));
1130
- const failures = [];
1131
- const outputs = new Array(items.length);
1132
- await Promise.all(
1133
- items.map(async (item, idx) => {
1134
- const release = await sem.acquire();
1135
- try {
1136
- const r = await dispatch(step.step, item, ctx, options, prevStepResults);
1137
- if (r.status === "failed") {
1138
- failures.push(new Error(`foreach item ${idx} failed: ${r.error?.message ?? "unknown"}`));
1139
- } else {
1140
- outputs[idx] = r.output;
1141
- }
1142
- } finally {
1143
- release();
1144
- }
1145
- })
1146
- );
1147
- if (failures.length > 0) {
1148
- return {
1149
- stepId: step.id,
1150
- kind: "foreach",
1151
- status: "failed",
1152
- attempts: 1,
1153
- durationMs: Date.now() - startedAt,
1154
- error: errToShape(
1155
- new AggregateError(failures, `foreach "${step.id}" had ${failures.length} failure(s)`)
1156
- )
1157
- };
1158
- }
1159
- return {
1160
- stepId: step.id,
1161
- kind: "foreach",
1162
- status: "completed",
1163
- attempts: 1,
1164
- durationMs: Date.now() - startedAt,
1165
- output: outputs
1166
- };
1167
- }
1168
- var init_step_foreach = __esm({
1169
- "src/internal/workflow/step-foreach.ts"() {
1170
- init_async_semaphore();
1171
- init_error_shape();
1172
- }
66
+ Object.defineProperty(exports, "WorkflowNestedError", {
67
+ enumerable: true,
68
+ get: function () { return chunkBWT67BI4_cjs.WorkflowNestedError; }
1173
69
  });
1174
-
1175
- // src/internal/workflow/step-parallel.ts
1176
- async function runParallelStep(step, input, ctx, options, _prevStepResults, dispatch) {
1177
- const startedAt = Date.now();
1178
- const policy = step.errorPolicy ?? "fail-fast";
1179
- const branchCount = step.branches.length;
1180
- if (branchCount === 0) {
1181
- return {
1182
- stepId: step.id,
1183
- kind: "parallel",
1184
- status: "completed",
1185
- attempts: 1,
1186
- durationMs: Date.now() - startedAt,
1187
- output: []
1188
- };
1189
- }
1190
- const concurrency = step.concurrency ?? branchCount;
1191
- const sem = createSemaphore(Math.max(1, Math.min(concurrency, branchCount)));
1192
- const failFastCtrl = policy === "fail-fast" ? new AbortController() : void 0;
1193
- const branchSignal = policy === "fail-fast" ? mergeSignals(ctx.signal, failFastCtrl.signal) : ctx.signal;
1194
- const semBranchPromises = step.branches.map(async (branch, branchIdx) => {
1195
- const release = await sem.acquire();
1196
- try {
1197
- return await runBranch(
1198
- branch,
1199
- input,
1200
- { ...ctx, signal: branchSignal },
1201
- options,
1202
- dispatch,
1203
- branchIdx
1204
- );
1205
- } finally {
1206
- release();
1207
- }
1208
- });
1209
- if (policy === "fail-fast") {
1210
- try {
1211
- const outputs2 = await Promise.all(semBranchPromises);
1212
- return {
1213
- stepId: step.id,
1214
- kind: "parallel",
1215
- status: "completed",
1216
- attempts: 1,
1217
- durationMs: Date.now() - startedAt,
1218
- output: outputs2
1219
- };
1220
- } catch (err) {
1221
- failFastCtrl?.abort(err);
1222
- const settled2 = await Promise.allSettled(semBranchPromises);
1223
- const errors = settled2.filter((s) => s.status === "rejected").map((s) => s.reason instanceof Error ? s.reason : new Error(String(s.reason)));
1224
- return {
1225
- stepId: step.id,
1226
- kind: "parallel",
1227
- status: "failed",
1228
- attempts: 1,
1229
- durationMs: Date.now() - startedAt,
1230
- error: errToShape(new exports.WorkflowParallelError(errors, step.id)),
1231
- output: void 0
1232
- };
1233
- }
1234
- }
1235
- const settled = await Promise.allSettled(semBranchPromises);
1236
- const outputs = settled.map(
1237
- (s) => s.status === "fulfilled" ? { ok: true, value: s.value } : { ok: false, error: errToShape(s.reason) }
1238
- );
1239
- return {
1240
- stepId: step.id,
1241
- kind: "parallel",
1242
- status: "completed",
1243
- attempts: 1,
1244
- durationMs: Date.now() - startedAt,
1245
- output: outputs
1246
- };
1247
- }
1248
- async function runBranch(branch, input, ctx, options, dispatch, branchIdx) {
1249
- let acc = input;
1250
- for (const inner of branch) {
1251
- const r = await dispatch(inner, acc, ctx, options, []);
1252
- if (r.status === "failed") {
1253
- throw new Error(
1254
- `parallel branch ${branchIdx} step "${inner.id}" failed: ${r.error?.message ?? "unknown"}`
1255
- );
1256
- }
1257
- acc = r.output;
1258
- }
1259
- return acc;
1260
- }
1261
- function mergeSignals(a, b) {
1262
- if (a.aborted) return a;
1263
- if (b.aborted) return b;
1264
- const ctrl = new AbortController();
1265
- const onAbortA = () => ctrl.abort(a.reason);
1266
- const onAbortB = () => ctrl.abort(b.reason);
1267
- a.addEventListener("abort", onAbortA, { once: true });
1268
- b.addEventListener("abort", onAbortB, { once: true });
1269
- return ctrl.signal;
1270
- }
1271
- var init_step_parallel = __esm({
1272
- "src/internal/workflow/step-parallel.ts"() {
1273
- init_workflow();
1274
- init_async_semaphore();
1275
- init_error_shape();
1276
- }
70
+ Object.defineProperty(exports, "WorkflowNotSerializableError", {
71
+ enumerable: true,
72
+ get: function () { return chunkBWT67BI4_cjs.WorkflowNotSerializableError; }
1277
73
  });
1278
-
1279
- // src/internal/workflow/step-sleep.ts
1280
- async function runSleepStep(step, input, ctx) {
1281
- const startedAt = Date.now();
1282
- try {
1283
- await abortableSleep(step.durationMs, ctx.signal);
1284
- return {
1285
- stepId: step.id,
1286
- kind: "sleep",
1287
- status: "completed",
1288
- attempts: 1,
1289
- durationMs: Date.now() - startedAt,
1290
- output: input
1291
- // sleep is a pass-through
1292
- };
1293
- } catch (err) {
1294
- return {
1295
- stepId: step.id,
1296
- kind: "sleep",
1297
- status: "failed",
1298
- attempts: 1,
1299
- durationMs: Date.now() - startedAt,
1300
- error: errToShape(err)
1301
- };
1302
- }
1303
- }
1304
- var init_step_sleep = __esm({
1305
- "src/internal/workflow/step-sleep.ts"() {
1306
- init_error_shape();
1307
- init_retry_policy();
1308
- }
74
+ Object.defineProperty(exports, "WorkflowOutputError", {
75
+ enumerable: true,
76
+ get: function () { return chunkBWT67BI4_cjs.WorkflowOutputError; }
1309
77
  });
1310
- function getTracer(name, version = "1.0.0") {
1311
- const cached = tracerCache.get(name);
1312
- if (cached !== void 0) return cached.tracer ?? void 0;
1313
- try {
1314
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('workflow.cjs', document.baseURI).href)));
1315
- const otel = r("@opentelemetry/api");
1316
- if (otel.trace?.getTracer === void 0) {
1317
- tracerCache.set(name, { tracer: null });
1318
- return void 0;
1319
- }
1320
- const tracer = otel.trace.getTracer(name, version);
1321
- tracerCache.set(name, { tracer });
1322
- return tracer;
1323
- } catch {
1324
- tracerCache.set(name, { tracer: null });
1325
- return void 0;
1326
- }
1327
- }
1328
- var noopSpan, tracerCache;
1329
- var init_tracer_loader = __esm({
1330
- "src/internal/telemetry/tracer-loader.ts"() {
1331
- noopSpan = {
1332
- setAttribute: () => noopSpan,
1333
- end: () => void 0
1334
- };
1335
- tracerCache = /* @__PURE__ */ new Map();
1336
- }
78
+ Object.defineProperty(exports, "WorkflowParallelError", {
79
+ enumerable: true,
80
+ get: function () { return chunkBWT67BI4_cjs.WorkflowParallelError; }
1337
81
  });
1338
-
1339
- // src/internal/workflow/telemetry.ts
1340
- function startWorkflowRunSpan(info) {
1341
- const tracer = getTracer(TRACER_NAME);
1342
- if (tracer === void 0) return noopSpan;
1343
- return tracer.startSpan("workflow.run", {
1344
- attributes: {
1345
- "workflow.name": info.workflowName,
1346
- "workflow.run_id": info.runId
1347
- }
1348
- });
1349
- }
1350
- function startWorkflowStepSpan(info) {
1351
- const tracer = getTracer(TRACER_NAME);
1352
- if (tracer === void 0) return noopSpan;
1353
- return tracer.startSpan(`workflow.step.${info.stepId}`, {
1354
- attributes: {
1355
- "step.id": info.stepId,
1356
- "step.kind": info.kind,
1357
- "step.attempt": info.attempt
1358
- }
1359
- });
1360
- }
1361
- var TRACER_NAME;
1362
- var init_telemetry = __esm({
1363
- "src/internal/workflow/telemetry.ts"() {
1364
- init_tracer_loader();
1365
- TRACER_NAME = "@theokit/sdk/workflow";
1366
- }
82
+ Object.defineProperty(exports, "WorkflowResumeStepNotFoundError", {
83
+ enumerable: true,
84
+ get: function () { return chunkBWT67BI4_cjs.WorkflowResumeStepNotFoundError; }
1367
85
  });
1368
-
1369
- // src/internal/workflow/executor.ts
1370
- var executor_exports = {};
1371
- __export(executor_exports, {
1372
- dispatchStep: () => dispatchStep,
1373
- executeWorkflow: () => executeWorkflow,
1374
- resumeWorkflow: () => resumeWorkflow
86
+ Object.defineProperty(exports, "WorkflowSnapshotNotFoundError", {
87
+ enumerable: true,
88
+ get: function () { return chunkBWT67BI4_cjs.WorkflowSnapshotNotFoundError; }
1375
89
  });
1376
- async function handleSuspend(err, ctx) {
1377
- try {
1378
- await saveSnapshot({
1379
- runId: ctx.runId,
1380
- workflowName: ctx.options.name,
1381
- currentStepId: ctx.step.id,
1382
- suspendedPayload: err.payload,
1383
- stepResults: ctx.stepResults,
1384
- accumulatedInput: ctx.acc,
1385
- state: ctx.stepCtx.state,
1386
- // SE29 — capture the shared state at suspend
1387
- options: ctx.options
1388
- });
1389
- } catch (snapErr) {
1390
- ctx.stepSpan.setAttribute("step.status", "failed");
1391
- ctx.stepSpan.end();
1392
- return {
1393
- kind: "failed",
1394
- run: assembleRun({
1395
- runId: ctx.runId,
1396
- name: ctx.name,
1397
- status: "failed",
1398
- stepResults: ctx.stepResults,
1399
- startedAt: ctx.startedAt,
1400
- error: errToShape(snapErr)
1401
- })
1402
- };
1403
- }
1404
- ctx.stepSpan.setAttribute("step.status", "suspended");
1405
- ctx.stepSpan.end();
1406
- return {
1407
- kind: "suspended",
1408
- run: assembleRun({
1409
- runId: ctx.runId,
1410
- name: ctx.name,
1411
- status: "suspended",
1412
- stepResults: [
1413
- ...ctx.stepResults,
1414
- {
1415
- stepId: ctx.step.id,
1416
- kind: ctx.step.kind,
1417
- status: "suspended",
1418
- attempts: 1,
1419
- durationMs: 0,
1420
- output: void 0
1421
- }
1422
- ],
1423
- startedAt: ctx.startedAt
1424
- })
1425
- };
1426
- }
1427
- async function runOneStep(args) {
1428
- const stepSpan = startWorkflowStepSpan({
1429
- stepId: args.step.id,
1430
- kind: args.step.kind,
1431
- attempt: 1
1432
- });
1433
- let result;
1434
- try {
1435
- result = await dispatchStep(args.step, args.acc, args.ctx, args.options, args.stepResults);
1436
- } catch (err) {
1437
- if (err instanceof WorkflowSuspendedSentinel) {
1438
- const outcome = await handleSuspend(err, { ...args, stepSpan, stepCtx: args.ctx });
1439
- return { kind: "terminal", run: outcome.run };
1440
- }
1441
- result = {
1442
- stepId: args.step.id,
1443
- kind: args.step.kind,
1444
- status: "failed",
1445
- attempts: 1,
1446
- durationMs: 0,
1447
- error: errToShape(err)
1448
- };
1449
- }
1450
- stepSpan.setAttribute("step.status", result.status);
1451
- stepSpan.setAttribute("step.attempts", result.attempts);
1452
- stepSpan.end();
1453
- return { kind: "ok", result };
1454
- }
1455
- function handleStepOutcome(outcome, step, loop, onStepEvent) {
1456
- if (outcome.kind === "terminal") {
1457
- if (outcome.run.status === "suspended") {
1458
- onStepEvent?.({ type: "workflow_suspended", stepId: step.id });
1459
- }
1460
- return { terminal: outcome.run };
1461
- }
1462
- loop.stepResults.push(outcome.result);
1463
- if (outcome.result.status === "failed") {
1464
- onStepEvent?.({
1465
- type: "step_failed",
1466
- stepId: step.id,
1467
- error: outcome.result.error ?? { name: "WorkflowStepError", message: "step failed" }
1468
- });
1469
- return {
1470
- terminal: assembleRun({
1471
- runId: loop.runId,
1472
- name: loop.name,
1473
- status: "failed",
1474
- stepResults: loop.stepResults,
1475
- startedAt: loop.startedAt,
1476
- error: outcome.result.error
1477
- })
1478
- };
1479
- }
1480
- onStepEvent?.({ type: "step_completed", stepId: step.id, output: outcome.result.output });
1481
- return { acc: outcome.result.output };
1482
- }
1483
- async function runStepsLoop(params) {
1484
- const { options, steps, ctx, runId, startedAt, signal, onStepEvent } = params;
1485
- const stepResults = [...params.initialStepResults ?? []];
1486
- const loop = { stepResults, runId, name: options.name, startedAt };
1487
- let acc = params.input;
1488
- for (const step of steps) {
1489
- if (signal.aborted) return abortRun(options.name, runId, startedAt, stepResults, signal);
1490
- onStepEvent?.({ type: "step_started", stepId: step.id });
1491
- const outcome = await runOneStep({
1492
- step,
1493
- acc,
1494
- ctx,
1495
- options,
1496
- stepResults,
1497
- runId,
1498
- name: options.name,
1499
- startedAt
1500
- });
1501
- const handled = handleStepOutcome(outcome, step, loop, onStepEvent);
1502
- if ("terminal" in handled) return handled.terminal;
1503
- acc = handled.acc;
1504
- }
1505
- const outputIssues = validateWorkflowSchema(options.outputSchema, acc);
1506
- if (outputIssues !== void 0) {
1507
- return assembleRun({
1508
- runId,
1509
- name: options.name,
1510
- status: "failed",
1511
- stepResults,
1512
- startedAt,
1513
- error: errToShape(new exports.WorkflowOutputError(options.name, outputIssues))
1514
- });
1515
- }
1516
- onStepEvent?.({ type: "workflow_completed" });
1517
- return assembleRun({
1518
- runId,
1519
- name: options.name,
1520
- status: "completed",
1521
- output: acc,
1522
- stepResults,
1523
- startedAt
1524
- });
1525
- }
1526
- async function executeWorkflow(options, steps, input, runOpts) {
1527
- const runId = runOpts?.runId ?? mintRunId();
1528
- const workflowId = options.workflowId ?? `wf-anon`;
1529
- const flight = acquireSingleFlight(workflowId, runId, options.name);
1530
- const startedAt = Date.now();
1531
- const signal = combineSignals(runOpts?.signal, flight.signal);
1532
- const runSpan = startWorkflowRunSpan({ workflowName: options.name, runId });
1533
- if (signal.aborted) {
1534
- flight.release();
1535
- runSpan.setAttribute("workflow.status", "cancelled");
1536
- runSpan.end();
1537
- return abortRun(options.name, runId, startedAt, [], signal);
1538
- }
1539
- const internal = runOpts;
1540
- const seededState = internal?.restoredState !== void 0 ? internal.restoredState : options.initialState;
1541
- const stateController = makeStateController(options, seededState);
1542
- const ctx = makeStepContext(runId, signal, stateController);
1543
- try {
1544
- const inputIssues = validateWorkflowSchema(options.inputSchema, input);
1545
- if (inputIssues !== void 0) {
1546
- return assembleRun({
1547
- runId,
1548
- name: options.name,
1549
- status: "failed",
1550
- stepResults: [],
1551
- startedAt,
1552
- error: errToShape(new exports.WorkflowInputError(options.name, inputIssues))
1553
- });
1554
- }
1555
- const stateIssues = seededState !== void 0 ? validateWorkflowSchema(options.stateSchema, seededState) : void 0;
1556
- if (stateIssues !== void 0) {
1557
- return assembleRun({
1558
- runId,
1559
- name: options.name,
1560
- status: "failed",
1561
- stepResults: [],
1562
- startedAt,
1563
- error: errToShape(new exports.WorkflowStateError(options.name, stateIssues))
1564
- });
1565
- }
1566
- return await runStepsLoop({
1567
- options,
1568
- steps,
1569
- input,
1570
- ctx,
1571
- runId,
1572
- startedAt,
1573
- signal,
1574
- ...internal?.initialStepResults !== void 0 ? { initialStepResults: internal.initialStepResults } : {},
1575
- ...internal?.onStepEvent !== void 0 ? { onStepEvent: internal.onStepEvent } : {}
1576
- });
1577
- } finally {
1578
- runSpan.end();
1579
- flight.release();
1580
- }
1581
- }
1582
- async function dispatchStep(step, input, ctx, options, prevStepResults) {
1583
- switch (step.kind) {
1584
- case "fn":
1585
- return runFnStep(step, input, ctx);
1586
- case "agent":
1587
- return runAgentStep(step, input, ctx);
1588
- case "parallel":
1589
- return runParallelStep(step, input, ctx, options, prevStepResults, dispatchStep);
1590
- case "branch":
1591
- return runBranchStep(step, input, ctx, options, prevStepResults, dispatchStep);
1592
- case "foreach":
1593
- return runForeachStep(step, input, ctx, options, prevStepResults, dispatchStep);
1594
- case "dowhile":
1595
- return runDowhileStep(step, input, ctx, options, prevStepResults, dispatchStep);
1596
- case "sleep":
1597
- return runSleepStep(step, input, ctx);
1598
- case "suspend":
1599
- throw new WorkflowSuspendedSentinel(void 0);
1600
- default: {
1601
- const _exhaustive = step;
1602
- throw new Error(`Unknown step kind: ${_exhaustive.kind}`);
1603
- }
1604
- }
1605
- }
1606
- async function saveSnapshot(p) {
1607
- const snapshot = {
1608
- _schemaVersion: 2,
1609
- // SE29 — carries `state`
1610
- runId: p.runId,
1611
- workflowName: p.workflowName,
1612
- currentStepId: p.currentStepId,
1613
- suspendedPayload: p.suspendedPayload,
1614
- stepResults: p.stepResults,
1615
- accumulatedInput: p.accumulatedInput,
1616
- ...p.state !== void 0 ? { state: p.state } : {},
1617
- suspendedAt: Date.now()
1618
- };
1619
- const store = getSnapshotStoreFor(p.options);
1620
- await store.save(snapshot);
1621
- }
1622
- async function resumeWorkflow(opts) {
1623
- const wfInternal = opts.workflow;
1624
- const options = wfInternal.__options;
1625
- const steps = wfInternal.__steps;
1626
- if (options === void 0 || steps === void 0) {
1627
- throw new Error("Workflow.resume requires an instance from Workflow.create().commit()");
1628
- }
1629
- const store = getSnapshotStoreFor(options);
1630
- const snapshot = await store.load(opts.runId);
1631
- if (snapshot === void 0) {
1632
- throw new exports.WorkflowSnapshotNotFoundError(opts.runId);
1633
- }
1634
- const stepIdx = steps.findIndex((s) => s.id === snapshot.currentStepId);
1635
- if (stepIdx < 0) {
1636
- throw new exports.WorkflowResumeStepNotFoundError(snapshot.currentStepId, snapshot.workflowName);
1637
- }
1638
- const suspendStep = steps[stepIdx];
1639
- if (suspendStep !== void 0 && suspendStep.kind === "suspend" && suspendStep.payloadSchema !== void 0) {
1640
- suspendStep.payloadSchema.parse(opts.payload);
1641
- }
1642
- const resumeInput = opts.payload !== void 0 ? opts.payload : snapshot.accumulatedInput;
1643
- const remainingSteps = steps.slice(stepIdx + 1);
1644
- await store.delete(opts.runId);
1645
- return executeWorkflow(options, remainingSteps, resumeInput, {
1646
- signal: opts.signal,
1647
- runId: opts.runId,
1648
- // M3 #62 — restore prior step outputs so the resumed run is not lossy (internal seam).
1649
- initialStepResults: snapshot.stepResults,
1650
- // SE29 — restore shared state (v2 snapshot). A v1 snapshot has no `state` →
1651
- // executeWorkflow falls back to `options.initialState`.
1652
- ...snapshot.state !== void 0 ? { restoredState: snapshot.state } : {}
1653
- });
1654
- }
1655
- var init_executor = __esm({
1656
- "src/internal/workflow/executor.ts"() {
1657
- init_workflow();
1658
- init_ctx();
1659
- init_error_shape();
1660
- init_executor_helpers();
1661
- init_run_id();
1662
- init_single_flight();
1663
- init_snapshot_store();
1664
- init_step_agent();
1665
- init_step_branch();
1666
- init_step_dowhile();
1667
- init_step_fn();
1668
- init_step_foreach();
1669
- init_step_parallel();
1670
- init_step_sleep();
1671
- init_telemetry();
1672
- }
90
+ Object.defineProperty(exports, "WorkflowStateError", {
91
+ enumerable: true,
92
+ get: function () { return chunkBWT67BI4_cjs.WorkflowStateError; }
1673
93
  });
1674
-
1675
- // src/types/run-events.ts
1676
- function emitRunEvent(sink, event) {
1677
- if (sink === void 0) return;
1678
- try {
1679
- sink(event);
1680
- } catch {
1681
- }
1682
- }
1683
- var init_run_events = __esm({
1684
- "src/types/run-events.ts"() {
1685
- }
94
+ Object.defineProperty(exports, "__resetSnapshotStoresForTests", {
95
+ enumerable: true,
96
+ get: function () { return chunkBWT67BI4_cjs.__resetSnapshotStoresForTests; }
1686
97
  });
1687
-
1688
- // src/types/task.ts
1689
- function isValidTaskId(id, allowReserved) {
1690
- if (!TASK_ID_GRAMMAR.test(id)) return false;
1691
- if (allowReserved) return true;
1692
- for (const prefix of RESERVED_PREFIXES) {
1693
- if (id.startsWith(prefix)) return false;
1694
- }
1695
- return true;
1696
- }
1697
- var TASK_ID_GRAMMAR, RESERVED_PREFIXES;
1698
- var init_task = __esm({
1699
- "src/types/task.ts"() {
1700
- TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;
1701
- RESERVED_PREFIXES = ["wf-", "b-", "cron-"];
1702
- }
1703
- });
1704
-
1705
- // src/internal/task/ring-buffer.ts
1706
- var RingBuffer;
1707
- var init_ring_buffer = __esm({
1708
- "src/internal/task/ring-buffer.ts"() {
1709
- RingBuffer = class {
1710
- constructor(cap) {
1711
- this.cap = cap;
1712
- if (!Number.isInteger(cap) || cap < 1) {
1713
- throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);
1714
- }
1715
- }
1716
- cap;
1717
- buf = [];
1718
- truncated = false;
1719
- push(item) {
1720
- if (this.buf.length >= this.cap) {
1721
- this.buf.shift();
1722
- this.truncated = true;
1723
- }
1724
- this.buf.push(item);
1725
- }
1726
- drain() {
1727
- return { items: this.buf.slice(), truncated: this.truncated };
1728
- }
1729
- size() {
1730
- return this.buf.length;
1731
- }
1732
- wasTruncated() {
1733
- return this.truncated;
1734
- }
1735
- };
1736
- }
1737
- });
1738
- function assertValidIdForStore(id) {
1739
- if (!isValidTaskId(
1740
- id,
1741
- /* allowReserved */
1742
- true
1743
- )) {
1744
- throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);
1745
- }
1746
- }
1747
- function terminalTimestamp(h) {
1748
- if (h.state === "finished") return h.finishedAt;
1749
- if (h.state === "error") return h.erroredAt;
1750
- if (h.state === "cancelled") return h.cancelledAt;
1751
- return void 0;
1752
- }
1753
- function isTerminal(state2) {
1754
- return state2 === "finished" || state2 === "error" || state2 === "cancelled";
1755
- }
1756
- function matchesState(h, filter) {
1757
- if (filter.state === void 0) return true;
1758
- const states = Array.isArray(filter.state) ? filter.state : [filter.state];
1759
- return states.includes(h.state);
1760
- }
1761
- function matchesKind(h, filter) {
1762
- if (filter.kind === void 0) return true;
1763
- const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];
1764
- return kinds.includes(h.kind);
1765
- }
1766
- function matchesTime(h, filter) {
1767
- if (filter.submittedAfter !== void 0 && h.submittedAt <= filter.submittedAfter) return false;
1768
- if (filter.submittedBefore !== void 0 && h.submittedAt >= filter.submittedBefore) return false;
1769
- return true;
1770
- }
1771
- function matchesFilter(h, filter) {
1772
- return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);
1773
- }
1774
- function applyFilter(values, filter) {
1775
- const limit = filter.limit ?? DEFAULT_LIST_LIMIT;
1776
- const out = [];
1777
- for (const h of values) {
1778
- if (matchesFilter(h, filter)) {
1779
- out.push(h);
1780
- if (out.length >= limit) break;
1781
- }
1782
- }
1783
- return out;
1784
- }
1785
- function getTaskStoreFor(options) {
1786
- if (options.backend === "memory") return new InMemoryTaskStore();
1787
- return new JsonFileTaskStore(options.dir);
1788
- }
1789
- var JSON_LOAD_CAP, DEFAULT_LIST_LIMIT, InMemoryTaskStore, JsonFileTaskStore;
1790
- var init_store = __esm({
1791
- "src/internal/task/store.ts"() {
1792
- init_errors();
1793
- init_task();
1794
- init_atomic_write();
1795
- JSON_LOAD_CAP = 256;
1796
- DEFAULT_LIST_LIMIT = 100;
1797
- InMemoryTaskStore = class {
1798
- map = /* @__PURE__ */ new Map();
1799
- async insert(handle) {
1800
- assertValidIdForStore(handle.id);
1801
- this.map.set(handle.id, handle);
1802
- }
1803
- async update(id, mutate) {
1804
- assertValidIdForStore(id);
1805
- const existing = this.map.get(id);
1806
- if (existing === void 0) return void 0;
1807
- const next = mutate(existing);
1808
- this.map.set(id, next);
1809
- return next;
1810
- }
1811
- async get(id) {
1812
- assertValidIdForStore(id);
1813
- return this.map.get(id);
1814
- }
1815
- async list(filter) {
1816
- return applyFilter(this.map.values(), filter);
1817
- }
1818
- async delete(id) {
1819
- assertValidIdForStore(id);
1820
- return this.map.delete(id);
1821
- }
1822
- async evictTerminalOlderThan(epochMs) {
1823
- let count = 0;
1824
- for (const [id, h] of this.map.entries()) {
1825
- if (!isTerminal(h.state)) continue;
1826
- const ts = terminalTimestamp(h);
1827
- if (ts !== void 0 && ts < epochMs) {
1828
- this.map.delete(id);
1829
- count++;
1830
- }
1831
- }
1832
- return count;
1833
- }
1834
- };
1835
- JsonFileTaskStore = class {
1836
- constructor(dir) {
1837
- this.dir = dir;
1838
- try {
1839
- fs.mkdirSync(dir, { recursive: true });
1840
- } catch (err) {
1841
- if (err.code !== "EEXIST") throw err;
1842
- }
1843
- }
1844
- dir;
1845
- filePath(id) {
1846
- return path.join(this.dir, `${id}.json`);
1847
- }
1848
- async insert(handle) {
1849
- assertValidIdForStore(handle.id);
1850
- await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));
1851
- }
1852
- async update(id, mutate) {
1853
- assertValidIdForStore(id);
1854
- const existing = await this.get(id);
1855
- if (existing === void 0) return void 0;
1856
- const next = mutate(existing);
1857
- await atomicWriteText(this.filePath(id), JSON.stringify(next));
1858
- return next;
1859
- }
1860
- async get(id) {
1861
- assertValidIdForStore(id);
1862
- try {
1863
- const raw = await promises.readFile(this.filePath(id), "utf8");
1864
- return JSON.parse(raw);
1865
- } catch (err) {
1866
- const code = err.code;
1867
- if (code === "ENOENT") return void 0;
1868
- process.stderr.write(`[task-store] failed to read ${id}: ${err.message}
1869
- `);
1870
- return void 0;
1871
- }
1872
- }
1873
- async list(filter) {
1874
- let entries;
1875
- try {
1876
- entries = fs.readdirSync(this.dir);
1877
- } catch (err) {
1878
- if (err.code === "ENOENT") return [];
1879
- throw err;
1880
- }
1881
- const candidates = entries.filter((name) => name.endsWith(".json") && !name.includes(".tmp")).slice(0, JSON_LOAD_CAP);
1882
- const loaded = await Promise.all(
1883
- candidates.map(async (name) => {
1884
- const id = name.slice(0, -".json".length);
1885
- if (!isValidTaskId(id, true)) return void 0;
1886
- return this.get(id);
1887
- })
1888
- );
1889
- const handles = loaded.filter((h) => h !== void 0);
1890
- return applyFilter(handles, filter);
1891
- }
1892
- async delete(id) {
1893
- assertValidIdForStore(id);
1894
- try {
1895
- await promises.unlink(this.filePath(id));
1896
- return true;
1897
- } catch (err) {
1898
- if (err.code === "ENOENT") return false;
1899
- throw err;
1900
- }
1901
- }
1902
- async evictTerminalOlderThan(epochMs) {
1903
- const handles = await this.list({ state: ["finished", "error", "cancelled"], limit: 256 });
1904
- let count = 0;
1905
- for (const h of handles) {
1906
- const ts = terminalTimestamp(h);
1907
- if (ts !== void 0 && ts < epochMs) {
1908
- if (await this.delete(h.id)) count++;
1909
- }
1910
- }
1911
- return count;
1912
- }
1913
- };
1914
- }
1915
- });
1916
-
1917
- // src/internal/task/subscribe.ts
1918
- function isTerminalEvent(event) {
1919
- return event.type === "finished" || event.type === "errored" || event.type === "cancelled";
1920
- }
1921
- function drainBuffered(buffer) {
1922
- const { items, truncated } = buffer.drain();
1923
- const queue = items.slice();
1924
- if (truncated && queue.length > 0) {
1925
- const first = queue[0];
1926
- if (first !== void 0 && first.type === "submitted") {
1927
- queue[0] = { ...first, truncated: true };
1928
- }
1929
- }
1930
- return queue;
1931
- }
1932
- function buildSubscribe(deps) {
1933
- return function subscribe2(id) {
1934
- if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);
1935
- const buffer = deps.getBuffer(id);
1936
- if (buffer === void 0) throw new TaskNotFoundError(id);
1937
- return {
1938
- [Symbol.asyncIterator]() {
1939
- return new TaskIterator(buffer, id, deps);
1940
- }
1941
- };
1942
- };
1943
- }
1944
- var TaskIterator;
1945
- var init_subscribe = __esm({
1946
- "src/internal/task/subscribe.ts"() {
1947
- init_errors();
1948
- init_task();
1949
- TaskIterator = class {
1950
- constructor(buffer, id, deps) {
1951
- this.id = id;
1952
- this.deps = deps;
1953
- this.queue = drainBuffered(buffer);
1954
- this.callback = (e) => this.deliver(e);
1955
- deps.getOrCreateSubscriberSet(id).add(this.callback);
1956
- }
1957
- id;
1958
- deps;
1959
- queue;
1960
- pendingResolve;
1961
- done = false;
1962
- callback;
1963
- deliver(e) {
1964
- if (this.done) return;
1965
- if (this.pendingResolve !== void 0) {
1966
- const r = this.pendingResolve;
1967
- this.pendingResolve = void 0;
1968
- r({ value: e, done: false });
1969
- } else {
1970
- this.queue.push(e);
1971
- }
1972
- }
1973
- cleanup() {
1974
- if (this.done) return;
1975
- this.done = true;
1976
- this.deps.removeSubscriber(this.id, this.callback);
1977
- if (this.pendingResolve !== void 0) {
1978
- const r = this.pendingResolve;
1979
- this.pendingResolve = void 0;
1980
- r({ value: void 0, done: true });
1981
- }
1982
- }
1983
- dequeue() {
1984
- const event = this.queue.shift();
1985
- if (event === void 0) return void 0;
1986
- if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());
1987
- return { value: event, done: false };
1988
- }
1989
- next() {
1990
- if (this.done) return Promise.resolve({ value: void 0, done: true });
1991
- const queued = this.dequeue();
1992
- if (queued !== void 0) return Promise.resolve(queued);
1993
- return new Promise((resolve2) => {
1994
- this.pendingResolve = resolve2;
1995
- });
1996
- }
1997
- return() {
1998
- this.cleanup();
1999
- return Promise.resolve({ value: void 0, done: true });
2000
- }
2001
- };
2002
- }
2003
- });
2004
-
2005
- // src/internal/task/task-run-event-bridge.ts
2006
- function taskEventToRunEvent(event, taskId, kind) {
2007
- switch (event.type) {
2008
- case "started":
2009
- return { type: "task_started", taskId, description: kind };
2010
- case "progress":
2011
- return { type: "task_updated", taskId, status: "progress" };
2012
- case "finished":
2013
- return { type: "task_completed", taskId, status: "completed" };
2014
- case "errored":
2015
- return { type: "task_completed", taskId, status: "failed" };
2016
- case "cancelled":
2017
- return { type: "task_completed", taskId, status: "stopped" };
2018
- default:
2019
- return void 0;
2020
- }
2021
- }
2022
- var init_task_run_event_bridge = __esm({
2023
- "src/internal/task/task-run-event-bridge.ts"() {
2024
- }
2025
- });
2026
-
2027
- // src/internal/task/telemetry.ts
2028
- function startTaskSubmitSpan(info) {
2029
- const tracer = getTracer(TRACER_NAME2);
2030
- if (tracer === void 0) return noopSpan;
2031
- return tracer.startSpan("task.submit", {
2032
- attributes: {
2033
- "task.id": info.taskId,
2034
- "task.kind": info.kind
2035
- }
2036
- });
2037
- }
2038
- function startTaskTransitionSpan(info) {
2039
- const tracer = getTracer(TRACER_NAME2);
2040
- if (tracer === void 0) return noopSpan;
2041
- return tracer.startSpan("task.transition", {
2042
- attributes: {
2043
- "task.id": info.taskId,
2044
- "task.state.from": info.from,
2045
- "task.state.to": info.to
2046
- }
2047
- });
2048
- }
2049
- function startTaskCancelSpan(info) {
2050
- const tracer = getTracer(TRACER_NAME2);
2051
- if (tracer === void 0) return noopSpan;
2052
- return tracer.startSpan("task.cancel", {
2053
- attributes: {
2054
- "task.id": info.taskId,
2055
- "task.cancel.via": info.via,
2056
- ...info.reason !== void 0 ? { "task.cancel.reason": info.reason } : {}
2057
- }
2058
- });
2059
- }
2060
- var TRACER_NAME2;
2061
- var init_telemetry2 = __esm({
2062
- "src/internal/task/telemetry.ts"() {
2063
- init_tracer_loader();
2064
- TRACER_NAME2 = "@theokit/sdk/task";
2065
- }
2066
- });
2067
-
2068
- // src/internal/task/registry.ts
2069
- var registry_exports = {};
2070
- __export(registry_exports, {
2071
- __getSubscribersCountForTests: () => __getSubscribersCountForTests,
2072
- __resetTaskRegistryForTests: () => __resetTaskRegistryForTests,
2073
- cancel: () => cancel,
2074
- configure: () => configure,
2075
- get: () => get,
2076
- list: () => list,
2077
- submit: () => submit,
2078
- subscribe: () => subscribe
2079
- });
2080
- function buildState(opts) {
2081
- const store = opts.store === void 0 ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);
2082
- return {
2083
- store,
2084
- semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),
2085
- aborters: /* @__PURE__ */ new Map(),
2086
- buffers: /* @__PURE__ */ new Map(),
2087
- subscribers: /* @__PURE__ */ new Map(),
2088
- retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,
2089
- firstSubmitSeen: false
2090
- };
2091
- }
2092
- function __resetTaskRegistryForTests() {
2093
- if (state.evictTimer !== void 0) clearInterval(state.evictTimer);
2094
- state = buildState({});
2095
- }
2096
- function __getSubscribersCountForTests(taskId) {
2097
- return state.subscribers.get(taskId)?.size ?? 0;
2098
- }
2099
- function configure(opts) {
2100
- if (state.firstSubmitSeen) {
2101
- process.stderr.write(
2102
- "[task] configure() ignored \u2014 registry already in use; reset via __resetTaskRegistryForTests()\n"
2103
- );
2104
- return;
2105
- }
2106
- if (state.evictTimer !== void 0) clearInterval(state.evictTimer);
2107
- state = buildState(opts);
2108
- }
2109
- function emitToSubscribers(taskId, event) {
2110
- const buffer = state.buffers.get(taskId);
2111
- if (buffer !== void 0) buffer.push(event);
2112
- const subs = state.subscribers.get(taskId);
2113
- if (subs === void 0) return;
2114
- for (const cb of subs) {
2115
- try {
2116
- cb(event);
2117
- } catch (err) {
2118
- process.stderr.write(`[task] subscriber threw: ${err.message}
2119
- `);
2120
- }
2121
- }
2122
- }
2123
- async function safeUpdate(taskId, mutate) {
2124
- try {
2125
- return await state.store.update(taskId, mutate);
2126
- } catch (err) {
2127
- process.stderr.write(`[task] store.update failed for ${taskId}: ${err.message}
2128
- `);
2129
- return void 0;
2130
- }
2131
- }
2132
- function startEvictTimerIfNeeded() {
2133
- if (state.evictTimer !== void 0) return;
2134
- state.evictTimer = setInterval(() => {
2135
- const cutoff = Date.now() - state.retentionMs;
2136
- void state.store.evictTerminalOlderThan(cutoff).then((count) => {
2137
- if (count === 0) return;
2138
- for (const id of state.buffers.keys()) {
2139
- void state.store.get(id).then((h) => {
2140
- if (h === void 0) {
2141
- state.buffers.delete(id);
2142
- state.subscribers.delete(id);
2143
- state.aborters.delete(id);
2144
- }
2145
- });
2146
- }
2147
- }).catch(() => {
2148
- });
2149
- }, EVICTION_INTERVAL_MS).unref();
2150
- }
2151
- function buildSubmittedEvent(handle) {
2152
- return {
2153
- type: "submitted",
2154
- taskId: handle.id,
2155
- kind: handle.kind,
2156
- submittedAt: handle.submittedAt,
2157
- ...handle.meta !== void 0 ? { meta: handle.meta } : {}
2158
- };
2159
- }
2160
- async function shortCircuitAborted(handle, signal) {
2161
- const cancelled = {
2162
- ...handle,
2163
- state: "cancelled",
2164
- cancelledAt: Date.now()
2165
- };
2166
- await state.store.insert(cancelled);
2167
- state.buffers.set(handle.id, new RingBuffer(RING_CAP));
2168
- emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));
2169
- emitToSubscribers(handle.id, {
2170
- type: "cancelled",
2171
- taskId: handle.id,
2172
- cancelledAt: cancelled.cancelledAt ?? Date.now(),
2173
- reason: signal.reason instanceof Error ? signal.reason.message : "pre-aborted"
2174
- });
2175
- return cancelled;
2176
- }
2177
- async function transition(taskId, next, patch) {
2178
- const before = await state.store.get(taskId);
2179
- const span = startTaskTransitionSpan({
2180
- taskId,
2181
- from: before?.state ?? "unknown",
2182
- to: next
2183
- });
2184
- try {
2185
- await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));
2186
- } finally {
2187
- span.end();
2188
- }
2189
- }
2190
- async function buildAndInsertQueued(internal, resolvedId) {
2191
- const submittedAt = Date.now();
2192
- const handle = {
2193
- id: resolvedId,
2194
- kind: internal.kind,
2195
- state: "queued",
2196
- submittedAt,
2197
- ...internal.meta !== void 0 ? { meta: internal.meta } : {}
2198
- };
2199
- await state.store.insert(handle);
2200
- state.buffers.set(resolvedId, new RingBuffer(RING_CAP));
2201
- emitToSubscribers(resolvedId, buildSubmittedEvent(handle));
2202
- return handle;
2203
- }
2204
- function resolveIdInternal(internal) {
2205
- if (internal.id === void 0) return crypto.randomUUID();
2206
- if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {
2207
- throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);
2208
- }
2209
- return internal.id;
2210
- }
2211
- async function runWorkAndFinalize(taskId, aborter, work) {
2212
- const ctx = {
2213
- signal: aborter.signal,
2214
- emit(payload) {
2215
- void checkCancelRequestedAt(taskId, aborter);
2216
- emitToSubscribers(taskId, {
2217
- type: "progress",
2218
- taskId,
2219
- at: Date.now(),
2220
- payload
2221
- });
2222
- }
2223
- };
2224
- try {
2225
- const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));
2226
- if (aborter.signal.aborted) {
2227
- const cancelledAt = Date.now();
2228
- await transition(taskId, "cancelled", { cancelledAt });
2229
- emitToSubscribers(taskId, { type: "cancelled", taskId, cancelledAt });
2230
- return;
2231
- }
2232
- const finishedAt = Date.now();
2233
- await transition(taskId, "finished", { finishedAt, result });
2234
- emitToSubscribers(taskId, { type: "finished", taskId, finishedAt, result });
2235
- } catch (err) {
2236
- if (aborter.signal.aborted) {
2237
- const cancelledAt = Date.now();
2238
- await transition(taskId, "cancelled", { cancelledAt });
2239
- emitToSubscribers(taskId, { type: "cancelled", taskId, cancelledAt });
2240
- return;
2241
- }
2242
- const erroredAt = Date.now();
2243
- const error = err instanceof Error ? { code: err.code ?? "work_threw", message: err.message } : { code: "work_threw", message: String(err) };
2244
- await transition(taskId, "error", { erroredAt, error });
2245
- emitToSubscribers(taskId, { type: "errored", taskId, erroredAt, error });
2246
- }
2247
- }
2248
- async function checkCancelRequestedAt(taskId, aborter) {
2249
- if (aborter.signal.aborted) return;
2250
- try {
2251
- const handle = await state.store.get(taskId);
2252
- if (handle?.cancelRequested === true) {
2253
- aborter.abort("cancelRequested");
2254
- }
2255
- } catch {
2256
- }
2257
- }
2258
- async function acquireSlot() {
2259
- if (reentryAls.getStore() === true) {
2260
- return () => {
2261
- };
2262
- }
2263
- return state.semaphore.acquire();
2264
- }
2265
- async function submit(internal) {
2266
- state.firstSubmitSeen = true;
2267
- startEvictTimerIfNeeded();
2268
- const resolvedId = resolveIdInternal(internal);
2269
- if (internal.onRunEvent !== void 0) {
2270
- const sink = internal.onRunEvent;
2271
- const kind = internal.kind;
2272
- const subs = state.subscribers.get(resolvedId) ?? /* @__PURE__ */ new Set();
2273
- subs.add((e) => {
2274
- const runEvent = taskEventToRunEvent(e, resolvedId, kind);
2275
- if (runEvent !== void 0) emitRunEvent(sink, runEvent);
2276
- });
2277
- state.subscribers.set(resolvedId, subs);
2278
- }
2279
- const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });
2280
- const existing = await state.store.get(resolvedId);
2281
- if (existing !== void 0) {
2282
- submitSpan.end();
2283
- return existing;
2284
- }
2285
- const queuedHandle = await buildAndInsertQueued(internal, resolvedId);
2286
- submitSpan.end();
2287
- if (internal.signal?.aborted === true) {
2288
- return shortCircuitAborted(queuedHandle, internal.signal);
2289
- }
2290
- const aborter = new AbortController();
2291
- state.aborters.set(resolvedId, aborter);
2292
- if (internal.signal !== void 0) {
2293
- internal.signal.addEventListener("abort", () => aborter.abort(internal.signal?.reason), {
2294
- once: true
2295
- });
2296
- }
2297
- const release = await acquireSlot();
2298
- void (async () => {
2299
- try {
2300
- await checkCancelRequestedAt(resolvedId, aborter);
2301
- if (aborter.signal.aborted) {
2302
- const cancelledAt = Date.now();
2303
- await transition(resolvedId, "cancelled", { cancelledAt });
2304
- emitToSubscribers(resolvedId, { type: "cancelled", taskId: resolvedId, cancelledAt });
2305
- return;
2306
- }
2307
- const startedAt = Date.now();
2308
- await transition(resolvedId, "running", { startedAt });
2309
- emitToSubscribers(resolvedId, { type: "started", taskId: resolvedId, startedAt });
2310
- await runWorkAndFinalize(resolvedId, aborter, internal.work);
2311
- } finally {
2312
- release();
2313
- state.aborters.delete(resolvedId);
2314
- }
2315
- })();
2316
- return queuedHandle;
2317
- }
2318
- async function list(filter = {}) {
2319
- return state.store.list(filter);
2320
- }
2321
- async function get(id) {
2322
- if (!isValidTaskId(id, true)) return void 0;
2323
- return state.store.get(id);
2324
- }
2325
- async function cancel(id, reason) {
2326
- if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };
2327
- const handle = await state.store.get(id);
2328
- if (handle === void 0) return { cancelled: false, alreadyTerminal: false };
2329
- if (handle.state === "finished" || handle.state === "error" || handle.state === "cancelled") {
2330
- return { cancelled: false, alreadyTerminal: true };
2331
- }
2332
- const span = startTaskCancelSpan({
2333
- taskId: id,
2334
- ...reason !== void 0 ? { reason } : {},
2335
- via: "api"
2336
- });
2337
- try {
2338
- return await cancelInternal(id, handle.state, reason);
2339
- } finally {
2340
- span.end();
2341
- }
2342
- }
2343
- async function cancelInternal(id, currentState, reason) {
2344
- if (currentState === "queued") {
2345
- const cancelledAt = Date.now();
2346
- await transition(id, "cancelled", { cancelledAt });
2347
- emitToSubscribers(id, {
2348
- type: "cancelled",
2349
- taskId: id,
2350
- cancelledAt,
2351
- ...reason !== void 0 ? { reason } : {}
2352
- });
2353
- state.aborters.delete(id);
2354
- return { cancelled: true, alreadyTerminal: false };
2355
- }
2356
- const aborter = state.aborters.get(id);
2357
- if (aborter !== void 0) aborter.abort(reason ?? "cancelled");
2358
- return { cancelled: true, alreadyTerminal: false };
2359
- }
2360
- var DEFAULT_CONCURRENCY, DEFAULT_RETENTION_MS, EVICTION_INTERVAL_MS, RING_CAP, reentryAls, state, subscribe;
2361
- var init_registry = __esm({
2362
- "src/internal/task/registry.ts"() {
2363
- init_errors();
2364
- init_run_events();
2365
- init_task();
2366
- init_async_semaphore();
2367
- init_ring_buffer();
2368
- init_store();
2369
- init_subscribe();
2370
- init_task_run_event_bridge();
2371
- init_telemetry2();
2372
- DEFAULT_CONCURRENCY = 8;
2373
- DEFAULT_RETENTION_MS = 60 * 60 * 1e3;
2374
- EVICTION_INTERVAL_MS = 5 * 60 * 1e3;
2375
- RING_CAP = 64;
2376
- reentryAls = new async_hooks.AsyncLocalStorage();
2377
- state = buildState({});
2378
- subscribe = buildSubscribe({
2379
- getBuffer: (id) => state.buffers.get(id),
2380
- getOrCreateSubscriberSet: (id) => {
2381
- let subs = state.subscribers.get(id);
2382
- if (subs === void 0) {
2383
- subs = /* @__PURE__ */ new Set();
2384
- state.subscribers.set(id, subs);
2385
- }
2386
- return subs;
2387
- },
2388
- removeSubscriber: (id, cb) => {
2389
- const set = state.subscribers.get(id);
2390
- set?.delete(cb);
2391
- if (set !== void 0 && set.size === 0) state.subscribers.delete(id);
2392
- }
2393
- });
2394
- }
2395
- });
2396
- var PersistenceSchema = zod.z.object({
2397
- backend: zod.z.enum(["memory", "json"]),
2398
- dir: zod.z.string().optional()
2399
- }).refine((p) => p.backend !== "json" || typeof p.dir === "string" && p.dir.length > 0, {
2400
- message: 'persistence.dir is required when backend = "json"'
2401
- }).optional();
2402
-
2403
- // src/internal/security/path-guard.ts
2404
- init_errors();
2405
- var PathTraversalError = class extends ConfigurationError {
2406
- name = "PathTraversalError";
2407
- constructor(input, resolvedPath) {
2408
- super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
2409
- code: "path_traversal"
2410
- });
2411
- }
2412
- };
2413
- function rejectNulAndControlChars(input, role) {
2414
- for (let i = 0; i < input.length; i++) {
2415
- const code = input.charCodeAt(i);
2416
- if (code === 0 || code >= 1 && code <= 31 || code === 127) {
2417
- const label = code === 0 ? "<nul-byte>" : `<control-char-0x${code.toString(16)}>`;
2418
- throw new PathTraversalError(`${role}: ${input}`, label);
2419
- }
2420
- }
2421
- }
2422
- var IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\-_]*$/i;
2423
- function sanitizeIdentifier(input, options) {
2424
- const maxLen = options?.maxLen;
2425
- if (input.length === 0 || input.length > maxLen) {
2426
- throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
2427
- code: "invalid_identifier"
2428
- });
2429
- }
2430
- rejectNulAndControlChars(input, "identifier");
2431
- if (!IDENTIFIER_PATTERN.test(input)) {
2432
- throw new ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
2433
- code: "invalid_identifier"
2434
- });
2435
- }
2436
- return input.toLowerCase();
2437
- }
2438
-
2439
- // src/internal/workflow/event-stream.ts
2440
- function createEventStream() {
2441
- const buffer = [];
2442
- const waiters = [];
2443
- let ended = false;
2444
- const stream = {
2445
- push(event) {
2446
- if (ended) return;
2447
- const waiter = waiters.shift();
2448
- if (waiter !== void 0) waiter({ value: event, done: false });
2449
- else buffer.push(event);
2450
- },
2451
- end() {
2452
- if (ended) return;
2453
- ended = true;
2454
- for (const waiter of waiters.splice(0)) waiter({ value: void 0, done: true });
2455
- },
2456
- next() {
2457
- const buffered = buffer.shift();
2458
- if (buffered !== void 0) return Promise.resolve({ value: buffered, done: false });
2459
- if (ended) return Promise.resolve({ value: void 0, done: true });
2460
- return new Promise((resolve2) => waiters.push(resolve2));
2461
- },
2462
- // `for await` calls return() on break/throw — close early so events stop
2463
- // buffering in memory for a consumer that stopped iterating.
2464
- return() {
2465
- stream.end();
2466
- buffer.length = 0;
2467
- return Promise.resolve({ value: void 0, done: true });
2468
- },
2469
- [Symbol.asyncIterator]() {
2470
- return stream;
2471
- }
2472
- };
2473
- return stream;
2474
- }
2475
- function toJsonSchema(schema, options = { unrepresentable: "any" }) {
2476
- return zod.toJSONSchema(schema, options);
2477
- }
2478
-
2479
- // src/workflow.ts
2480
- init_workflow();
2481
- init_snapshot_store();
2482
- init_workflow();
2483
- var RetryPolicySchema = zod.z.object({
2484
- // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].
2485
- maxAttempts: zod.z.number().int("retry.maxAttempts must be integer").min(1, "retry.maxAttempts must be >= 1").max(20, "retry.maxAttempts must be <= 20"),
2486
- initialBackoffMs: zod.z.number().int().min(0).optional(),
2487
- backoffCoefficient: zod.z.number().min(1).optional(),
2488
- maximumBackoffMs: zod.z.number().int().min(0).optional(),
2489
- nonRetryableErrors: zod.z.array(zod.z.string()).optional()
2490
- });
2491
- var WorkflowOptionsSchema = zod.z.object({
2492
- name: zod.z.string().min(1).max(128),
2493
- persistence: PersistenceSchema,
2494
- // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot
2495
- // silently drop them (create() passes the ORIGINAL options today, but the
2496
- // schema is also the documentation of the shape).
2497
- inputSchema: zod.z.custom().optional(),
2498
- outputSchema: zod.z.custom().optional()
2499
- });
2500
- var WorkflowBuilder = class {
2501
- /** @internal */
2502
- constructor(options) {
2503
- this.options = options;
2504
- }
2505
- options;
2506
- _steps = [];
2507
- _committed = false;
2508
- /** @internal — only the executor reads this. */
2509
- get __steps() {
2510
- return this._steps;
2511
- }
2512
- // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.
2513
- then(step) {
2514
- this.assertNotCommitted();
2515
- validateStepId(step.id);
2516
- this._steps.push(step);
2517
- return this;
2518
- }
2519
- parallel(branches, opts) {
2520
- this.assertNotCommitted();
2521
- const id = opts?.id ?? `parallel_${this._steps.length}`;
2522
- validateStepId(id);
2523
- for (const branch of branches) {
2524
- for (const inner of branch) validateStepId(inner.id);
2525
- }
2526
- const step = {
2527
- kind: "parallel",
2528
- id,
2529
- branches,
2530
- ...opts?.concurrency !== void 0 ? { concurrency: opts.concurrency } : {},
2531
- ...opts?.errorPolicy !== void 0 ? { errorPolicy: opts.errorPolicy } : {}
2532
- };
2533
- this._steps.push(step);
2534
- return this;
2535
- }
2536
- branch(predicates, opts) {
2537
- this.assertNotCommitted();
2538
- const id = opts?.id ?? `branch_${this._steps.length}`;
2539
- validateStepId(id);
2540
- const step = {
2541
- kind: "branch",
2542
- id,
2543
- predicates,
2544
- ...opts?.fallback !== void 0 ? { fallback: opts.fallback } : {}
2545
- };
2546
- this._steps.push(step);
2547
- return this;
2548
- }
2549
- foreach(iterableFrom, step, opts) {
2550
- this.assertNotCommitted();
2551
- const id = opts?.id ?? `foreach_${this._steps.length}`;
2552
- validateStepId(id);
2553
- validateStepId(iterableFrom);
2554
- validateStepId(step.id);
2555
- const node = {
2556
- kind: "foreach",
2557
- id,
2558
- iterableFrom,
2559
- step,
2560
- ...opts?.concurrency !== void 0 ? { concurrency: opts.concurrency } : {}
2561
- };
2562
- this._steps.push(node);
2563
- return this;
2564
- }
2565
- dowhile(step, condFn, opts) {
2566
- this.assertNotCommitted();
2567
- const id = opts?.id ?? `dowhile_${this._steps.length}`;
2568
- validateStepId(id);
2569
- validateStepId(step.id);
2570
- const node = {
2571
- kind: "dowhile",
2572
- id,
2573
- step,
2574
- condFn,
2575
- ...opts?.maxIterations !== void 0 ? { maxIterations: opts.maxIterations } : {}
2576
- };
2577
- this._steps.push(node);
2578
- return this;
2579
- }
2580
- sleep(durationMs, id) {
2581
- this.assertNotCommitted();
2582
- const stepId = id ?? `sleep_${this._steps.length}`;
2583
- validateStepId(stepId);
2584
- if (!Number.isFinite(durationMs) || durationMs < 0) {
2585
- throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);
2586
- }
2587
- const step = { kind: "sleep", id: stepId, durationMs };
2588
- this._steps.push(step);
2589
- return this;
2590
- }
2591
- suspend(opts) {
2592
- this.assertNotCommitted();
2593
- const id = opts?.id ?? `suspend_${this._steps.length}`;
2594
- validateStepId(id);
2595
- const step = {
2596
- kind: "suspend",
2597
- id,
2598
- ...opts?.payloadSchema !== void 0 ? { payloadSchema: opts.payloadSchema } : {}
2599
- };
2600
- this._steps.push(step);
2601
- return this;
2602
- }
2603
- commit() {
2604
- this.assertNotCommitted();
2605
- this.validateUniqueIds();
2606
- this._committed = true;
2607
- const workflowId = `wf-${mintShortId()}`;
2608
- return new Workflow({ ...this.options, workflowId }, [...this._steps]);
2609
- }
2610
- validateUniqueIds() {
2611
- const seen = /* @__PURE__ */ new Set();
2612
- walkStepsValidating(this._steps, seen);
2613
- }
2614
- assertNotCommitted() {
2615
- if (this._committed) {
2616
- throw new Error("Workflow already committed; create a fresh Workflow.create(...) call.");
2617
- }
2618
- }
2619
- };
2620
- var Workflow = class {
2621
- /** @internal */
2622
- constructor(_options, _steps) {
2623
- this._options = _options;
2624
- this._steps = _steps;
2625
- }
2626
- _options;
2627
- _steps;
2628
- /** @internal — only the executor reads these. */
2629
- get __options() {
2630
- return this._options;
2631
- }
2632
- /** @internal */
2633
- get __steps() {
2634
- return this._steps;
2635
- }
2636
- /**
2637
- * Construct a workflow builder. Validate options via Zod and return a
2638
- * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the
2639
- * immutable `Workflow`.
2640
- */
2641
- static create(options) {
2642
- WorkflowOptionsSchema.parse(options);
2643
- return new WorkflowBuilder(options);
2644
- }
2645
- /**
2646
- * Run this workflow with the given input. Returns a populated
2647
- * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via
2648
- * `run.status === "failed"`.
2649
- */
2650
- async run(input, opts) {
2651
- const { executeWorkflow: executeWorkflow2 } = await Promise.resolve().then(() => (init_executor(), executor_exports));
2652
- const result = await executeWorkflow2(this._options, this._steps, input, opts);
2653
- if (opts?.task !== void 0) {
2654
- const { submit: taskSubmit } = await Promise.resolve().then(() => (init_registry(), registry_exports));
2655
- const taskOpts = opts.task === true ? {} : opts.task;
2656
- const id = taskOpts.id ?? `wf-${result.id}`;
2657
- await taskSubmit({
2658
- kind: "workflow",
2659
- work: async (ctx) => {
2660
- ctx.emit({ status: result.status, runId: result.id });
2661
- return { status: result.status, runId: result.id, output: result.output };
2662
- },
2663
- id,
2664
- meta: {
2665
- workflowName: this._options.name,
2666
- runId: result.id,
2667
- status: result.status,
2668
- ...taskOpts.meta ?? {}
2669
- },
2670
- allowReservedPrefix: true
2671
- });
2672
- }
2673
- return result;
2674
- }
2675
- /**
2676
- * SE28 — run the workflow and STREAM step-level events as they happen. Returns
2677
- * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`
2678
- * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level
2679
- * steps) plus a `result` promise resolving to the same terminal
2680
- * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for
2681
- * the outcome. The stream ends when the run terminates.
2682
- *
2683
- * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a
2684
- * closing event: a step failure emits `step_failed`, but an `outputSchema`
2685
- * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —
2686
- * always `await result` to read the final `status`. Consuming order is free:
2687
- * awaiting `result` without draining, or draining without awaiting `result`,
2688
- * both work (breaking out of `for await` stops the buffering early).
2689
- */
2690
- stream(input, opts) {
2691
- const queue = createEventStream();
2692
- const result = (async () => {
2693
- const { executeWorkflow: executeWorkflow2 } = await Promise.resolve().then(() => (init_executor(), executor_exports));
2694
- try {
2695
- return await executeWorkflow2(this._options, this._steps, input, {
2696
- ...opts,
2697
- onStepEvent: (event) => queue.push(event)
2698
- });
2699
- } finally {
2700
- queue.end();
2701
- }
2702
- })();
2703
- return Object.assign(queue, { result });
2704
- }
2705
- /**
2706
- * Resume a suspended workflow from its snapshot. Throws
2707
- * `WorkflowSnapshotNotFoundError` if `runId` is unknown.
2708
- */
2709
- static async resume(opts) {
2710
- const { resumeWorkflow: resumeWorkflow2 } = await Promise.resolve().then(() => (init_executor(), executor_exports));
2711
- return resumeWorkflow2(opts);
2712
- }
2713
- };
2714
- function fn(id, step, opts) {
2715
- validateStepId(id);
2716
- if (opts?.retry !== void 0) RetryPolicySchema.parse(opts.retry);
2717
- return {
2718
- kind: "fn",
2719
- id,
2720
- fn: step,
2721
- ...opts?.inputSchema !== void 0 ? { inputSchema: opts.inputSchema } : {},
2722
- ...opts?.outputSchema !== void 0 ? { outputSchema: opts.outputSchema } : {},
2723
- ...opts?.retry !== void 0 ? { retry: opts.retry } : {}
2724
- };
2725
- }
2726
- function agentStep(id, agent, promptTemplate, opts) {
2727
- validateStepId(id);
2728
- if (opts?.retry !== void 0) RetryPolicySchema.parse(opts.retry);
2729
- return {
2730
- kind: "agent",
2731
- id,
2732
- agent,
2733
- promptTemplate,
2734
- ...opts?.retry !== void 0 ? { retry: opts.retry } : {},
2735
- // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).
2736
- ...opts?.origin !== void 0 ? { origin: opts.origin } : {}
2737
- };
2738
- }
2739
- function workflowStep(child, opts) {
2740
- const id = opts?.id ?? `workflow_${child.__options.name}`;
2741
- validateStepId(id);
2742
- return {
2743
- kind: "fn",
2744
- id,
2745
- fn: async (input, ctx) => {
2746
- const run = await child.run(input, { signal: ctx.signal });
2747
- if (run.status === "completed") return run.output;
2748
- throw new exports.WorkflowNestedError(id, child.__options.name, run.status, run.error);
2749
- }
2750
- };
2751
- }
2752
- function cloneWorkflow(wf, opts) {
2753
- return new Workflow(
2754
- { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },
2755
- [...wf.__steps]
2756
- );
2757
- }
2758
- var WorkflowToolError = class extends Error {
2759
- constructor(toolName, workflowStatus, workflowError) {
2760
- super(
2761
- `workflowAsTool("${toolName}"): workflow ${workflowStatus}${workflowError ? `: ${workflowError.message}` : ""}`
2762
- );
2763
- this.toolName = toolName;
2764
- this.workflowStatus = workflowStatus;
2765
- this.workflowError = workflowError;
2766
- this.name = "WorkflowToolError";
2767
- }
2768
- toolName;
2769
- workflowStatus;
2770
- workflowError;
2771
- code = "workflow_tool_failed";
2772
- };
2773
- function workflowAsTool(workflow, spec) {
2774
- const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: "any" });
2775
- return {
2776
- name: spec.name,
2777
- description: spec.description,
2778
- inputSchema,
2779
- handler: async (rawInput) => {
2780
- const parsed = spec.inputSchema.parse(rawInput);
2781
- const run = await workflow.run(parsed);
2782
- if (run.status !== "completed") {
2783
- throw new WorkflowToolError(spec.name, run.status, run.error);
2784
- }
2785
- const output = run.output;
2786
- return typeof output === "string" ? output : JSON.stringify(output ?? null);
2787
- }
2788
- };
2789
- }
2790
- function validateStepId(id) {
2791
- sanitizeIdentifier(id, { maxLen: 64 });
2792
- }
2793
- function mintShortId() {
2794
- return globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 8);
2795
- }
2796
- function nestedStepsOf(s) {
2797
- if (s.kind === "parallel") return s.branches;
2798
- if (s.kind === "branch") {
2799
- const groups = s.predicates.map(([, branch]) => branch);
2800
- return s.fallback !== void 0 ? [...groups, s.fallback] : groups;
2801
- }
2802
- if (s.kind === "foreach" || s.kind === "dowhile") return [[s.step]];
2803
- return [];
2804
- }
2805
- function walkStepsValidating(steps, seen) {
2806
- for (const s of steps) {
2807
- if (seen.has(s.id)) throw new exports.WorkflowDuplicateStepIdError(s.id);
2808
- seen.add(s.id);
2809
- for (const nested of nestedStepsOf(s)) {
2810
- walkStepsValidating(nested, seen);
2811
- }
2812
- }
2813
- }
2814
-
2815
- exports.Workflow = Workflow;
2816
- exports.WorkflowBuilder = WorkflowBuilder;
2817
- exports.WorkflowToolError = WorkflowToolError;
2818
- exports.__resetSnapshotStoresForTests = __resetSnapshotStoresForTests;
2819
- exports.agentStep = agentStep;
2820
- exports.cloneWorkflow = cloneWorkflow;
2821
- exports.fn = fn;
2822
- exports.workflowAsTool = workflowAsTool;
2823
- exports.workflowStep = workflowStep;
2824
98
  //# sourceMappingURL=workflow.cjs.map
2825
99
  //# sourceMappingURL=workflow.cjs.map