@theokit/sdk 4.24.0 → 4.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (382) hide show
  1. package/dist/a2a/index.cjs +10 -171
  2. package/dist/a2a/index.cjs.map +1 -1
  3. package/dist/a2a/index.js +3 -170
  4. package/dist/a2a/index.js.map +1 -1
  5. package/dist/agent-factory-registry-UU46BUMU.cjs +16 -0
  6. package/dist/agent-factory-registry-UU46BUMU.cjs.map +1 -0
  7. package/dist/agent-factory-registry-ZVTABLEY.js +3 -0
  8. package/dist/agent-factory-registry-ZVTABLEY.js.map +1 -0
  9. package/dist/auth/index.cjs +63 -367
  10. package/dist/auth/index.cjs.map +1 -1
  11. package/dist/auth/index.js +6 -342
  12. package/dist/auth/index.js.map +1 -1
  13. package/dist/batch-2FSD2UNL.cjs +244 -0
  14. package/dist/batch-2FSD2UNL.cjs.map +1 -0
  15. package/dist/batch-MR2HKYMS.js +241 -0
  16. package/dist/batch-MR2HKYMS.js.map +1 -0
  17. package/dist/chunk-2HRYBRD7.cjs +31 -0
  18. package/dist/chunk-2HRYBRD7.cjs.map +1 -0
  19. package/dist/chunk-2MF3IE2D.cjs +2863 -0
  20. package/dist/chunk-2MF3IE2D.cjs.map +1 -0
  21. package/dist/chunk-2ONFGMBV.js +6 -0
  22. package/dist/chunk-2ONFGMBV.js.map +1 -0
  23. package/dist/chunk-2SFBB54R.js +23 -0
  24. package/dist/chunk-2SFBB54R.js.map +1 -0
  25. package/dist/chunk-2XLKLVVR.js +18 -0
  26. package/dist/chunk-2XLKLVVR.js.map +1 -0
  27. package/dist/chunk-4SXHEZIV.cjs +240 -0
  28. package/dist/chunk-4SXHEZIV.cjs.map +1 -0
  29. package/dist/chunk-4VPXM6UU.js +10 -0
  30. package/dist/chunk-4VPXM6UU.js.map +1 -0
  31. package/dist/chunk-4WL52CXU.cjs +148 -0
  32. package/dist/chunk-4WL52CXU.cjs.map +1 -0
  33. package/dist/chunk-5NBUH3NO.js +39 -0
  34. package/dist/chunk-5NBUH3NO.js.map +1 -0
  35. package/dist/chunk-5PZMMF4H.js +43 -0
  36. package/dist/chunk-5PZMMF4H.js.map +1 -0
  37. package/dist/chunk-6CLRANZA.js +289 -0
  38. package/dist/chunk-6CLRANZA.js.map +1 -0
  39. package/dist/chunk-6JSIEDKL.cjs +121 -0
  40. package/dist/chunk-6JSIEDKL.cjs.map +1 -0
  41. package/dist/chunk-6M4ODB2V.cjs +145 -0
  42. package/dist/chunk-6M4ODB2V.cjs.map +1 -0
  43. package/dist/chunk-6X6ID4MO.js +20 -0
  44. package/dist/chunk-6X6ID4MO.js.map +1 -0
  45. package/dist/chunk-77FOZCOT.js +165 -0
  46. package/dist/chunk-77FOZCOT.js.map +1 -0
  47. package/dist/chunk-7AD3ZTZL.js +25 -0
  48. package/dist/chunk-7AD3ZTZL.js.map +1 -0
  49. package/dist/chunk-7GFX45DD.js +57 -0
  50. package/dist/chunk-7GFX45DD.js.map +1 -0
  51. package/dist/chunk-7S7KKUO6.cjs +45 -0
  52. package/dist/chunk-7S7KKUO6.cjs.map +1 -0
  53. package/dist/chunk-7W7ZWMLQ.js +99 -0
  54. package/dist/chunk-7W7ZWMLQ.js.map +1 -0
  55. package/dist/chunk-A44COQJJ.cjs +353 -0
  56. package/dist/chunk-A44COQJJ.cjs.map +1 -0
  57. package/dist/chunk-AKSBP7OO.js +185 -0
  58. package/dist/chunk-AKSBP7OO.js.map +1 -0
  59. package/dist/chunk-ANIZEWTU.cjs +196 -0
  60. package/dist/chunk-ANIZEWTU.cjs.map +1 -0
  61. package/dist/chunk-BEURCLDV.cjs +139 -0
  62. package/dist/chunk-BEURCLDV.cjs.map +1 -0
  63. package/dist/chunk-BFWPZMG7.js +379 -0
  64. package/dist/chunk-BFWPZMG7.js.map +1 -0
  65. package/dist/chunk-BUUUWQMB.cjs +34 -0
  66. package/dist/chunk-BUUUWQMB.cjs.map +1 -0
  67. package/dist/chunk-BV2MWEMV.cjs +26 -0
  68. package/dist/chunk-BV2MWEMV.cjs.map +1 -0
  69. package/dist/chunk-BWT67BI4.cjs +268 -0
  70. package/dist/chunk-BWT67BI4.cjs.map +1 -0
  71. package/dist/chunk-BXV2QUIC.js +191 -0
  72. package/dist/chunk-BXV2QUIC.js.map +1 -0
  73. package/dist/chunk-C6Y6CWYD.cjs +44 -0
  74. package/dist/chunk-C6Y6CWYD.cjs.map +1 -0
  75. package/dist/chunk-C7PICHRF.cjs +68 -0
  76. package/dist/chunk-C7PICHRF.cjs.map +1 -0
  77. package/dist/chunk-CAH3G4IS.js +13 -0
  78. package/dist/chunk-CAH3G4IS.js.map +1 -0
  79. package/dist/chunk-D42XHI4O.cjs +565 -0
  80. package/dist/chunk-D42XHI4O.cjs.map +1 -0
  81. package/dist/chunk-DGRZNMTU.js +104 -0
  82. package/dist/chunk-DGRZNMTU.js.map +1 -0
  83. package/dist/chunk-DUK5WMKJ.js +71 -0
  84. package/dist/chunk-DUK5WMKJ.js.map +1 -0
  85. package/dist/chunk-EEZ7CFMM.js +14 -0
  86. package/dist/chunk-EEZ7CFMM.js.map +1 -0
  87. package/dist/chunk-EPYZOCOL.cjs +82 -0
  88. package/dist/chunk-EPYZOCOL.cjs.map +1 -0
  89. package/dist/chunk-EVADEGM7.cjs +168 -0
  90. package/dist/chunk-EVADEGM7.cjs.map +1 -0
  91. package/dist/chunk-FD2UT76F.js +3 -0
  92. package/dist/chunk-FD2UT76F.js.map +1 -0
  93. package/dist/chunk-FV3YEMQ7.js +179 -0
  94. package/dist/chunk-FV3YEMQ7.js.map +1 -0
  95. package/dist/chunk-G2F67XUR.cjs +184 -0
  96. package/dist/chunk-G2F67XUR.cjs.map +1 -0
  97. package/dist/chunk-G6GO6BXD.js +994 -0
  98. package/dist/chunk-G6GO6BXD.js.map +1 -0
  99. package/dist/chunk-GIW4L6HY.cjs +27 -0
  100. package/dist/chunk-GIW4L6HY.cjs.map +1 -0
  101. package/dist/chunk-GJAGKFTR.js +74 -0
  102. package/dist/chunk-GJAGKFTR.js.map +1 -0
  103. package/dist/chunk-HFPGOTVF.cjs +324 -0
  104. package/dist/chunk-HFPGOTVF.cjs.map +1 -0
  105. package/dist/chunk-HRA3CPGG.js +486 -0
  106. package/dist/chunk-HRA3CPGG.js.map +1 -0
  107. package/dist/chunk-HZQEDNF6.js +66 -0
  108. package/dist/chunk-HZQEDNF6.js.map +1 -0
  109. package/dist/chunk-IT3PWBW4.cjs +19 -0
  110. package/dist/chunk-IT3PWBW4.cjs.map +1 -0
  111. package/dist/chunk-JD74LN7R.cjs +171 -0
  112. package/dist/chunk-JD74LN7R.cjs.map +1 -0
  113. package/dist/chunk-JTFYYKDT.js +135 -0
  114. package/dist/chunk-JTFYYKDT.js.map +1 -0
  115. package/dist/chunk-K2BQQ445.js +30 -0
  116. package/dist/chunk-K2BQQ445.js.map +1 -0
  117. package/dist/chunk-KAP4GJHO.js +546 -0
  118. package/dist/chunk-KAP4GJHO.js.map +1 -0
  119. package/dist/chunk-KDNBTPY2.js +458 -0
  120. package/dist/chunk-KDNBTPY2.js.map +1 -0
  121. package/dist/chunk-KIO7QFIV.cjs +223 -0
  122. package/dist/chunk-KIO7QFIV.cjs.map +1 -0
  123. package/dist/chunk-KSKU6JY6.cjs +71 -0
  124. package/dist/chunk-KSKU6JY6.cjs.map +1 -0
  125. package/dist/chunk-LSLPF6OI.cjs +192 -0
  126. package/dist/chunk-LSLPF6OI.cjs.map +1 -0
  127. package/dist/chunk-LU7VALW5.js +312 -0
  128. package/dist/chunk-LU7VALW5.js.map +1 -0
  129. package/dist/chunk-LUSXDZPV.cjs +296 -0
  130. package/dist/chunk-LUSXDZPV.cjs.map +1 -0
  131. package/dist/chunk-M72RJVPC.js +69 -0
  132. package/dist/chunk-M72RJVPC.js.map +1 -0
  133. package/dist/chunk-MQLCZ4HJ.cjs +1010 -0
  134. package/dist/chunk-MQLCZ4HJ.cjs.map +1 -0
  135. package/dist/chunk-MUUQ2WFJ.cjs +4 -0
  136. package/dist/chunk-MUUQ2WFJ.cjs.map +1 -0
  137. package/dist/chunk-MZ5ZRORA.cjs +496 -0
  138. package/dist/chunk-MZ5ZRORA.cjs.map +1 -0
  139. package/dist/chunk-N24XBYNX.cjs +140 -0
  140. package/dist/chunk-N24XBYNX.cjs.map +1 -0
  141. package/dist/chunk-NINIJCHU.cjs +23 -0
  142. package/dist/chunk-NINIJCHU.cjs.map +1 -0
  143. package/dist/chunk-NRSH7RJY.js +2841 -0
  144. package/dist/chunk-NRSH7RJY.js.map +1 -0
  145. package/dist/chunk-OIYQBUW4.cjs +111 -0
  146. package/dist/chunk-OIYQBUW4.cjs.map +1 -0
  147. package/dist/chunk-PNVDQL5Y.cjs +15 -0
  148. package/dist/chunk-PNVDQL5Y.cjs.map +1 -0
  149. package/dist/chunk-POQT2OIF.js +214 -0
  150. package/dist/chunk-POQT2OIF.js.map +1 -0
  151. package/dist/chunk-PSJN532Q.js +10573 -0
  152. package/dist/chunk-PSJN532Q.js.map +1 -0
  153. package/dist/chunk-QUTUJ6P6.cjs +76 -0
  154. package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
  155. package/dist/chunk-R43CNCES.cjs +460 -0
  156. package/dist/chunk-R43CNCES.cjs.map +1 -0
  157. package/dist/chunk-S2BBRVQX.js +68 -0
  158. package/dist/chunk-S2BBRVQX.js.map +1 -0
  159. package/dist/chunk-S5RCBTSF.js +145 -0
  160. package/dist/chunk-S5RCBTSF.js.map +1 -0
  161. package/dist/chunk-S7OEXQMI.cjs +136 -0
  162. package/dist/chunk-S7OEXQMI.cjs.map +1 -0
  163. package/dist/chunk-SKWVAQAY.js +129 -0
  164. package/dist/chunk-SKWVAQAY.js.map +1 -0
  165. package/dist/chunk-SQLZ7ONU.js +152 -0
  166. package/dist/chunk-SQLZ7ONU.js.map +1 -0
  167. package/dist/chunk-TIZ4TS5V.cjs +72 -0
  168. package/dist/chunk-TIZ4TS5V.cjs.map +1 -0
  169. package/dist/chunk-TQKCU7CL.js +142 -0
  170. package/dist/chunk-TQKCU7CL.js.map +1 -0
  171. package/dist/chunk-U54XCYG3.js +116 -0
  172. package/dist/chunk-U54XCYG3.js.map +1 -0
  173. package/dist/chunk-U6QGZHPN.js +29 -0
  174. package/dist/chunk-U6QGZHPN.js.map +1 -0
  175. package/dist/chunk-UCFONJBG.js +79 -0
  176. package/dist/chunk-UCFONJBG.js.map +1 -0
  177. package/dist/chunk-UJ7IQJAG.js +141 -0
  178. package/dist/chunk-UJ7IQJAG.js.map +1 -0
  179. package/dist/chunk-UVNG67DG.js +253 -0
  180. package/dist/chunk-UVNG67DG.js.map +1 -0
  181. package/dist/chunk-V4XRLPEF.js +25 -0
  182. package/dist/chunk-V4XRLPEF.js.map +1 -0
  183. package/dist/chunk-VJ26EKGJ.cjs +28 -0
  184. package/dist/chunk-VJ26EKGJ.cjs.map +1 -0
  185. package/dist/chunk-VK7MAV65.cjs +90 -0
  186. package/dist/chunk-VK7MAV65.cjs.map +1 -0
  187. package/dist/chunk-VYCKUKPA.cjs +106 -0
  188. package/dist/chunk-VYCKUKPA.cjs.map +1 -0
  189. package/dist/chunk-VYHJZVL5.cjs +29 -0
  190. package/dist/chunk-VYHJZVL5.cjs.map +1 -0
  191. package/dist/chunk-WA3FO4R7.js +155 -0
  192. package/dist/chunk-WA3FO4R7.js.map +1 -0
  193. package/dist/chunk-WJVHMTKB.cjs +12 -0
  194. package/dist/chunk-WJVHMTKB.cjs.map +1 -0
  195. package/dist/chunk-WLKFWQSJ.js +333 -0
  196. package/dist/chunk-WLKFWQSJ.js.map +1 -0
  197. package/dist/chunk-WPZTYOUX.cjs +59 -0
  198. package/dist/chunk-WPZTYOUX.cjs.map +1 -0
  199. package/dist/chunk-X2FR4OIT.js +27 -0
  200. package/dist/chunk-X2FR4OIT.js.map +1 -0
  201. package/dist/chunk-XIG2IE3L.js +134 -0
  202. package/dist/chunk-XIG2IE3L.js.map +1 -0
  203. package/dist/chunk-YLQQX5W2.cjs +20 -0
  204. package/dist/chunk-YLQQX5W2.cjs.map +1 -0
  205. package/dist/chunk-YPEPCZHF.cjs +147 -0
  206. package/dist/chunk-YPEPCZHF.cjs.map +1 -0
  207. package/dist/chunk-YPQF26X7.cjs +8 -0
  208. package/dist/chunk-YPQF26X7.cjs.map +1 -0
  209. package/dist/chunk-YU6KON2I.cjs +160 -0
  210. package/dist/chunk-YU6KON2I.cjs.map +1 -0
  211. package/dist/chunk-Z2OC3UIW.cjs +388 -0
  212. package/dist/chunk-Z2OC3UIW.cjs.map +1 -0
  213. package/dist/chunk-ZUBIEQJF.cjs +10590 -0
  214. package/dist/chunk-ZUBIEQJF.cjs.map +1 -0
  215. package/dist/chunk-ZZWTY3RX.js +230 -0
  216. package/dist/chunk-ZZWTY3RX.js.map +1 -0
  217. package/dist/compact-session-OO2GD76G.js +17 -0
  218. package/dist/compact-session-OO2GD76G.js.map +1 -0
  219. package/dist/compact-session-OO7NVWPB.cjs +54 -0
  220. package/dist/compact-session-OO7NVWPB.cjs.map +1 -0
  221. package/dist/compaction.cjs +54 -303
  222. package/dist/compaction.cjs.map +1 -1
  223. package/dist/compaction.js +3 -292
  224. package/dist/compaction.js.map +1 -1
  225. package/dist/concurrency.cjs +9 -81
  226. package/dist/concurrency.cjs.map +1 -1
  227. package/dist/concurrency.js +5 -80
  228. package/dist/concurrency.js.map +1 -1
  229. package/dist/context-GWANQLX4.js +5 -0
  230. package/dist/context-GWANQLX4.js.map +1 -0
  231. package/dist/context-KNWVTZSY.cjs +22 -0
  232. package/dist/context-KNWVTZSY.cjs.map +1 -0
  233. package/dist/{cron-x3muPNgg.d.cts → cron-D0JKR-yX.d.cts} +2 -1
  234. package/dist/{cron-B_NkE_VM.d.ts → cron-DivRaEmN.d.ts} +2 -1
  235. package/dist/cron.cjs +44 -20676
  236. package/dist/cron.cjs.map +1 -1
  237. package/dist/cron.d.cts +1 -1
  238. package/dist/cron.d.ts +1 -1
  239. package/dist/cron.js +38 -20676
  240. package/dist/cron.js.map +1 -1
  241. package/dist/errors.cjs +78 -470
  242. package/dist/errors.cjs.map +1 -1
  243. package/dist/errors.d.ts +3 -424
  244. package/dist/errors.js +2 -455
  245. package/dist/errors.js.map +1 -1
  246. package/dist/eval.cjs +72 -20411
  247. package/dist/eval.cjs.map +1 -1
  248. package/dist/eval.js +59 -20402
  249. package/dist/eval.js.map +1 -1
  250. package/dist/executor-ORJS5GV2.js +981 -0
  251. package/dist/executor-ORJS5GV2.js.map +1 -0
  252. package/dist/executor-Y4MKPIUD.cjs +985 -0
  253. package/dist/executor-Y4MKPIUD.cjs.map +1 -0
  254. package/dist/filesystem/index.cjs +7 -112
  255. package/dist/filesystem/index.cjs.map +1 -1
  256. package/dist/filesystem/index.js +4 -109
  257. package/dist/filesystem/index.js.map +1 -1
  258. package/dist/fork-agent-RSV4E3EA.js +61 -0
  259. package/dist/fork-agent-RSV4E3EA.js.map +1 -0
  260. package/dist/fork-agent-Y2IK2RYU.cjs +64 -0
  261. package/dist/fork-agent-Y2IK2RYU.cjs.map +1 -0
  262. package/dist/fs-session-store-KAUQYSGI.cjs +17 -0
  263. package/dist/fs-session-store-KAUQYSGI.cjs.map +1 -0
  264. package/dist/fs-session-store-ZKB5NN37.js +8 -0
  265. package/dist/fs-session-store-ZKB5NN37.js.map +1 -0
  266. package/dist/generate-object-H3RNAM6S.cjs +20 -0
  267. package/dist/generate-object-H3RNAM6S.cjs.map +1 -0
  268. package/dist/generate-object-YJPDV5BS.js +7 -0
  269. package/dist/generate-object-YJPDV5BS.js.map +1 -0
  270. package/dist/index-manager-CB6I7XFQ.cjs +19 -0
  271. package/dist/index-manager-CB6I7XFQ.cjs.map +1 -0
  272. package/dist/index-manager-L27Q3QAC.js +10 -0
  273. package/dist/index-manager-L27Q3QAC.js.map +1 -0
  274. package/dist/index.cjs +371 -22888
  275. package/dist/index.cjs.map +1 -1
  276. package/dist/index.d.cts +16 -21
  277. package/dist/index.d.ts +16 -21
  278. package/dist/index.js +92 -22713
  279. package/dist/index.js.map +1 -1
  280. package/dist/inject-session-6MJUSGZP.cjs +27 -0
  281. package/dist/inject-session-6MJUSGZP.cjs.map +1 -0
  282. package/dist/inject-session-KOFHS5K3.js +25 -0
  283. package/dist/inject-session-KOFHS5K3.js.map +1 -0
  284. package/dist/internal/judge/judge-call.d.ts +32 -19
  285. package/dist/internal/persistence/index.cjs +93 -508
  286. package/dist/internal/persistence/index.cjs.map +1 -1
  287. package/dist/internal/persistence/index.js +11 -489
  288. package/dist/internal/persistence/index.js.map +1 -1
  289. package/dist/internal/security/index.cjs +44 -361
  290. package/dist/internal/security/index.cjs.map +1 -1
  291. package/dist/internal/security/index.js +4 -355
  292. package/dist/internal/security/index.js.map +1 -1
  293. package/dist/judge-call-CEQ3FYYD.js +126 -0
  294. package/dist/judge-call-CEQ3FYYD.js.map +1 -0
  295. package/dist/judge-call-QG4WZ7F3.cjs +130 -0
  296. package/dist/judge-call-QG4WZ7F3.cjs.map +1 -0
  297. package/dist/models.cjs +24 -919
  298. package/dist/models.cjs.map +1 -1
  299. package/dist/models.js +11 -907
  300. package/dist/models.js.map +1 -1
  301. package/dist/oauth-transaction-store-7CKHPQRN.cjs +32 -0
  302. package/dist/oauth-transaction-store-7CKHPQRN.cjs.map +1 -0
  303. package/dist/oauth-transaction-store-W74I6EFD.js +3 -0
  304. package/dist/oauth-transaction-store-W74I6EFD.js.map +1 -0
  305. package/dist/path-safety.cjs +31 -200
  306. package/dist/path-safety.cjs.map +1 -1
  307. package/dist/path-safety.js +3 -197
  308. package/dist/path-safety.js.map +1 -1
  309. package/dist/persistence.cjs +73 -393
  310. package/dist/persistence.cjs.map +1 -1
  311. package/dist/persistence.js +9 -381
  312. package/dist/persistence.js.map +1 -1
  313. package/dist/project.cjs +8 -112
  314. package/dist/project.cjs.map +1 -1
  315. package/dist/project.js +6 -110
  316. package/dist/project.js.map +1 -1
  317. package/dist/registry-34IWWDQQ.js +9 -0
  318. package/dist/registry-34IWWDQQ.js.map +1 -0
  319. package/dist/registry-APYDISL6.cjs +46 -0
  320. package/dist/registry-APYDISL6.cjs.map +1 -0
  321. package/dist/retry.cjs +7 -87
  322. package/dist/retry.cjs.map +1 -1
  323. package/dist/retry.js +3 -90
  324. package/dist/retry.js.map +1 -1
  325. package/dist/run-to-completion-J73I6IY4.cjs +48 -0
  326. package/dist/run-to-completion-J73I6IY4.cjs.map +1 -0
  327. package/dist/run-to-completion-JDPIUKSH.js +3 -0
  328. package/dist/run-to-completion-JDPIUKSH.js.map +1 -0
  329. package/dist/run-until-PNO3QQLI.cjs +180 -0
  330. package/dist/run-until-PNO3QQLI.cjs.map +1 -0
  331. package/dist/run-until-XLHEHRQM.js +177 -0
  332. package/dist/run-until-XLHEHRQM.js.map +1 -0
  333. package/dist/sandbox/index.cjs +35 -337
  334. package/dist/sandbox/index.cjs.map +1 -1
  335. package/dist/sandbox/index.js +7 -323
  336. package/dist/sandbox/index.js.map +1 -1
  337. package/dist/sanitize/index.cjs +5 -112
  338. package/dist/sanitize/index.cjs.map +1 -1
  339. package/dist/sanitize/index.js +1 -114
  340. package/dist/sanitize/index.js.map +1 -1
  341. package/dist/server/auth/index.cjs +35 -175
  342. package/dist/server/auth/index.cjs.map +1 -1
  343. package/dist/server/auth/index.js +7 -161
  344. package/dist/server/auth/index.js.map +1 -1
  345. package/dist/server/errors-envelope.cjs +17 -328
  346. package/dist/server/errors-envelope.cjs.map +1 -1
  347. package/dist/server/errors-envelope.js +4 -317
  348. package/dist/server/errors-envelope.js.map +1 -1
  349. package/dist/session-transcript-LPNZR3YS.cjs +46 -0
  350. package/dist/session-transcript-LPNZR3YS.cjs.map +1 -0
  351. package/dist/session-transcript-T7LGJUGW.js +5 -0
  352. package/dist/session-transcript-T7LGJUGW.js.map +1 -0
  353. package/dist/skills.cjs +12 -280
  354. package/dist/skills.cjs.map +1 -1
  355. package/dist/skills.js +4 -282
  356. package/dist/skills.js.map +1 -1
  357. package/dist/stream-object-QEQJJDTI.cjs +20 -0
  358. package/dist/stream-object-QEQJJDTI.cjs.map +1 -0
  359. package/dist/stream-object-WUQSSRY2.js +7 -0
  360. package/dist/stream-object-WUQSSRY2.js.map +1 -0
  361. package/dist/stream-to-completion-DFJ5T3BK.js +30 -0
  362. package/dist/stream-to-completion-DFJ5T3BK.js.map +1 -0
  363. package/dist/stream-to-completion-H2MHISSK.cjs +32 -0
  364. package/dist/stream-to-completion-H2MHISSK.cjs.map +1 -0
  365. package/dist/subagents.cjs +2 -8
  366. package/dist/subagents.cjs.map +1 -1
  367. package/dist/subagents.js +1 -7
  368. package/dist/subagents.js.map +1 -1
  369. package/dist/subscription/index.cjs +4 -17
  370. package/dist/subscription/index.cjs.map +1 -1
  371. package/dist/subscription/index.js +3 -16
  372. package/dist/subscription/index.js.map +1 -1
  373. package/dist/task-store.cjs +16 -258
  374. package/dist/task-store.cjs.map +1 -1
  375. package/dist/task-store.js +4 -259
  376. package/dist/task-store.js.map +1 -1
  377. package/dist/types/goal-events.d.ts +2 -1
  378. package/dist/workflow.cjs +71 -2797
  379. package/dist/workflow.cjs.map +1 -1
  380. package/dist/workflow.js +8 -2812
  381. package/dist/workflow.js.map +1 -1
  382. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":[],"mappings":";;;;;AA6CO,IAAM,iBAAN,MAA6C;AAAA,EACzC,QAAA;AAAA,EACA,IAAA;AAAA,EAET,YAAY,OAAA,EAAgC;AAC1C,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,GAAA;AAAA,EACtB;AAAA,EAEA,MAAM,YAAY,OAAA,EAA2C;AAC3D,IAAA,OAAO,eAAe,cAAA,CAAe,IAAA,CAAK,UAAU,IAAA,CAAK,IAAA,EAAM,OAAO,CAAC,CAAA;AAAA,EACzE;AAAA,EAEA,MAAM,aAAA,CAAc,OAAA,EAAiB,OAAA,EAAkD;AAErF,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,OAAO,cAAA,CAAe,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,MAAM,OAAO,CAAA;AAE7D,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,YAAA,CAAa,MAAM,YAAY;AACnC,MAAA,MAAM,KAAA,GAAQ,MAAM,cAAA,CAAe,IAAI,CAAA;AACvC,MAAA,MAAM,gBAAgB,IAAA,EAAM,CAAC,GAAG,KAAA,EAAO,GAAG,OAAO,CAAC,CAAA;AAAA,IACpD,CAAC,CAAA;AAAA,EACH;AACF","file":"chunk-U6QGZHPN.js","sourcesContent":["/**\n * SE41 — `FsSessionStore`, the DEFAULT reference implementation of the pluggable\n * {@link SessionStore} seam. It reads and append-writes the native Claude-shaped\n * `.jsonl` transcript at `<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl` — the\n * exact on-disk format SE40 introduced (the file the Claude Code CLI can\n * `--continue`). Omitting `local.sessionStore` resolves to this store, so the\n * default persistence path is byte-identical to SE40 behavior.\n *\n * `readRecords` is `readTranscript(transcriptPath(...))` (a missing session →\n * `[]`, not an error — a fresh agent has no history). `appendRecords` is a TRUE\n * append: it reads the prior records, concatenates the new-turn delta, and\n * rewrites the whole line set atomically under the SE40 cross-process file lock\n * (`writeTranscript` never shrinks — the native format is an append-only\n * `parentUuid` DAG). The parent dir is created BEFORE acquiring the lock because\n * the lock's companion `<path>.lock` file needs an existing parent dir (the SE40\n * `mkdir(dirname)`-before-lock fix).\n *\n * @internal\n */\n\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport {\n readTranscript,\n type SessionRecord,\n transcriptPath,\n writeTranscript,\n} from \"./session-transcript.js\";\n\n/** Options identifying the on-disk transcript location for the FS default store. */\nexport interface FsSessionStoreOptions {\n /** Transcript base dir (`~/.theokit` default, `~/.claude` for CLI interop) — already `~`-expanded. */\n baseDir: string;\n /** The workspace cwd whose encoded form is the transcript project dir. */\n cwd: string;\n}\n\n/**\n * The default `SessionStore` — reads/append-writes the native `.jsonl` transcript.\n *\n * @internal\n */\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n\n constructor(options: FsSessionStoreOptions) {\n this.#baseDir = options.baseDir;\n this.#cwd = options.cwd;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n // Empty delta → nothing to persist (avoids an unnecessary lock + rewrite).\n if (records.length === 0) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n // mkdir BEFORE the lock: withFileLock's companion `<path>.lock` needs the parent dir.\n await mkdir(dirname(path), { recursive: true });\n await withFileLock(path, async () => {\n const prior = await readTranscript(path);\n await writeTranscript(path, [...prior, ...records]);\n });\n }\n}\n"]}
@@ -0,0 +1,79 @@
1
+ // src/internal/runtime/lifecycle/run-to-completion.ts
2
+ var DEFAULT_MAX_ROUNDS = 5;
3
+ var DEFAULT_CONTINUATION_PROMPT = "Continue from where you left off and finish the task. If it is already complete, give the final answer.";
4
+ function isEmptyRound(result) {
5
+ return (result.result ?? "").trim() === "";
6
+ }
7
+ function classifyRound(result, round, maxRounds, emptyStreak) {
8
+ if (result.stoppedByDoomLoop === true) return "no_progress";
9
+ if (result.stoppedAtIterationLimit !== true) return "done";
10
+ if (isEmptyRound(result) && emptyStreak >= 1) return "no_progress";
11
+ if (round >= maxRounds) return "step_limit";
12
+ return "continue";
13
+ }
14
+ function addUsage(acc, u) {
15
+ if (u === void 0) return acc;
16
+ const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;
17
+ const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;
18
+ const sumOpt = (a, b) => a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
19
+ return {
20
+ inputTokens,
21
+ outputTokens,
22
+ totalTokens: inputTokens + outputTokens,
23
+ cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),
24
+ cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),
25
+ reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens)
26
+ };
27
+ }
28
+ function buildResult(terminal, rounds, lastResult, usage) {
29
+ return { terminal, rounds, lastResult, ...usage !== void 0 ? { usage } : {} };
30
+ }
31
+ async function continuationTail(round, lastResult, usage, onTruncated, signal) {
32
+ await onTruncated?.({ round });
33
+ return signal?.aborted === true ? buildResult("step_limit", round, lastResult, usage) : void 0;
34
+ }
35
+ function resolveContinuation(options) {
36
+ return {
37
+ maxRounds: options?.maxRounds ?? DEFAULT_MAX_ROUNDS,
38
+ continuationPrompt: options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT,
39
+ onTruncated: options?.onTruncated,
40
+ signal: options?.signal,
41
+ sendOptions: options?.sendOptions,
42
+ state: { usage: void 0, emptyStreak: 0 }
43
+ };
44
+ }
45
+ function promptForRound(round, message, continuationPrompt) {
46
+ return round === 0 ? message : continuationPrompt;
47
+ }
48
+ async function stepRound(agent, prompt, sendOptions, round, maxRounds, state) {
49
+ const roundOptions = round === 0 ? sendOptions : { ...sendOptions ?? {}, origin: { kind: "auto-continuation" } };
50
+ const run = await agent.send(prompt, roundOptions);
51
+ const result = await run.wait();
52
+ const usage = addUsage(state.usage, result.usage);
53
+ const decision = classifyRound(result, round, maxRounds, state.emptyStreak);
54
+ if (decision !== "continue") return { terminal: buildResult(decision, round, result, usage) };
55
+ const emptyStreak = isEmptyRound(result) ? state.emptyStreak + 1 : 0;
56
+ return { next: { usage, emptyStreak }, lastResult: result };
57
+ }
58
+ async function runToCompletionImpl(agent, message, options) {
59
+ const cfg = resolveContinuation(options);
60
+ let state = cfg.state;
61
+ for (let round = 0; ; round += 1) {
62
+ const prompt = promptForRound(round, message, cfg.continuationPrompt);
63
+ const outcome = await stepRound(agent, prompt, cfg.sendOptions, round, cfg.maxRounds, state);
64
+ if ("terminal" in outcome) return outcome.terminal;
65
+ state = outcome.next;
66
+ const aborted = await continuationTail(
67
+ round,
68
+ outcome.lastResult,
69
+ state.usage,
70
+ cfg.onTruncated,
71
+ cfg.signal
72
+ );
73
+ if (aborted !== void 0) return aborted;
74
+ }
75
+ }
76
+
77
+ export { DEFAULT_CONTINUATION_PROMPT, DEFAULT_MAX_ROUNDS, addUsage, buildResult, classifyRound, continuationTail, isEmptyRound, promptForRound, resolveContinuation, runToCompletionImpl };
78
+ //# sourceMappingURL=chunk-UCFONJBG.js.map
79
+ //# sourceMappingURL=chunk-UCFONJBG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/lifecycle/run-to-completion.ts"],"names":[],"mappings":";AA+BO,IAAM,kBAAA,GAAqB;AAE3B,IAAM,2BAAA,GACX;AAQK,SAAS,aAAa,MAAA,EAA4B;AACvD,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAA,IAAU,EAAA,EAAI,IAAA,EAAK,KAAM,EAAA;AAC1C;AASO,SAAS,aAAA,CACd,MAAA,EACA,KAAA,EACA,SAAA,EACA,WAAA,EACe;AAIf,EAAA,IAAI,MAAA,CAAO,iBAAA,KAAsB,IAAA,EAAM,OAAO,aAAA;AAC9C,EAAA,IAAI,MAAA,CAAO,uBAAA,KAA4B,IAAA,EAAM,OAAO,MAAA;AAEpD,EAAA,IAAI,YAAA,CAAa,MAAM,CAAA,IAAK,WAAA,IAAe,GAAG,OAAO,aAAA;AACrD,EAAA,IAAI,KAAA,IAAS,WAAW,OAAO,YAAA;AAC/B,EAAA,OAAO,UAAA;AACT;AAWO,SAAS,QAAA,CACd,KACA,CAAA,EACwB;AACxB,EAAA,IAAI,CAAA,KAAM,QAAW,OAAO,GAAA;AAC5B,EAAA,MAAM,WAAA,GAAA,CAAe,GAAA,EAAK,WAAA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B,KAAA,EACA,OAAA,EACA,OAAA,EACgC;AAChC,EAAA,MAAM,GAAA,GAAM,oBAAoB,OAAO,CAAA;AACvC,EAAA,IAAI,QAAQ,GAAA,CAAI,KAAA;AAEhB,EAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,IAAK,KAAA,IAAS,CAAA,EAAG;AAChC,IAAA,MAAM,MAAA,GAAS,cAAA,CAAe,KAAA,EAAO,OAAA,EAAS,IAAI,kBAAkB,CAAA;AACpE,IAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,KAAA,EAAO,MAAA,EAAQ,IAAI,WAAA,EAAa,KAAA,EAAO,GAAA,CAAI,SAAA,EAAW,KAAK,CAAA;AAC3F,IAAA,IAAI,UAAA,IAAc,OAAA,EAAS,OAAO,OAAA,CAAQ,QAAA;AAG1C,IAAA,KAAA,GAAQ,OAAA,CAAQ,IAAA;AAChB,IAAA,MAAM,UAAU,MAAM,gBAAA;AAAA,MACpB,KAAA;AAAA,MACA,OAAA,CAAQ,UAAA;AAAA,MACR,KAAA,CAAM,KAAA;AAAA,MACN,GAAA,CAAI,WAAA;AAAA,MACJ,GAAA,CAAI;AAAA,KACN;AACA,IAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAAA,EACpC;AACF","file":"chunk-UCFONJBG.js","sourcesContent":["/**\n * `runToCompletion` continuation driver (M1 Phase 3 — plan m1-run-to-completion).\n *\n * Drives repeated `send()`s on a STATEFUL agent until a genuine terminal,\n * consuming the `RunResult.stoppedAtIterationLimit` signal shipped in 2.2.0.\n * The agent's session preserves conversation history across sends, so after a\n * truncated round the driver only re-sends a short continuation prompt (it does\n * NOT reconstruct history). Mirrors the injectable shape of `run-until.ts` and\n * absorbs the outer-loop policy hand-rolled in `theocode/server/lib/agent-loop.ts`.\n *\n * The core is decision-pure + injectable (`agent` is only the `.send` port) so\n * every terminal is unit-testable with a fake send — fixture mode never sets\n * `stoppedAtIterationLimit`, so injection is the only deterministic path.\n *\n * @internal\n */\n\nimport type {\n RunResult,\n RunToCompletionOptions,\n RunToCompletionResult,\n SendOptions,\n} from \"../../../types/run.js\";\nimport type { TokenUsage } from \"../../../types/usage.js\";\n\n/** Minimal agent port the driver needs — the instance `.send()` surface. */\nexport interface RunToCompletionAgent {\n send(message: string, options?: SendOptions): Promise<{ wait(): Promise<RunResult> }>;\n}\n\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_MAX_ROUNDS = 5;\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport const DEFAULT_CONTINUATION_PROMPT =\n \"Continue from where you left off and finish the task. If it is already complete, give the final answer.\";\n\ntype RoundDecision = \"done\" | \"continue\" | \"step_limit\" | \"no_progress\";\n\n/**\n * True when a round produced no observable output text.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function isEmptyRound(result: RunResult): boolean {\n return (result.result ?? \"\").trim() === \"\";\n}\n\n/**\n * Pure decision: given a round's result + position + the running empty streak,\n * decide whether to finish (`done`), keep going (`continue`), or bail\n * (`step_limit` / `no_progress`).\n *\n * @internal\n */\nexport function classifyRound(\n result: RunResult,\n round: number,\n maxRounds: number,\n emptyStreak: number,\n): RoundDecision {\n // Doom-loop stop is a genuine terminal (the model repeated identical tool calls) — classify it as\n // `no_progress` FIRST, before the iteration-limit check, so it is never mistaken for a truncation\n // to re-send (which would re-trigger the loop). Complements the empty-round `no_progress` below.\n if (result.stoppedByDoomLoop === true) return \"no_progress\";\n if (result.stoppedAtIterationLimit !== true) return \"done\";\n // Truncated at the iteration ceiling.\n if (isEmptyRound(result) && emptyStreak >= 1) return \"no_progress\";\n if (round >= maxRounds) return \"step_limit\";\n return \"continue\";\n}\n\n/**\n * Sum a round's usage into the running aggregate. `requests` is intentionally\n * dropped (concatenating per-run request breakdowns across continuation rounds\n * would falsely imply a single multi-call run). `totalTokens` is DERIVED\n * (`inputTokens + outputTokens`), never summed independently, to preserve the\n * EC-10 invariant (`usage.ts`) at this aggregation boundary even if a provider\n * folded extra buckets into a round's own `totalTokens`.\n */\n/** @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4). */\nexport function addUsage(\n acc: TokenUsage | undefined,\n u: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (u === undefined) return acc;\n const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;\n const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;\n const sumOpt = (a: number | undefined, b: number | undefined): number | undefined =>\n a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),\n cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),\n reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens),\n };\n}\n\n/**\n * Assemble the result object, omitting `usage` when no round reported any.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport function buildResult(\n terminal: RunToCompletionResult[\"terminal\"],\n rounds: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n): RunToCompletionResult {\n return { terminal, rounds, lastResult, ...(usage !== undefined ? { usage } : {}) };\n}\n\n/**\n * The shared between-rounds tail: fire `onTruncated`, then — re-reading `aborted`\n * (a getter that can flip between rounds) — return a `step_limit` result if the\n * signal aborted, else `undefined` to continue. Used by BOTH the stateful driver\n * and its streaming twin (V3-4), so the continuation-end policy has one home.\n * @internal\n */\nexport async function continuationTail(\n round: number,\n lastResult: RunResult,\n usage: TokenUsage | undefined,\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<RunToCompletionResult | undefined> {\n await onTruncated?.({ round });\n return signal?.aborted === true ? buildResult(\"step_limit\", round, lastResult, usage) : undefined;\n}\n\n/**\n * Carried state between continuation rounds.\n * @internal — shared with the streaming twin (`stream-to-completion.ts`, V3-4).\n */\nexport interface RoundState {\n usage: TokenUsage | undefined;\n emptyStreak: number;\n}\n\n/** Resolved continuation config + fresh initial state — shared by both drivers. @internal */\nexport interface ResolvedContinuation {\n maxRounds: number;\n continuationPrompt: string;\n onTruncated: ((event: { round: number }) => void | Promise<void>) | undefined;\n signal: AbortSignal | undefined;\n sendOptions: SendOptions | undefined;\n state: RoundState;\n}\n\n/** Resolve options to the continuation config + a fresh state. One home for the defaults. @internal */\nexport function resolveContinuation(options?: RunToCompletionOptions): ResolvedContinuation {\n return {\n maxRounds: options?.maxRounds ?? DEFAULT_MAX_ROUNDS,\n continuationPrompt: options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT,\n onTruncated: options?.onTruncated,\n signal: options?.signal,\n sendOptions: options?.sendOptions,\n state: { usage: undefined, emptyStreak: 0 },\n };\n}\n\n/** The round's prompt: the task on round 0, the continuation prompt after. @internal */\nexport function promptForRound(round: number, message: string, continuationPrompt: string): string {\n return round === 0 ? message : continuationPrompt;\n}\n\n/** A round either reaches a terminal, or yields the state to carry into the next round. */\ntype RoundOutcome =\n | { terminal: RunToCompletionResult }\n | { next: RoundState; lastResult: RunResult };\n\n/** Send one round, fold usage, classify. Splits the loop body out to cap complexity. */\nasync function stepRound(\n agent: RunToCompletionAgent,\n prompt: string,\n sendOptions: SendOptions | undefined,\n round: number,\n maxRounds: number,\n state: RoundState,\n): Promise<RoundOutcome> {\n // SE3 — a continuation round (round > 0) is a driver-initiated turn; stamp its\n // provenance so a consumer can tell it apart from the caller's first send.\n const roundOptions: SendOptions | undefined =\n round === 0 ? sendOptions : { ...(sendOptions ?? {}), origin: { kind: \"auto-continuation\" } };\n const run = await agent.send(prompt, roundOptions);\n const result = await run.wait();\n const usage = addUsage(state.usage, result.usage);\n const decision = classifyRound(result, round, maxRounds, state.emptyStreak);\n if (decision !== \"continue\") return { terminal: buildResult(decision, round, result, usage) };\n const emptyStreak = isEmptyRound(result) ? state.emptyStreak + 1 : 0;\n return { next: { usage, emptyStreak }, lastResult: result };\n}\n\n/**\n * Drive `agent.send()` until a terminal. See {@link RunToCompletionOptions}.\n *\n * @internal\n */\nexport async function runToCompletionImpl(\n agent: RunToCompletionAgent,\n message: string,\n options?: RunToCompletionOptions,\n): Promise<RunToCompletionResult> {\n const cfg = resolveContinuation(options);\n let state = cfg.state;\n\n for (let round = 0; ; round += 1) {\n const prompt = promptForRound(round, message, cfg.continuationPrompt);\n const outcome = await stepRound(agent, prompt, cfg.sendOptions, round, cfg.maxRounds, state);\n if (\"terminal\" in outcome) return outcome.terminal;\n\n // Truncated and below the round budget — re-send next iteration.\n state = outcome.next;\n const aborted = await continuationTail(\n round,\n outcome.lastResult,\n state.usage,\n cfg.onTruncated,\n cfg.signal,\n );\n if (aborted !== undefined) return aborted;\n }\n}\n"]}
@@ -0,0 +1,141 @@
1
+ import { existsSync, realpathSync } from 'fs';
2
+ import { readdir } from 'fs/promises';
3
+ import { isAbsolute, resolve, join, dirname } from 'path';
4
+
5
+ // src/internal/runtime/context/context-discovery.ts
6
+ var DEFAULT_DISCOVERY_SPECS = [
7
+ {
8
+ id: "AGENTS.md",
9
+ pattern: "AGENTS.md",
10
+ scope: "git-root-walk",
11
+ parser: "plain-markdown",
12
+ followImports: false,
13
+ priority: 10
14
+ },
15
+ {
16
+ id: "GEMINI.md",
17
+ pattern: "GEMINI.md",
18
+ scope: "git-root-walk",
19
+ parser: "plain-markdown",
20
+ followImports: true,
21
+ priority: 20
22
+ },
23
+ {
24
+ id: "CLAUDE.md",
25
+ pattern: "CLAUDE.md",
26
+ scope: "git-root-walk",
27
+ parser: "plain-markdown",
28
+ followImports: true,
29
+ priority: 30
30
+ },
31
+ {
32
+ id: "cursor-rules",
33
+ pattern: ".cursor/rules/*.mdc",
34
+ scope: "globbed",
35
+ parser: "mdc",
36
+ followImports: false,
37
+ priority: 40
38
+ },
39
+ {
40
+ id: "theokit-rules",
41
+ pattern: ".theokit/rules/*.md",
42
+ scope: "globbed",
43
+ parser: "rules-frontmatter",
44
+ followImports: false,
45
+ priority: 45
46
+ },
47
+ {
48
+ id: "theokit-context",
49
+ pattern: ".theokit/context/*.md",
50
+ scope: "globbed",
51
+ parser: "frontmatter-zod",
52
+ followImports: false,
53
+ priority: 50
54
+ },
55
+ {
56
+ id: "THEO.md",
57
+ pattern: ".theokit/THEO.md",
58
+ scope: "cwd-only",
59
+ parser: "plain-markdown",
60
+ followImports: false,
61
+ priority: 60
62
+ }
63
+ ];
64
+ var SAFE_FILENAME = /^[a-zA-Z0-9_.\-/*]+$/;
65
+ var TRAVERSAL_RE = /(^|\/)\.\.(\/|$)/;
66
+ function isSafePattern(pattern) {
67
+ if (typeof pattern !== "string" || pattern.length === 0) return false;
68
+ if (TRAVERSAL_RE.test(pattern)) return false;
69
+ if (isAbsolute(pattern)) return false;
70
+ return SAFE_FILENAME.test(pattern);
71
+ }
72
+ function findGitRoot(cwd) {
73
+ if (typeof cwd !== "string" || cwd.length === 0) return void 0;
74
+ let current = resolve(cwd);
75
+ for (let i = 0; i < 64; i += 1) {
76
+ if (existsSync(join(current, ".git"))) return current;
77
+ const parent = dirname(current);
78
+ if (parent === current) return void 0;
79
+ current = parent;
80
+ }
81
+ return void 0;
82
+ }
83
+ function walkUpForFile(cwd, filename, stopDir) {
84
+ if (!isSafePattern(filename)) {
85
+ return [];
86
+ }
87
+ const start = resolve(cwd);
88
+ const stop = stopDir !== void 0 ? resolve(stopDir) : void 0;
89
+ const found = [];
90
+ const seenReal = /* @__PURE__ */ new Set();
91
+ let current = start;
92
+ for (let i = 0; i < 64; i += 1) {
93
+ const candidate = join(current, filename);
94
+ if (existsSync(candidate)) {
95
+ let real;
96
+ try {
97
+ real = realpathSync(candidate);
98
+ } catch {
99
+ real = candidate;
100
+ }
101
+ if (!seenReal.has(real)) {
102
+ seenReal.add(real);
103
+ found.push(real);
104
+ }
105
+ }
106
+ if (stop !== void 0 && current === stop) break;
107
+ const parent = dirname(current);
108
+ if (parent === current) break;
109
+ current = parent;
110
+ }
111
+ return found;
112
+ }
113
+ async function walkUpForGlob(cwd, pattern) {
114
+ if (!isSafePattern(pattern)) return [];
115
+ const lastSlash = pattern.lastIndexOf("/");
116
+ if (lastSlash < 0) {
117
+ const candidate = join(cwd, pattern);
118
+ return existsSync(candidate) ? [resolve(candidate)] : [];
119
+ }
120
+ const dirPart = pattern.slice(0, lastSlash);
121
+ const filePart = pattern.slice(lastSlash + 1);
122
+ const dir = join(cwd, dirPart);
123
+ if (!existsSync(dir)) return [];
124
+ const fileRe = filePartToRegex(filePart);
125
+ let entries;
126
+ try {
127
+ entries = await readdir(dir);
128
+ } catch {
129
+ return [];
130
+ }
131
+ const matched = entries.filter((e) => fileRe.test(e)).sort();
132
+ return matched.map((e) => resolve(join(dir, e)));
133
+ }
134
+ function filePartToRegex(filePart) {
135
+ const escaped = filePart.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
136
+ return new RegExp(`^${escaped}$`);
137
+ }
138
+
139
+ export { DEFAULT_DISCOVERY_SPECS, findGitRoot, isSafePattern, walkUpForFile, walkUpForGlob };
140
+ //# sourceMappingURL=chunk-UJ7IQJAG.js.map
141
+ //# sourceMappingURL=chunk-UJ7IQJAG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/context/context-discovery.ts"],"names":[],"mappings":";;;;;AAsDO,IAAM,uBAAA,GAAwD;AAAA,EACnE;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,KAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,IAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;A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AAA,GAAS,gBAAgB,QAAQ,CAAA;AACvC,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,QAAQ,GAAG,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAM,OAAO,IAAA,CAAK,CAAC,CAAC,CAAA,CAAE,IAAA,EAAK;AAC3D,EAAA,OAAO,OAAA,CAAQ,IAAI,CAAC,CAAA,KAAM,QAAQ,IAAA,CAAK,GAAA,EAAK,CAAC,CAAC,CAAC,CAAA;AACjD;AAEA,SAAS,gBAAgB,QAAA,EAA0B;AACjD,EAAA,MAAM,OAAA,GAAU,SAAS,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA,CAAE,OAAA,CAAQ,OAAO,IAAI,CAAA;AACjF,EAAA,OAAO,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA,CAAG,CAAA;AAClC","file":"chunk-UJ7IQJAG.js","sourcesContent":["/**\n * Context file discovery (T1.1, ADRs D150 / D151).\n *\n * Discovers context files via three scopes:\n * - `cwd-only` — single dir, single path lookup\n * - `git-root-walk` — walk cwd → git-root, collect every directory's match\n * (nearest-first ordering)\n * - `globbed` — glob pattern relative to cwd (e.g. `.cursor/rules/*.mdc`)\n *\n * Pure `existsSync` checks — **no `.gitignore` parsing** (EC-A, KISS) and\n * **no invented `.theokitignore`** (EC-B). Paths normalized via\n * `realpath` to dedup symlink chains pointing to the same physical file\n * (EC-F). Git worktrees work transparently because `.git` exists as a\n * file in that case (EC-N).\n *\n * @internal\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** Single filename (\"AGENTS.md\") or relative glob (\".cursor/rules/*.mdc\"). */\nexport type DiscoveryScope = \"cwd-only\" | \"git-root-walk\" | \"globbed\";\n\n/** Parser to apply once file is read. */\nexport type DiscoveryParser = \"plain-markdown\" | \"mdc\" | \"frontmatter-zod\" | \"rules-frontmatter\";\n\n/**\n * Specification for one discoverable context source. The default registry\n * `DEFAULT_DISCOVERY_SPECS` covers the 2026 industry-standard set.\n *\n * @internal\n */\nexport interface DiscoverySpec {\n /** Stable identifier — used as `<source name=\"\">` and telemetry key. */\n readonly id: string;\n /** Priority for merge (lower = earlier in prompt). */\n readonly priority: number;\n /** Filename (cwd-only/git-root-walk) or glob (globbed). */\n readonly pattern: string;\n readonly scope: DiscoveryScope;\n readonly parser: DiscoveryParser;\n /** Whether to follow `@path` import directives (CLAUDE.md / GEMINI.md). */\n readonly followImports: boolean;\n}\n\n/**\n * 2026 industry-standard context file registry. Sorted by priority\n * ascending — earlier in prompt = more general, last-writer-wins on\n * conflict (D152 concat-by-priority).\n *\n * @internal\n */\nexport const DEFAULT_DISCOVERY_SPECS: ReadonlyArray<DiscoverySpec> = [\n {\n id: \"AGENTS.md\",\n pattern: \"AGENTS.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 10,\n },\n {\n id: \"GEMINI.md\",\n pattern: \"GEMINI.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 20,\n },\n {\n id: \"CLAUDE.md\",\n pattern: \"CLAUDE.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 30,\n },\n {\n id: \"cursor-rules\",\n pattern: \".cursor/rules/*.mdc\",\n scope: \"globbed\",\n parser: \"mdc\",\n followImports: false,\n priority: 40,\n },\n {\n id: \"theokit-rules\",\n pattern: \".theokit/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 45,\n },\n {\n id: \"theokit-context\",\n pattern: \".theokit/context/*.md\",\n scope: \"globbed\",\n parser: \"frontmatter-zod\",\n followImports: false,\n priority: 50,\n },\n {\n id: \"THEO.md\",\n pattern: \".theokit/THEO.md\",\n scope: \"cwd-only\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 60,\n },\n];\n\nconst SAFE_FILENAME = /^[a-zA-Z0-9_.\\-/*]+$/;\nconst TRAVERSAL_RE = /(^|\\/)\\.\\.(\\/|$)/;\n\n/**\n * Reject patterns that contain path traversal (`..`) or non-allowed\n * characters (D81 parity, EC-4).\n *\n * @internal\n */\nexport function isSafePattern(pattern: string): boolean {\n if (typeof pattern !== \"string\" || pattern.length === 0) return false;\n if (TRAVERSAL_RE.test(pattern)) return false;\n if (isAbsolute(pattern)) return false;\n return SAFE_FILENAME.test(pattern);\n}\n\n/**\n * Walk upward from `cwd` looking for the closest directory containing\n * a `.git` entry (file OR directory — worktrees use a `.git` FILE,\n * EC-N). Returns the absolute path of that directory, or `undefined`\n * when no git root exists at or above `cwd`.\n *\n * @internal\n */\nexport function findGitRoot(cwd: string): string | undefined {\n if (typeof cwd !== \"string\" || cwd.length === 0) return undefined;\n let current = resolve(cwd);\n // Guard against infinite loops on weird filesystems.\n for (let i = 0; i < 64; i += 1) {\n if (existsSync(join(current, \".git\"))) return current;\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return undefined;\n}\n\n/**\n * Walk `cwd` upward to `stopDir` (inclusive) collecting every existing\n * occurrence of `filename`. Returns absolute, realpath-deduped paths in\n * nearest-first order (innermost dir first).\n *\n * No `.gitignore` parsing (EC-A). Realpath collapses symlink chains\n * pointing to the same physical file (EC-F). Filesystem races (file\n * deleted mid-walk) are skipped silently (EC-5).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walk-up loop combines validation + realpath dedup + FS-race handling + stopDir guard in a single bounded loop; splitting fragments the dedup invariant.\nexport function walkUpForFile(\n cwd: string,\n filename: string,\n stopDir: string | undefined,\n): string[] {\n if (!isSafePattern(filename)) {\n return [];\n }\n const start = resolve(cwd);\n const stop = stopDir !== undefined ? resolve(stopDir) : undefined;\n const found: string[] = [];\n const seenReal = new Set<string>();\n let current = start;\n // 64-level depth cap.\n for (let i = 0; i < 64; i += 1) {\n const candidate = join(current, filename);\n if (existsSync(candidate)) {\n let real: string;\n try {\n real = realpathSync(candidate);\n } catch {\n // FS race (deleted mid-walk) — skip.\n real = candidate;\n }\n if (!seenReal.has(real)) {\n seenReal.add(real);\n found.push(real);\n }\n }\n if (stop !== undefined && current === stop) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return found;\n}\n\n/**\n * Glob-style discovery scoped to a single directory under cwd (e.g.\n * `.cursor/rules/*.mdc`). Flat — does NOT recurse into subdirectories\n * (EC-R: nested directories deferred to v2). Returns absolute,\n * lex-sorted paths.\n *\n * @internal\n */\nexport async function walkUpForGlob(cwd: string, pattern: string): Promise<string[]> {\n if (!isSafePattern(pattern)) return [];\n const lastSlash = pattern.lastIndexOf(\"/\");\n if (lastSlash < 0) {\n // Single filename — treat as cwd-only single match.\n const candidate = join(cwd, pattern);\n return existsSync(candidate) ? [resolve(candidate)] : [];\n }\n const dirPart = pattern.slice(0, lastSlash);\n const filePart = pattern.slice(lastSlash + 1);\n const dir = join(cwd, dirPart);\n if (!existsSync(dir)) return [];\n // Build a regex from the file part — supports only `*` wildcard.\n const fileRe = filePartToRegex(filePart);\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n const matched = entries.filter((e) => fileRe.test(e)).sort();\n return matched.map((e) => resolve(join(dir, e)));\n}\n\nfunction filePartToRegex(filePart: string): RegExp {\n const escaped = filePart.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(`^${escaped}$`);\n}\n"]}
@@ -0,0 +1,253 @@
1
+ import { atomicWriteText } from './chunk-S2BBRVQX.js';
2
+ import { mkdir, readFile, readdir } from 'fs/promises';
3
+ import { join } from 'path';
4
+
5
+ // src/types/workflow.ts
6
+ var WorkflowDuplicateStepIdError = class extends Error {
7
+ constructor(stepId) {
8
+ super(`Duplicate step id "${stepId}" in workflow.`);
9
+ this.stepId = stepId;
10
+ }
11
+ stepId;
12
+ name = "WorkflowDuplicateStepIdError";
13
+ };
14
+ var WorkflowInputError = class extends Error {
15
+ constructor(workflowName, detail) {
16
+ super(`Workflow "${workflowName}" input failed schema validation: ${detail}`);
17
+ this.workflowName = workflowName;
18
+ this.detail = detail;
19
+ }
20
+ workflowName;
21
+ detail;
22
+ name = "WorkflowInputError";
23
+ };
24
+ var WorkflowOutputError = class extends Error {
25
+ constructor(workflowName, detail) {
26
+ super(`Workflow "${workflowName}" output failed schema validation: ${detail}`);
27
+ this.workflowName = workflowName;
28
+ this.detail = detail;
29
+ }
30
+ workflowName;
31
+ detail;
32
+ name = "WorkflowOutputError";
33
+ };
34
+ var WorkflowStateError = class extends Error {
35
+ constructor(workflowName, detail) {
36
+ super(`Workflow "${workflowName}" state failed schema validation: ${detail}`);
37
+ this.workflowName = workflowName;
38
+ this.detail = detail;
39
+ }
40
+ workflowName;
41
+ detail;
42
+ name = "WorkflowStateError";
43
+ };
44
+ var WorkflowNestedError = class extends Error {
45
+ constructor(stepId, childName, childStatus, childError) {
46
+ super(
47
+ `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}` : ""}`,
48
+ // Reconstruct a synthetic Error from the serialized child-error shape so
49
+ // debuggers surface the nested cause chain — the original Error instance is
50
+ // lost at the WorkflowRun serialization boundary, so this is the best
51
+ // achievable without changing the run protocol.
52
+ childError ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) } : void 0
53
+ );
54
+ this.stepId = stepId;
55
+ this.childName = childName;
56
+ this.childStatus = childStatus;
57
+ this.childError = childError;
58
+ }
59
+ stepId;
60
+ childName;
61
+ childStatus;
62
+ childError;
63
+ name = "WorkflowNestedError";
64
+ };
65
+ var WorkflowAlreadyRunningError = class extends Error {
66
+ constructor(workflowName, runId) {
67
+ super(`Workflow "${workflowName}" run "${runId}" already in-flight.`);
68
+ this.workflowName = workflowName;
69
+ this.runId = runId;
70
+ }
71
+ workflowName;
72
+ runId;
73
+ name = "WorkflowAlreadyRunningError";
74
+ };
75
+ var WorkflowSnapshotNotFoundError = class extends Error {
76
+ constructor(runId) {
77
+ super(`No snapshot found for runId "${runId}". Configure persistence to enable resume.`);
78
+ this.runId = runId;
79
+ }
80
+ runId;
81
+ name = "WorkflowSnapshotNotFoundError";
82
+ };
83
+ var WorkflowMaxIterationsExceededError = class extends Error {
84
+ constructor(stepId, maxIterations) {
85
+ super(`Step "${stepId}" exceeded max iterations (${maxIterations}).`);
86
+ this.stepId = stepId;
87
+ this.maxIterations = maxIterations;
88
+ }
89
+ stepId;
90
+ maxIterations;
91
+ name = "WorkflowMaxIterationsExceededError";
92
+ };
93
+ var WorkflowNotSerializableError = class extends Error {
94
+ constructor(stepId, underlying) {
95
+ super(
96
+ `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).`
97
+ );
98
+ this.stepId = stepId;
99
+ this.underlying = underlying;
100
+ }
101
+ stepId;
102
+ underlying;
103
+ name = "WorkflowNotSerializableError";
104
+ };
105
+ var WorkflowResumeStepNotFoundError = class extends Error {
106
+ constructor(stepId, workflowName) {
107
+ super(
108
+ `Cannot resume: step "${stepId}" not found in workflow "${workflowName}". The Workflow definition diverged from the snapshot.`
109
+ );
110
+ this.stepId = stepId;
111
+ this.workflowName = workflowName;
112
+ }
113
+ stepId;
114
+ workflowName;
115
+ name = "WorkflowResumeStepNotFoundError";
116
+ };
117
+ var WorkflowParallelError = class extends AggregateError {
118
+ constructor(errors, stepId) {
119
+ super(errors, `${errors.length} branch(es) failed in parallel step "${stepId}".`);
120
+ this.stepId = stepId;
121
+ }
122
+ stepId;
123
+ name = "WorkflowParallelError";
124
+ };
125
+ var WorkflowCompensateNotImplementedError = class extends Error {
126
+ constructor(stepId) {
127
+ super(
128
+ `Step "${stepId}" defines compensate, but saga engine is deferred to v1.2. Remove compensate or implement rollback manually.`
129
+ );
130
+ this.stepId = stepId;
131
+ }
132
+ stepId;
133
+ name = "WorkflowCompensateNotImplementedError";
134
+ };
135
+ var InMemoryWorkflowSnapshotStore = class {
136
+ map = /* @__PURE__ */ new Map();
137
+ async save(snapshot) {
138
+ try {
139
+ JSON.stringify(snapshot);
140
+ } catch (err) {
141
+ throw new WorkflowNotSerializableError(
142
+ snapshot.currentStepId,
143
+ err instanceof Error ? err : new Error(String(err))
144
+ );
145
+ }
146
+ this.map.set(snapshot.runId, snapshot);
147
+ }
148
+ async load(runId) {
149
+ return this.map.get(runId);
150
+ }
151
+ async delete(runId) {
152
+ this.map.delete(runId);
153
+ }
154
+ async list(workflowName) {
155
+ return [...this.map.values()].filter((s) => workflowName === void 0 || s.workflowName === workflowName).map((s) => ({
156
+ runId: s.runId,
157
+ workflowName: s.workflowName,
158
+ suspendedAt: s.suspendedAt
159
+ }));
160
+ }
161
+ };
162
+ var JsonFileWorkflowSnapshotStore = class {
163
+ constructor(dir) {
164
+ this.dir = dir;
165
+ }
166
+ dir;
167
+ filePath(runId) {
168
+ return join(this.dir, `${runId}.json`);
169
+ }
170
+ async save(snapshot) {
171
+ let serialized;
172
+ try {
173
+ serialized = JSON.stringify(snapshot);
174
+ } catch (err) {
175
+ throw new WorkflowNotSerializableError(
176
+ snapshot.currentStepId,
177
+ err instanceof Error ? err : new Error(String(err))
178
+ );
179
+ }
180
+ await mkdir(this.dir, { recursive: true });
181
+ await atomicWriteText(this.filePath(snapshot.runId), serialized);
182
+ }
183
+ async load(runId) {
184
+ try {
185
+ const raw = await readFile(this.filePath(runId), "utf8");
186
+ return JSON.parse(raw);
187
+ } catch (err) {
188
+ if (err.code === "ENOENT") return void 0;
189
+ throw err;
190
+ }
191
+ }
192
+ async delete(runId) {
193
+ try {
194
+ await (await import('fs/promises')).unlink(this.filePath(runId));
195
+ } catch (err) {
196
+ if (err.code !== "ENOENT") throw err;
197
+ }
198
+ }
199
+ async readEntriesOrEmpty() {
200
+ try {
201
+ return await readdir(this.dir);
202
+ } catch (err) {
203
+ if (err.code === "ENOENT") return [];
204
+ throw err;
205
+ }
206
+ }
207
+ async readSnapshotSafe(file) {
208
+ try {
209
+ const raw = await readFile(join(this.dir, file), "utf8");
210
+ return JSON.parse(raw);
211
+ } catch {
212
+ return void 0;
213
+ }
214
+ }
215
+ async list(workflowName) {
216
+ const entries = await this.readEntriesOrEmpty();
217
+ const results = [];
218
+ for (const file of entries) {
219
+ if (!file.endsWith(".json")) continue;
220
+ const snap = await this.readSnapshotSafe(file);
221
+ if (snap === void 0) continue;
222
+ if (workflowName !== void 0 && snap.workflowName !== workflowName) continue;
223
+ results.push({
224
+ runId: snap.runId,
225
+ workflowName: snap.workflowName,
226
+ suspendedAt: snap.suspendedAt
227
+ });
228
+ }
229
+ return results;
230
+ }
231
+ };
232
+ var memoryStore = new InMemoryWorkflowSnapshotStore();
233
+ var jsonStores = /* @__PURE__ */ new Map();
234
+ function getSnapshotStoreFor(options) {
235
+ if (options.persistence?.backend === "json") {
236
+ const dir = options.persistence.dir;
237
+ let store = jsonStores.get(dir);
238
+ if (store === void 0) {
239
+ store = new JsonFileWorkflowSnapshotStore(dir);
240
+ jsonStores.set(dir, store);
241
+ }
242
+ return store;
243
+ }
244
+ return memoryStore;
245
+ }
246
+ function __resetSnapshotStoresForTests() {
247
+ jsonStores.clear();
248
+ memoryStore.map.clear();
249
+ }
250
+
251
+ export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests, getSnapshotStoreFor };
252
+ //# sourceMappingURL=chunk-UVNG67DG.js.map
253
+ //# sourceMappingURL=chunk-UVNG67DG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapshot-store.ts"],"names":[],"mappings":";;;;;AA2RO,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAEtD,YAA4B,MAAA,EAAgB;AAC1C,IAAA,KAAA,CAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,cAAA,CAAgB,CAAA;AADxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAE5B;AAAA,EAF4B,MAAA;AAAA,EADV,IAAA,GAAO,8BAAA;AAI3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,kCAAA,EAAqC,MAAM,CAAA,CAAE,CAAA;AAH5D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,oBAAA;AAO3B;AAMO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAE7C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,mCAAA,EAAsC,MAAM,CAAA,CAAE,CAAA;AAH7D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,qBAAA;AAO3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,E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7C,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-UVNG67DG.js","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import { createSemaphore } from './chunk-5PZMMF4H.js';
2
+
3
+ // src/internal/runtime/concurrency/map-with-concurrency.ts
4
+ var NEVER_ABORT = new AbortController().signal;
5
+ async function mapWithConcurrency(items, concurrency, fn, options) {
6
+ const semaphore = createSemaphore(concurrency);
7
+ const signal = options?.signal ?? NEVER_ABORT;
8
+ return Promise.all(
9
+ items.map(async (item, index) => {
10
+ const release = await semaphore.acquire();
11
+ try {
12
+ if (signal.aborted) {
13
+ throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
14
+ }
15
+ return await fn(item, index, signal);
16
+ } finally {
17
+ release();
18
+ }
19
+ })
20
+ );
21
+ }
22
+
23
+ export { mapWithConcurrency };
24
+ //# sourceMappingURL=chunk-V4XRLPEF.js.map
25
+ //# sourceMappingURL=chunk-V4XRLPEF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-V4XRLPEF.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}