@makaio/framework 1.0.0-dev-1788966380232 → 1.0.0-dev-1789000242829

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 (244) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/{2020-CpDjcHDh.mjs → 2020-DvDj4r_K.mjs} +1 -1
  3. package/dist/{account-identity-D00LLclm.mjs → account-identity-CNdiLYaM.mjs} +1 -1
  4. package/dist/{adapter-D92pfm_b.mjs → adapter-BdMny6vw.mjs} +1 -1
  5. package/dist/adapters/claude/index.d.mts +24 -24
  6. package/dist/adapters/index.mjs +1 -1
  7. package/dist/artifact-Cxm5ZX7L.mjs +1 -0
  8. package/dist/{auth-CB4an9bh.mjs → auth-BIgwGHp-.mjs} +1 -1
  9. package/dist/authority-state-bootstrap-DVFYemDL.mjs +1 -0
  10. package/dist/{automation-trigger-xNDX0Am_.mjs → automation-trigger-CQNQpzkA.mjs} +1 -1
  11. package/dist/bus/index.mjs +8 -1
  12. package/dist/{caller-owned-adapter-stub-oM1G1KvC.mjs → caller-owned-adapter-stub-NiR7KT2N.mjs} +1 -1
  13. package/dist/{canonical-model-D7Cg0l2R.mjs → canonical-model-BMnzRhG_.mjs} +1 -1
  14. package/dist/{capabilities-D2ggcMem.mjs → capabilities-CEwSeTB3.mjs} +1 -1
  15. package/dist/{client-CpUVfDxa.mjs → client-C0HcPzvw.mjs} +1 -1
  16. package/dist/{code-execution-CMqsHnGg.mjs → code-execution-BhUo84eg.mjs} +1 -1
  17. package/dist/{compression-Civ-rf-O.mjs → compression-DvPXSBWS.mjs} +1 -1
  18. package/dist/{config-namespace-CQnsvr77.mjs → config-namespace-CE3KasJn.mjs} +1 -1
  19. package/dist/contracts/adapter/index.d.mts +1 -1
  20. package/dist/contracts/adapter/index.mjs +1 -1
  21. package/dist/contracts/artifact/index.d.mts +3 -3
  22. package/dist/contracts/artifact/index.mjs +1 -1
  23. package/dist/contracts/auth/index.mjs +1 -1
  24. package/dist/contracts/automation-trigger/index.mjs +1 -1
  25. package/dist/contracts/canonical-model/index.mjs +1 -1
  26. package/dist/contracts/capabilities/index.d.mts +1 -1
  27. package/dist/contracts/capabilities/index.mjs +1 -1
  28. package/dist/contracts/client/index.d.mts +1 -1
  29. package/dist/contracts/client/index.mjs +1 -1
  30. package/dist/contracts/code-execution/index.mjs +1 -1
  31. package/dist/contracts/common/index.mjs +1 -1
  32. package/dist/contracts/config/index.mjs +1 -1
  33. package/dist/contracts/extension/index.d.mts +2 -2
  34. package/dist/contracts/extension/index.mjs +1 -1
  35. package/dist/contracts/facet/index.d.mts +1 -1
  36. package/dist/contracts/facet/index.mjs +1 -1
  37. package/dist/contracts/harness/index.d.mts +1 -1
  38. package/dist/contracts/harness/index.mjs +1 -1
  39. package/dist/contracts/host/index.mjs +1 -1
  40. package/dist/contracts/index.d.mts +92 -226
  41. package/dist/contracts/index.mjs +1 -1
  42. package/dist/contracts/materialization/index.d.mts +2 -2
  43. package/dist/contracts/materialization/index.mjs +1 -1
  44. package/dist/contracts/model-registry/index.mjs +1 -1
  45. package/dist/contracts/native-session-supervisor/index.mjs +1 -1
  46. package/dist/contracts/platform/index.mjs +1 -1
  47. package/dist/contracts/provider/index.mjs +1 -1
  48. package/dist/contracts/reaction/index.mjs +1 -1
  49. package/dist/contracts/session/index.d.mts +2 -2
  50. package/dist/contracts/session/index.mjs +1 -1
  51. package/dist/contracts/shared/index.mjs +1 -1
  52. package/dist/contracts/skill/index.mjs +1 -1
  53. package/dist/contracts/telemetry/index.mjs +1 -1
  54. package/dist/contracts/timeout/index.mjs +1 -1
  55. package/dist/contracts/toast/index.mjs +1 -1
  56. package/dist/contracts/variant/index.d.mts +1 -1
  57. package/dist/contracts/variant/index.mjs +1 -1
  58. package/dist/contracts/worker/index.d.mts +1 -1
  59. package/dist/contracts/worker/index.mjs +1 -1
  60. package/dist/contracts/workflow/index.d.mts +3 -3
  61. package/dist/contracts/workflow/index.mjs +1 -1
  62. package/dist/{definition-Dqw0YJdi.mjs → definition-o5Dfg5j-.mjs} +1 -1
  63. package/dist/{dist-DeI9zYMP.mjs → dist-DMIaE8sg.mjs} +1 -1
  64. package/dist/{execution-attempt-repository--RVils5-.d.mts → execution-attempt-repository-DSpz2kyW.d.mts} +7 -25
  65. package/dist/{execution-target-_oVNW6Zm.mjs → execution-target-Ba7b_UmX.mjs} +1 -1
  66. package/dist/{extension-CAi7bbyv.mjs → extension-D9D8tJQY.mjs} +1 -1
  67. package/dist/{extension-CrghVa93.mjs → extension-GQEL-NCV.mjs} +1 -1
  68. package/dist/{framework-packages-BOPhhtK7.mjs → framework-packages-DdCJ4JsE.mjs} +1 -1
  69. package/dist/{handlers-YPTyZDhF.mjs → handlers-CqL2TWbk.mjs} +1 -1
  70. package/dist/{harness-Ds1I4smU.mjs → harness-CYzkReGi.mjs} +1 -1
  71. package/dist/{index-LjLUr3Dm.d.mts → index-BIlFSGnW.d.mts} +10 -10
  72. package/dist/{index-BqR2xDu6.d.mts → index-BTluq4-E.d.mts} +151 -108
  73. package/dist/{index-nJvYTAbD.d.mts → index-BfwHYuRf.d.mts} +1 -1
  74. package/dist/{index-MtDz_goH.d.mts → index-BxJRljy-.d.mts} +274 -86
  75. package/dist/{index-BKwYE1Qk.d.mts → index-Bzxs2nVR.d.mts} +5 -5
  76. package/dist/{index-BkQlL0Pl.d.mts → index-CCNCo440.d.mts} +5 -5
  77. package/dist/{index-v9TbeVee2.d.mts → index-CRM23ToM2.d.mts} +5 -5
  78. package/dist/{index-Bxq_zO2E.d.mts → index-CilWtThn.d.mts} +4 -4
  79. package/dist/{index-B7wjmaev.d.mts → index-CjMMvZch.d.mts} +12 -12
  80. package/dist/{index-ud9i9pue.d.mts → index-DCHdW5g-.d.mts} +16 -16
  81. package/dist/{index-BT5qcsEf2.d.mts → index-DR308wUB2.d.mts} +18 -18
  82. package/dist/{index-DU9Y9tes2.d.mts → index-Dckvm0Ml2.d.mts} +12 -12
  83. package/dist/{index-Bnm0QvJ4.d.mts → index-DvoitgXV.d.mts} +9 -9
  84. package/dist/{index-DzlGAEws.d.mts → index-Dzozmb5u.d.mts} +1 -1
  85. package/dist/{index-DO633_D-.d.mts → index-GTCM4lXx.d.mts} +38 -38
  86. package/dist/{index-09eal6WI2.d.mts → index-hm8NV4CJ2.d.mts} +7 -7
  87. package/dist/kernel/cli/index.mjs +1 -1
  88. package/dist/kernel/cli/register.mjs +1 -1
  89. package/dist/kernel/cli/schemas.mjs +1 -1
  90. package/dist/kernel/extension/index.d.mts +1 -1
  91. package/dist/kernel/extension/index.mjs +1 -1
  92. package/dist/kernel/index.d.mts +2 -2
  93. package/dist/kernel/index.mjs +1 -1
  94. package/dist/kernel/namespace/index.mjs +1 -1
  95. package/dist/kernel/observability/index.d.mts +1 -1
  96. package/dist/kernel/observability/index.mjs +1 -1
  97. package/dist/kernel/providers/index.mjs +1 -1
  98. package/dist/kernel/window/index.mjs +1 -1
  99. package/dist/kind-registration-BanX_UAF.mjs +1 -0
  100. package/dist/{materialization-BwC7pVg2.mjs → materialization--bg6ZwQd.mjs} +1 -1
  101. package/dist/mcp-http-server/index.mjs +1 -1
  102. package/dist/model-Dya0clsM.mjs +1 -0
  103. package/dist/{namespace-wuGMWlyz.d.mts → namespace-B0_Sg-1m.d.mts} +2 -2
  104. package/dist/{namespace-CnRcpgJ8.mjs → namespace-CD9mJGhU.mjs} +1 -1
  105. package/dist/{namespace-BYsKOw-g.d.mts → namespace-CY-9Evdf.d.mts} +3 -3
  106. package/dist/{namespace-B1sjokHd.d.mts → namespace-CfA0C0JR.d.mts} +2 -2
  107. package/dist/namespace-D53UGrP6.mjs +1 -0
  108. package/dist/{namespace-Cy62a3YP.d.mts → namespace-Dmbm2JzV.d.mts} +2 -2
  109. package/dist/{native-session-supervisor-B0rziwHI.mjs → native-session-supervisor-i3PeijHn.mjs} +1 -1
  110. package/dist/{orchestrator-shared-CmS8iU9_.mjs → orchestrator-shared-DMldWEah.mjs} +1 -1
  111. package/dist/{ownership-memory-handler-DMirNILL.mjs → ownership-memory-handler-LXaweX6V.mjs} +1 -1
  112. package/dist/{package-Co36_pRw.mjs → package-BFto8lbP.mjs} +1 -1
  113. package/dist/package-BT94BLu4.mjs +7 -0
  114. package/dist/{package-Bl0mcGb8.d.mts → package-BaTrCWZl.d.mts} +46 -42
  115. package/dist/package.json +1 -1
  116. package/dist/packages-DAw3Z011.mjs +1 -0
  117. package/dist/{profile-C9RV7ao-.mjs → profile-Cjq4QnUQ.mjs} +1 -1
  118. package/dist/{provider-context-BPITm0cn.mjs → provider-context-BpabfMlj.mjs} +1 -1
  119. package/dist/{provider-context-CyGvwXPz.mjs → provider-context-CYUUoI6x.mjs} +1 -1
  120. package/dist/{resolved-M6PyrgFr.mjs → resolved-XQTiHgrA.mjs} +1 -1
  121. package/dist/runtime-node/index.d.mts +1 -1
  122. package/dist/runtime-node/index.mjs +1 -1
  123. package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
  124. package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
  125. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  126. package/dist/{schema-DrHrto2J.mjs → schema-BVbkNHVQ.mjs} +1 -1
  127. package/dist/{schemas-DGKWi7mk.d.mts → schemas-CQe4xCRn.d.mts} +2 -2
  128. package/dist/{schemas-D2HmGmCt.d.mts → schemas-CSeLgroC.d.mts} +1 -1
  129. package/dist/{schemas-DRho446W.mjs → schemas-NKlV5jqJ.mjs} +1 -1
  130. package/dist/{schemas-DyZNwquY.mjs → schemas-QEr2LI43.mjs} +1 -1
  131. package/dist/{schemas-CvUe_yff.d.mts → schemas-bcDK-fK3.d.mts} +18 -9
  132. package/dist/{schemas-CQKfd2Xd.mjs → schemas-pHboaOxJ.mjs} +1 -1
  133. package/dist/{schemas-BYyT43gX.d.mts → schemas-yXs929kr.d.mts} +3 -3
  134. package/dist/{selection-BDs7K53w.mjs → selection-D7V0wyHX.mjs} +1 -1
  135. package/dist/services/adapter-runtime/index.d.mts +3 -3
  136. package/dist/services/adapter-runtime/index.mjs +1 -1
  137. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  138. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  139. package/dist/services/adapter-subsystem/index.mjs +1 -1
  140. package/dist/services/adapter-subsystem/namespace.mjs +1 -1
  141. package/dist/services/agent-runtime/index.d.mts +2 -2
  142. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  143. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  144. package/dist/services/context-rules/index.d.mts +3 -3
  145. package/dist/services/execution-target/index.mjs +1 -1
  146. package/dist/services/execution-target/namespace.mjs +1 -1
  147. package/dist/services/execution-target/schemas.mjs +1 -1
  148. package/dist/services/harness/index.d.mts +3 -3
  149. package/dist/services/index.d.mts +14 -14
  150. package/dist/services/index.mjs +1 -1
  151. package/dist/services/materialization/index.mjs +1 -1
  152. package/dist/services/provider-context/index.mjs +1 -1
  153. package/dist/services/session/handlers/index.mjs +1 -1
  154. package/dist/services/session/index.d.mts +1 -1
  155. package/dist/services/session/index.mjs +1 -1
  156. package/dist/services/session/messages/namespace.d.mts +1 -1
  157. package/dist/services/session/messages/namespace.mjs +1 -1
  158. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  159. package/dist/services/session/session-events/namespace.mjs +1 -1
  160. package/dist/services/session/testing/index.mjs +1 -1
  161. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  162. package/dist/services/session/turns/namespace.mjs +1 -1
  163. package/dist/services/session-editor/index.mjs +1 -1
  164. package/dist/services/settings/index.mjs +1 -1
  165. package/dist/services/settings/storage/clients-namespace.mjs +1 -1
  166. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  167. package/dist/services/settings/storage/index.mjs +1 -1
  168. package/dist/services/settings/storage/providers-namespace.mjs +1 -1
  169. package/dist/services/subagent/index.mjs +1 -1
  170. package/dist/services/subagent-template/index.d.mts +2 -2
  171. package/dist/services/subagent-template/namespace.d.mts +1 -1
  172. package/dist/services/subagent-template/schemas.d.mts +1 -1
  173. package/dist/services/tool-approval/index.mjs +1 -1
  174. package/dist/services/tools/index.mjs +1 -1
  175. package/dist/services/workflow-transitions/index.mjs +1 -1
  176. package/dist/{session-Cn8z1hxD.mjs → session-CAKfa5o8.mjs} +1 -1
  177. package/dist/{session-9C42TPQq.mjs → session-CODDwsGa.mjs} +1 -1
  178. package/dist/{shared-DqvfJVYk.mjs → shared-CkCrHz66.mjs} +1 -1
  179. package/dist/{skill-BmRp8GhW.mjs → skill-91kZNQnF.mjs} +1 -1
  180. package/dist/{tool-approval-service-DchkAdAr.mjs → tool-approval-service-BV3WxxX6.mjs} +1 -1
  181. package/dist/{tools-r50UBPJ9.mjs → tools-CElCajoS.mjs} +1 -1
  182. package/dist/{transition-CgsrmsfE.d.mts → transition-bYkXnLY2.d.mts} +1 -1
  183. package/dist/{types-ZvPhKp3j.d.mts → types-BNKqcHfP.d.mts} +5 -5
  184. package/dist/{version-sDSWOMn_.mjs → version-DdGhNoY5.mjs} +1 -1
  185. package/dist/{view-builder-D54kvyf7.d.mts → view-builder-CA5qUx85.d.mts} +10 -10
  186. package/dist/{visibility-syKffo3e.mjs → visibility-cMXbf9nY.mjs} +1 -1
  187. package/dist/{worker-DRQGyWAS.mjs → worker-B0xwfo9-.mjs} +1 -1
  188. package/dist/{worker-DzbPk2YI.mjs → worker-Cx1JDOB9.mjs} +1 -1
  189. package/dist/{workflow-D-yrAZW8.mjs → workflow-5yHn_Knq.mjs} +1 -1
  190. package/dist/workflow-engine/execution-attempt-repository.d.mts +1 -1
  191. package/dist/workflow-engine/index.d.mts +70 -70
  192. package/dist/workflow-engine/index.mjs +1 -1
  193. package/dist/workflow-engine/package.d.mts +1 -1
  194. package/dist/workflow-engine/package.mjs +1 -1
  195. package/dist/workflow-engine/provider-operation.d.mts +1 -1
  196. package/dist/workflow-engine/testing/conformance.d.mts +1 -1
  197. package/dist/workflow-engine/testing/index.d.mts +15 -4
  198. package/dist/workflow-engine/testing/index.mjs +1 -1
  199. package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
  200. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  201. package/dist/{workflow-transitions-D5RvMSnf.mjs → workflow-transitions-DH246j6E.mjs} +1 -1
  202. package/dist/workflow-worker-BAO7pQpx.mjs +2 -0
  203. package/package.json +1 -1
  204. package/dist/artifact-_pN73_7c.mjs +0 -1
  205. package/dist/authority-state-bootstrap-DgoHPc9J.mjs +0 -1
  206. package/dist/kind-registration-DggkrLkv.mjs +0 -1
  207. package/dist/model-Cn1IFEP8.mjs +0 -1
  208. package/dist/namespace-DFc1nkal.mjs +0 -1
  209. package/dist/package-B-xpYKe8.mjs +0 -7
  210. package/dist/packages-COqPg5TI.mjs +0 -1
  211. package/dist/workflow-worker-CrnDwpkP.mjs +0 -2
  212. /package/dist/{ajv-IlnfOGAj.mjs → ajv-Dz-0DD7m.mjs} +0 -0
  213. /package/dist/{attach-error-DOlUtquX.mjs → attach-error-D5BWfaBO.mjs} +0 -0
  214. /package/dist/{capability-BQHyskJB.mjs → capability-BnQx1BWc.mjs} +0 -0
  215. /package/dist/{common-CylczUIW.mjs → common-Bta2ivrd.mjs} +0 -0
  216. /package/dist/{definitions-2T95Q-y6.mjs → definitions-CyFaNG_c.mjs} +0 -0
  217. /package/dist/{extension-namespace-CWfV3IiR.mjs → extension-namespace-AaHKv6tQ.mjs} +0 -0
  218. /package/dist/{facet-6tnSbjXc.mjs → facet-De-2AP_o.mjs} +0 -0
  219. /package/dist/{host-D7v3YlDG.mjs → host-CbaJg6D4.mjs} +0 -0
  220. /package/dist/{identity-CxMRRAXx.mjs → identity-B6RqbCn7.mjs} +0 -0
  221. /package/dist/{model-registry-BTjKBCCw.mjs → model-registry-DVTFd0RF.mjs} +0 -0
  222. /package/dist/{modes-Bo9Vv5c9.mjs → modes-Dc9_sSbr.mjs} +0 -0
  223. /package/dist/{namespace-DX3QsYpv.mjs → namespace-BZ7UQmW4.mjs} +0 -0
  224. /package/dist/{namespace-Dyxpur8_.mjs → namespace-BnNBM94X.mjs} +0 -0
  225. /package/dist/{namespace-DORNUF0_.mjs → namespace-DGi7tw_W.mjs} +0 -0
  226. /package/dist/{namespace-BCSJz417.mjs → namespace-KYIbWPvl.mjs} +0 -0
  227. /package/dist/{ownership-recovery-guard-CYA5CsiO.mjs → ownership-recovery-guard-BIB5uqgz.mjs} +0 -0
  228. /package/dist/{platform-BdLHWgVc.mjs → platform-BObC-WJA.mjs} +0 -0
  229. /package/dist/{providers-DGTA-lki.mjs → providers-BysYiNMO.mjs} +0 -0
  230. /package/dist/{reaction-aQJGWUWl.mjs → reaction-Cev6JNcb.mjs} +0 -0
  231. /package/dist/{schema-mXXJcaQT.mjs → schema-bfw9nz8B.mjs} +0 -0
  232. /package/dist/{schema-introspection-BsWP1vGC.mjs → schema-introspection-BTS7FZT_.mjs} +0 -0
  233. /package/dist/{schemas-HffXbw8C.mjs → schemas-A2hlgeNu.mjs} +0 -0
  234. /package/dist/{schemas-NYUz8K9Q.mjs → schemas-B3UNnzKG.mjs} +0 -0
  235. /package/dist/{schemas-7fHmNUQc.mjs → schemas-BEDq3Psz.mjs} +0 -0
  236. /package/dist/{schemas-MIYusvwn.mjs → schemas-mLjTSUvJ.mjs} +0 -0
  237. /package/dist/{semver-_h8-BJ8k.mjs → semver-ByPlHR3P.mjs} +0 -0
  238. /package/dist/{shared-schemas-CaL1iEk6.mjs → shared-schemas-CKsgVsGX.mjs} +0 -0
  239. /package/dist/{storage-namespace-definition-4UYuij1r.mjs → storage-namespace-definition-Ct9ohqU0.mjs} +0 -0
  240. /package/dist/{telemetry-BLYrkonr.mjs → telemetry-Be3u4I7b.mjs} +0 -0
  241. /package/dist/{timeout-d0dzIY3V.mjs → timeout-Bscg1B-y.mjs} +0 -0
  242. /package/dist/{ui-config-CsH94fwa.mjs → ui-config-Bl2Wbkr-.mjs} +0 -0
  243. /package/dist/{variant-BZ9UcJBi.mjs → variant-B5j5wR2p.mjs} +0 -0
  244. /package/dist/{window-registry-DQkv5wM9.mjs → window-registry-DWHz8TA5.mjs} +0 -0
@@ -1 +1 @@
1
- import{C as e,E as t,H as n,K as ee,L as te,Q as r,S as i,T as a,U as o,W as s,_ as c,b as l,ct as u,et as d,ft as f,gt as p,nt as m,v as h,vt as g,w as _,x as v,y}from"../authority-state-bootstrap-DgoHPc9J.mjs";import{_ as b,a as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,t as F,u as I}from"../package-B-xpYKe8.mjs";import{_ as L,a as R,b as ne,c as z,d as B,f as V,g as H,h as U,i as W,l as G,m as K,n as q,o as J,p as Y,r as X,s as Z,t as re,u as ie,x as ae,y as oe}from"../execution-attempt-repository-CWbgCTwA.mjs";import{assertWorkflowTriggerPayload as se,compileWorkflowTriggerBindingFilter as ce}from"./workflow-trigger-binding-consumer.mjs";import{a as le,i as ue,n as de,r as fe,t as pe}from"../execution-attempt-owner-recovery-D4APLAvt.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as me,isProviderOperationResolved as he}from"./provider-operation.mjs";import{JsonValueSchema as Q,WorkflowFrameStateSchema as ge}from"@makaio/framework/contracts";const _e=new Set([...ge.shape.status.options]);function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ve(e){if(!$(e))return!1;for(let t of Object.values(e))if(!$(t)||typeof t.status!=`string`||!_e.has(t.status)||`result`in t&&t.result!==void 0&&!Q.safeParse(t.result).success)return!1;return!0}function ye(e){let t={trigger:$(e.trigger)?e.trigger:{},steps:ve(e.steps)?e.steps:{},inputs:Q.safeParse(e.inputs).success?e.inputs:{}};return`item`in e&&(t.item=e.item),typeof e.index==`number`&&(t.index=e.index),t}export{re as ATTEMPT_OPERATION_START_GATES,q as DuplicateExecutionAttemptError,X as EXECUTION_ATTEMPT_SETTLEMENT_KINDS,W as EXECUTION_ATTEMPT_STATUSES,x as ExecutionAttemptAuthority,me as PROVIDER_OPERATION_OBLIGATIONS,O as RUNTIME_PROBE_DELIVERY_TIMEOUT_MS,Y as RuntimeOutcomeFenceMismatchError,v as WORKFLOW_WORKLOAD_KIND,i as WORKFLOW_WORKLOAD_VERSION,c as WorkflowAttemptOutcomeSchema,D as WorkflowEngineService,F as WorkflowEngineToken,P as WorkflowExecutor,e as WorkflowInvocationInputSchema,o as WorkflowStorageNamespace,s as WorkflowStorageSubjects,j as WorkflowTriggerReconciler,K as assertRuntimeOutcomeFence,se as assertWorkflowTriggerPayload,_ as buildWorkflowAttemptInstruction,ye as buildWorkflowExpressionContextFromResolvedInputs,ce as compileWorkflowTriggerBindingFilter,A as createWorkflowEnginePackage,R as decodeDurableOutcome,h as decodeWorkflowAttemptOutcome,J as durableOutcome,G as evaluateAttemptCancellation,U as evaluateAttemptReachability,H as evaluateOperationAdmission,L as evaluateOperationCompletion,oe as evaluateProvisionerIncarnationLoss,ne as evaluateRuntimeReadiness,ae as evaluateRuntimeRegistration,E as getWorkflowState,T as initializeWorkflowState,he as isProviderOperationResolved,a as parseWorkflowAttemptInstruction,b as patchWorkflowState,pe as readAttemptSettlementSnapshot,S as registerBootstrapStartHandler,k as registerDrizzleWorkflowStorage,w as registerExecutionAttemptHandlers,C as registerOperationAdmissionHandler,I as registerRuntimeRegistrationHandler,de as replayEnsuredAttempt,n as resolveExecutionAttemptPeer,t as runAuthorityDispatchedAttempt,te as runShellStep,Z as sameAllocationRef,z as sameDurableOutcome,ie as snapshotAttemptOutcomeControl,fe as snapshotEnsureExecutionAttemptInput,ue as snapshotEnsureExecutionAttemptPersistenceInput,le as snapshotReadAttemptSettlementInput,B as snapshotRequestAttemptCancellationInput,V as snapshotRequestExecutionCancellationInput,M as submitAttemptOutcome,y as toCommittedWorkflowRunnerResult,l as workflowAttemptOutcomeCodec,ee as workflowDefinitionsDual,N as workflowEnginePackage,r as workflowExecutionStateDual,d as workflowExecutionStateEventsDual,m as workflowExecutionsDual,g as workflowFinalizationsDual,u as workflowStepSpansDual,f as worklogFrameEntriesDual,p as worklogSummariesDual};
1
+ import{B as e,C as t,D as n,E as ee,G as te,K as r,O as i,S as a,T as o,Y as s,at as c,b as l,dt as u,ht as d,q as f,rt as p,tt as m,v as h,w as g,x as _,xt as v,y,yt as b}from"../authority-state-bootstrap-DVFYemDL.mjs";import{_ as x,a as S,c as C,d as w,f as T,g as E,h as D,i as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L}from"../package-BT94BLu4.mjs";import{_ as R,a as ne,b as z,c as B,d as V,f as H,g as U,h as W,i as G,l as K,m as q,n as J,o as Y,p as X,r as Z,s as re,t as ie,u as ae,x as oe,y as se}from"../execution-attempt-repository-CWbgCTwA.mjs";import{assertWorkflowTriggerPayload as ce,compileWorkflowTriggerBindingFilter as le}from"./workflow-trigger-binding-consumer.mjs";import{a as ue,i as de,n as fe,r as pe,t as me}from"../execution-attempt-owner-recovery-D4APLAvt.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as he,isProviderOperationResolved as ge}from"./provider-operation.mjs";import{JsonValueSchema as Q,WorkflowFrameStateSchema as _e}from"@makaio/framework/contracts";const ve=new Set([..._e.shape.status.options]);function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ye(e){if(!$(e))return!1;for(let t of Object.values(e))if(!$(t)||typeof t.status!=`string`||!ve.has(t.status)||`result`in t&&t.result!==void 0&&!Q.safeParse(t.result).success)return!1;return!0}function be(e){let t={trigger:$(e.trigger)?e.trigger:{},steps:ye(e.steps)?e.steps:{},inputs:Q.safeParse(e.inputs).success?e.inputs:{}};return`item`in e&&(t.item=e.item),typeof e.index==`number`&&(t.index=e.index),t}export{ie as ATTEMPT_OPERATION_START_GATES,J as DuplicateExecutionAttemptError,Z as EXECUTION_ATTEMPT_SETTLEMENT_KINDS,G as EXECUTION_ATTEMPT_STATUSES,S as ExecutionAttemptAuthority,he as PROVIDER_OPERATION_OBLIGATIONS,k as RUNTIME_PROBE_DELIVERY_TIMEOUT_MS,X as RuntimeOutcomeFenceMismatchError,t as WORKFLOW_WORKLOAD_KIND,g as WORKFLOW_WORKLOAD_VERSION,h as WorkflowAttemptOutcomeSchema,O as WorkflowEngineService,I as WorkflowEngineToken,F as WorkflowExecutor,o as WorkflowInvocationInputSchema,r as WorkflowStorageNamespace,f as WorkflowStorageSubjects,M as WorkflowTriggerReconciler,q as assertRuntimeOutcomeFence,ce as assertWorkflowTriggerPayload,ee as buildWorkflowAttemptInstruction,be as buildWorkflowExpressionContextFromResolvedInputs,le as compileWorkflowTriggerBindingFilter,j as createWorkflowEnginePackage,ne as decodeDurableOutcome,y as decodeWorkflowAttemptOutcome,Y as durableOutcome,K as evaluateAttemptCancellation,W as evaluateAttemptReachability,U as evaluateOperationAdmission,R as evaluateOperationCompletion,se as evaluateProvisionerIncarnationLoss,z as evaluateRuntimeReadiness,oe as evaluateRuntimeRegistration,D as getWorkflowState,E as initializeWorkflowState,ge as isProviderOperationResolved,n as parseWorkflowAttemptInstruction,x as patchWorkflowState,me as readAttemptSettlementSnapshot,C as registerBootstrapStartHandler,A as registerDrizzleWorkflowStorage,T as registerExecutionAttemptHandlers,w as registerOperationAdmissionHandler,L as registerRuntimeRegistrationHandler,fe as replayEnsuredAttempt,te as resolveExecutionAttemptPeer,i as runAuthorityDispatchedAttempt,e as runShellStep,re as sameAllocationRef,B as sameDurableOutcome,ae as snapshotAttemptOutcomeControl,pe as snapshotEnsureExecutionAttemptInput,de as snapshotEnsureExecutionAttemptPersistenceInput,ue as snapshotReadAttemptSettlementInput,V as snapshotRequestAttemptCancellationInput,H as snapshotRequestExecutionCancellationInput,N as submitAttemptOutcome,l as toCommittedWorkflowRunnerCompletion,_ as toCommittedWorkflowRunnerResult,a as workflowAttemptOutcomeCodec,s as workflowDefinitionsDual,P as workflowEnginePackage,m as workflowExecutionStateDual,p as workflowExecutionStateEventsDual,c as workflowExecutionsDual,v as workflowFinalizationsDual,u as workflowStepSpansDual,d as worklogFrameEntriesDual,b as worklogSummariesDual};
@@ -1,2 +1,2 @@
1
- import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-Bl0mcGb8.mjs";
1
+ import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-BaTrCWZl.mjs";
2
2
  export { WorkflowEngineToken, createWorkflowEnginePackage, workflowEnginePackage };
@@ -1 +1 @@
1
- import{n as e,r as t,t as n}from"../package-B-xpYKe8.mjs";export{n as WorkflowEngineToken,e as createWorkflowEnginePackage,t as workflowEnginePackage};
1
+ import{n as e,r as t,t as n}from"../package-BT94BLu4.mjs";export{n as WorkflowEngineToken,e as createWorkflowEnginePackage,t as workflowEnginePackage};
@@ -1,2 +1,2 @@
1
- import { $ as InitialProviderOperationClaimContextSource, Q as InitialProviderOperationClaimContext, X as CompleteProviderOperationInput, Z as HandoffProviderOperationInput, _t as isProviderOperationResolved, at as ProviderOperationClaimDecision, ct as ProviderOperationLeaseRenewal, dt as ProviderOperationOwnershipRecord, et as ListOpenProviderOperationsInput, ft as ProvisionerIncarnationLossDecision, gt as TakeOverProviderOperationInput, ht as RenewProviderOperationClaimInput, it as ProviderOperationClaim, lt as ProviderOperationMutationDecision, mt as RecordProviderOperationUncertaintyInput, nt as PROVIDER_OPERATION_OBLIGATIONS, ot as ProviderOperationCompletionDecision, pt as ProvisioningAbsenceDecision, rt as ProcessBoundProvisionerLossProof, st as ProviderOperationLeasePolicy, tt as OpenProviderOperationRecord, ut as ProviderOperationObligation } from "../execution-attempt-repository--RVils5-.mjs";
1
+ import { $ as InitialProviderOperationClaimContextSource, Q as InitialProviderOperationClaimContext, X as CompleteProviderOperationInput, Z as HandoffProviderOperationInput, _t as isProviderOperationResolved, at as ProviderOperationClaimDecision, ct as ProviderOperationLeaseRenewal, dt as ProviderOperationOwnershipRecord, et as ListOpenProviderOperationsInput, ft as ProvisionerIncarnationLossDecision, gt as TakeOverProviderOperationInput, ht as RenewProviderOperationClaimInput, it as ProviderOperationClaim, lt as ProviderOperationMutationDecision, mt as RecordProviderOperationUncertaintyInput, nt as PROVIDER_OPERATION_OBLIGATIONS, ot as ProviderOperationCompletionDecision, pt as ProvisioningAbsenceDecision, rt as ProcessBoundProvisionerLossProof, st as ProviderOperationLeasePolicy, tt as OpenProviderOperationRecord, ut as ProviderOperationObligation } from "../execution-attempt-repository-DSpz2kyW.mjs";
2
2
  export { CompleteProviderOperationInput, HandoffProviderOperationInput, InitialProviderOperationClaimContext, InitialProviderOperationClaimContextSource, ListOpenProviderOperationsInput, OpenProviderOperationRecord, PROVIDER_OPERATION_OBLIGATIONS, ProcessBoundProvisionerLossProof, ProviderOperationClaim, ProviderOperationClaimDecision, ProviderOperationCompletionDecision, ProviderOperationLeasePolicy, ProviderOperationLeaseRenewal, ProviderOperationMutationDecision, ProviderOperationObligation, ProviderOperationOwnershipRecord, ProvisionerIncarnationLossDecision, ProvisioningAbsenceDecision, RecordProviderOperationUncertaintyInput, RenewProviderOperationClaimInput, TakeOverProviderOperationInput, isProviderOperationResolved };
@@ -1,4 +1,4 @@
1
- import { j as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository--RVils5-.mjs";
1
+ import { j as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository-DSpz2kyW.mjs";
2
2
 
3
3
  //#region subsystems/workflow-engine/src/testing/conformance/types.d.ts
4
4
  /** Narrow fixture input for recovery's oldest-first, identifier-tiebreak ordering contract. */
@@ -1,4 +1,4 @@
1
- import { I as RecordAllocationInput, Mt as AttemptOutcomeControlObservation, P as ProvisioningClaimDecision, Pt as ExecutionAttemptCancellationIntent, dt as ProviderOperationOwnershipRecord, it as ProviderOperationClaim, j as OutcomeCodec, r as AllocationRecordingDecision, rt as ProcessBoundProvisionerLossProof, s as AttemptControlState, u as BeginProvisioningInput, w as ExecutionOwnerId, x as ExecutionAttemptRepository, y as ExecutionAttemptRecord } from "../../execution-attempt-repository--RVils5-.mjs";
1
+ import { I as RecordAllocationInput, Mt as AttemptOutcomeControlObservation$1, P as ProvisioningClaimDecision, Pt as ExecutionAttemptCancellationIntent$1, dt as ProviderOperationOwnershipRecord, it as ProviderOperationClaim, j as OutcomeCodec, r as AllocationRecordingDecision, rt as ProcessBoundProvisionerLossProof, s as AttemptControlState, u as BeginProvisioningInput, w as ExecutionOwnerId, x as ExecutionAttemptRepository, y as ExecutionAttemptRecord, yt as ExecutionAttemptOutcomeDecision } from "../../execution-attempt-repository-DSpz2kyW.mjs";
2
2
  import { BoundedRecoveryEvidence, ExecutionAttemptInstruction, ExecutionAttemptPreparationResult, ProviderAllocationRef, WorkerAllocationLifetime, WorkflowRunResult } from "@makaio/framework/contracts";
3
3
 
4
4
  //#region subsystems/workflow-engine/src/testing/attempt-record-codec.d.ts
@@ -13,6 +13,17 @@ import { BoundedRecoveryEvidence, ExecutionAttemptInstruction, ExecutionAttemptP
13
13
  */
14
14
  declare const INITIAL_ATTEMPT_CONTROL_STATE: AttemptControlState;
15
15
  //#endregion
16
+ //#region subsystems/workflow-engine/src/testing/committed-outcome.d.ts
17
+ /**
18
+ * Require the successful commit a test fixture is about to explicitly accept.
19
+ * This assertion never turns a conflict or fence into a successful settlement.
20
+ * @param decision - Actual repository commit decision.
21
+ * @returns Accepted or duplicate decision with its canonical outcome facts.
22
+ */
23
+ declare function requireCommittedOutcome<TOutcome>(decision: ExecutionAttemptOutcomeDecision<TOutcome>): Extract<ExecutionAttemptOutcomeDecision<TOutcome>, {
24
+ kind: 'accepted' | 'duplicate';
25
+ }>;
26
+ //#endregion
16
27
  //#region subsystems/workflow-engine/src/testing/in-memory-attempt-repository.d.ts
17
28
  /**
18
29
  * Durable state the in-memory realization keeps.
@@ -44,13 +55,13 @@ interface InMemoryAttemptRepositoryState {
44
55
  */
45
56
  readonly committedOutcomes: Map<string, string>;
46
57
  /** Commit-time control facts, absent only for outcomes created before this observation existed. */
47
- readonly outcomeControlObservations: Map<string, AttemptOutcomeControlObservation>;
58
+ readonly outcomeControlObservations: Map<string, AttemptOutcomeControlObservation$1>;
48
59
  /** Active attempt per `executionId`, the fence every bootstrap path reads. */
49
60
  readonly activeAttempts: Map<string, string>;
50
61
  /** Request-to-attempt bindings, nested by owner and then opaque request key. */
51
62
  readonly requestBindings: Map<string, Map<string, string>>;
52
63
  /** First owner cancellation request for each attempt, surviving controller replacement. */
53
- readonly cancellations: Map<string, ExecutionAttemptCancellationIntent>;
64
+ readonly cancellations: Map<string, ExecutionAttemptCancellationIntent$1>;
54
65
  }
55
66
  /**
56
67
  * The in-memory realization together with the state backing it.
@@ -229,4 +240,4 @@ declare function driveTestAttemptToAllocated(driver: Pick<AttemptAllocationDrive
229
240
  */
230
241
  declare function allocateTestAttempt(driver: AttemptAllocationDriver, executionId: ExecutionOwnerId): Promise<string>;
231
242
  //#endregion
232
- export { type AttemptAllocationDriver, INITIAL_ATTEMPT_CONTROL_STATE, type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, allocateTestAttempt, beginTestProvisioning, createInMemoryAttemptRepository, driveTestAttemptToAllocated, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestInstruction, makeTestWorkflowResult, workflowRunResultOutcomeCodec };
243
+ export { type AttemptAllocationDriver, INITIAL_ATTEMPT_CONTROL_STATE, type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, allocateTestAttempt, beginTestProvisioning, createInMemoryAttemptRepository, driveTestAttemptToAllocated, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestInstruction, makeTestWorkflowResult, requireCommittedOutcome, workflowRunResultOutcomeCodec };
@@ -1 +1 @@
1
- import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as ee,l as s,m as c,n as l,o as u,s as d,u as f,v as p,x as m,y as h}from"../../execution-attempt-repository-CWbgCTwA.mjs";import{a as g,i as _,n as v,o as y,t as b}from"../../execution-attempt-owner-recovery-D4APLAvt.mjs";import{isProviderOperationResolved as x}from"../provider-operation.mjs";import{a as S,c as C,d as w,f as T,i as E,l as D,n as O,o as k,p as A,r as j,s as M,t as N,u as P}from"../../attempt-record-codec-D2Gb_epJ.mjs";import{a as F,c as I,d as L,f as R,i as z,l as B,m as V,n as H,o as U,p as W,r as G,s as K,t as q,u as J}from"../../attempt-fixtures-CMx-2OlG.mjs";import{randomUUID as Y}from"node:crypto";import{BoundedRecoveryEvidenceSchema as X}from"@makaio/framework/contracts";function Z(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function Q(F,I={}){let L=I.attempts??new Map,R=I.operations??new Map,z=e=>R.get(e)?.obligation===`terminal-convergence`,B=I.committedOutcomes??new Map,V=I.outcomeControlObservations??new Map,H=I.activeAttempts??new Map,U=I.requestBindings??new Map,W=I.cancellations??new Map,G=e=>{let t=e.settlementKind!=null,n=!t&&H.get(e.executionId)===e.executionAttemptId;return ee({matchesExecution:!0,settled:t,active:n,allocated:n&&e.allocationRef!==null&&!z(e.executionAttemptId)})},K=e=>{let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:x(t,n)?{kind:`resolved`,attempt:t}:n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}},q=(e,t)=>{e.completionEvidence===null&&R.set(e.executionAttemptId,{...e,completionEvidence:t})},J=(e,t)=>{let n=M(e.allocationRef),r=K(e.claim);if(r.kind!==`not-found`&&w(r.attempt,n),r.kind===`resolved`)return{kind:`resolved`,allocationRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i,operation:a}=r;if(i.allocationRef!==null)return d(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let o=H.get(i.executionId)===i.executionAttemptId;return L.set(i.executionAttemptId,{...i,status:i.settlementKind===null?`allocated`:i.status,allocationRef:n,claimable:i.settlementKind===null&&t&&o}),R.set(a.executionAttemptId,{...a,obligation:`allocation-control`}),{kind:`recorded`}},Q={async getAttemptWithAllocation(e){return L.get(e)??null},async recordDiscoveredAllocation(e){return J(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=C(e),r=K(e.claim);if(r.kind===`stale`)return{kind:`stale`,storedRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?{kind:`not-allocated`}:d(i.allocationRef,t)?(L.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=E(new Date().toISOString()),n=[];for(let r of L.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&E(r.claimExpiresAt)<t||n.push(A(r)));return n.sort(O)},async listOpenProviderOperations(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw RangeError(`limit must be a positive safe integer`);let t=E(e.observedAt),n=[];for(let e of R.values()){let r=L.get(e.executionAttemptId);!r||x(r,e)||e.ownerId!==null&&e.leaseExpiresAt!==null&&E(e.leaseExpiresAt)>t||n.push({attempt:r,operation:e})}return n.sort((e,t)=>O(e.attempt,t.attempt)).slice(0,e.limit)}},$=e=>{let t=j(e.bootstrapTimeoutMs);if(L.has(e.executionAttemptId))throw new l(e.executionAttemptId);let n={executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:e.instruction,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,...t,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...N},r=H.get(e.executionId),i=r===void 0?void 0:L.get(r);return i!==void 0&&L.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),L.set(e.executionAttemptId,n),H.set(e.executionId,e.executionAttemptId),n};return{async createAttempt(e){return $({...e,instruction:y(e.instruction)})},async ensureAttempt(e){let t=_(e),n=U.get(t.executionId),r=n?.get(t.requestKey);if(r!==void 0)return v(t,L.get(r)??null);let i=$(t),a=n??new Map;return a.set(t.requestKey,i.executionAttemptId),U.set(t.executionId,a),{kind:`created`,attempt:structuredClone(i)}},async readAttemptSettlement(e){let t=g(e);return b(t,{attempt:L.get(t.executionAttemptId)??null,activeAttemptId:H.get(t.executionId)??null,outcomeText:B.get(t.executionAttemptId)??null,controlObservation:V.get(t.executionAttemptId)??null},F)},async readBootstrapStartState(e){let t=L.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:z(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=k(e.allocationLifetime),n=L.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(H.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.operationStartGate===`closed`)return{kind:`fenced`};if(n.status!==`pending`)return{kind:`already-provisioning`};L.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:S(e.leaseExpiresAt)};return R.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null,completionEvidence:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return R.get(e)??null},async renewProviderOperationClaim(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=S(e.leaseExpiresAt);return R.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(x(t,n))return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&E(n.leaseExpiresAt)>E(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:S(e.leaseExpiresAt)};return R.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async completeProviderOperation(e){let t=X.parse(e.evidence),n=L.get(e.claim.executionAttemptId),r=R.get(e.claim.executionAttemptId);return!n||!r?{kind:`not-found`}:r.token!==e.claim.token||r.generation!==e.claim.generation||r.ownerId!==e.claim.ownerId?{kind:`stale`}:x(n,r)?{kind:`already-completed`}:r.completionEvidence===null?(q(r,t),n.settlementKind===null?{kind:`evidence-recorded`}:{kind:`completed`}):{kind:`evidence-recorded`}},async recordAllocation(e){return J(e,!0)},async recordProvisioningAbsent(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?r.settlementKind===null?(L.set(r.executionAttemptId,Z(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=X.parse(e.proof.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n,a=h(r,e);return a===null?r.settlementKind===null?(L.set(r.executionAttemptId,Z(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):a},async recordAllocationTerminated(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(R.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.settlementKind===null?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(L.set(n.executionAttemptId,Z(n,`infrastructure-failure`)),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},async registerRuntime(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t)??m(t,e);if(n!==null)return n;let r=t.runtimeGeneration+1;return L.set(t.executionAttemptId,{...t,runtimeGeneration:r,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:r}},async admitOperation(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t);if(n!==null)return n;let r=o(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?S(new Date().toISOString()):``,t);if(r!==null)return r;let i=crypto.randomUUID(),a=S(new Date().toISOString());return L.set(t.executionAttemptId,{...t,activeOperationId:i,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:a}),{kind:`admitted`,operationId:i,runtimeGeneration:t.runtimeGeneration,admittedAt:a}},async getInstruction(e){let t=L.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=P(e.result),n=L.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=p({matchesExecution:!0,settled:n.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!z(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=D([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return L.set(e.executionAttemptId,{...n,preparationReceipts:i,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`accepted`,binding:t.binding}},async completeOperation(t){let n=L.get(t.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlementKind!=null)return{kind:`resolved`};let r=e(n,t);return r===null?(L.set(n.executionAttemptId,{...n,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:t.operationId}),{kind:`completed`}):r},async markRuntimeReady(e){let t=S(e.readyAt),r=L.get(e.executionAttemptId);if(r===void 0||r.executionId!==e.executionId)return{kind:`not-found`};let i=G(r)??n(r,e);return i===null?(L.set(r.executionAttemptId,{...r,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):i},async getAttemptControlState(e){let t=L.get(e);return t===void 0?null:T(t)},async requestAttemptCancellation(e){let t=i(e),n=L.get(t.executionAttemptId);if(n===void 0||n.executionId!==t.executionId)return{kind:`not-found`};let r=s(W.get(t.executionAttemptId)??null,t,new Date().toISOString());return r.kind===`conflict`?r:(W.set(t.executionAttemptId,{...r.intent}),L.set(t.executionAttemptId,{...n,operationStartGate:`closed`}),r)},async requestCancellation(e){let t=a(e),n={...t,requestKey:Y()},r=new Date().toISOString(),i=[...L].filter(([,e])=>e.executionId===t.executionId).map(([e,t])=>{let i=s(W.get(e)??null,n,r);if(i.kind===`conflict`)throw Error(`Conflicting generated cancellation request key`);return{id:e,attempt:t,intent:i.intent}});for(let{id:e,attempt:t,intent:n}of i)W.set(e,{...n}),L.set(e,{...t,operationStartGate:`closed`})},async readCancellation(e){let t=W.get(e);return t===void 0?null:{...t}},async getActiveAttempt(e,t){return H.get(e)===t?L.get(t)??null:null},canonicalizeOutcome(e){return u(F,e)},decodeOutcome(e){return t(F,e)},async commitOutcome(e){let n=e.result;if(H.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let i=L.get(e.executionAttemptId);if(i===void 0)return{kind:`fenced`};let a=B.get(e.executionAttemptId);if(a!==void 0){let i=t(F,a);return r(a,n.text)?{kind:`duplicate`,outcome:i,text:a,controlObservation:structuredClone(V.get(e.executionAttemptId)??null)}:{kind:`conflict`}}if(i.settlementKind!=null)return{kind:`conflict`};c(i,e.runtimeFence);let o=f(W.get(e.executionAttemptId)??null);return B.set(e.executionAttemptId,n.text),V.set(e.executionAttemptId,o),L.set(e.executionAttemptId,Z(i,`outcome`)),{kind:`accepted`,outcome:t(F,n.text),text:n.text,controlObservation:structuredClone(o)}},async abandonPendingAttempt(e,t){if(H.get(t)!==e)return{kind:`fenced`};let n=L.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(L.set(e,Z(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:Q,attempts:L,operations:R,committedOutcomes:B,outcomeControlObservations:V,activeAttempts:H,requestBindings:U,cancellations:W}}export{N as INITIAL_ATTEMPT_CONTROL_STATE,q as TEST_OWNER_ID,H as TEST_PROVIDER_ID,G as TEST_PROVISIONER_INCARNATION_ID,z as allocateTestAttempt,F as beginTestProvisioning,Q as createInMemoryAttemptRepository,U as driveTestAttemptToAllocated,K as leaseAt,I as makeBeginProvisioningInput,B as makeEvidence,J as makeProcessLossProof,L as makeTestAllocationRef,R as makeTestInstruction,W as makeTestWorkflowResult,V as workflowRunResultOutcomeCodec};
1
+ import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,s as f,u as p,v as m,x as h,y as g}from"../../execution-attempt-repository-CWbgCTwA.mjs";import{a as _,i as v,n as y,o as b,t as x}from"../../execution-attempt-owner-recovery-D4APLAvt.mjs";import{isProviderOperationResolved as S}from"../provider-operation.mjs";import{a as C,c as w,d as T,f as E,i as D,l as ee,n as O,o as k,p as A,r as j,s as M,t as N,u as P}from"../../attempt-record-codec-D2Gb_epJ.mjs";import{a as F,c as I,d as L,f as R,i as z,l as B,m as V,n as H,o as U,p as W,r as G,s as K,t as q,u as J}from"../../attempt-fixtures-CMx-2OlG.mjs";import{randomUUID as Y}from"node:crypto";import{BoundedRecoveryEvidenceSchema as X}from"@makaio/framework/contracts";function Z(e){if(e.kind===`accepted`||e.kind===`duplicate`)return e;throw Error(`Expected a committed test outcome, received ${e.kind}`)}function Q(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function $(F,I={}){let L=I.attempts??new Map,R=I.operations??new Map,z=e=>R.get(e)?.obligation===`terminal-convergence`,B=I.committedOutcomes??new Map,V=I.outcomeControlObservations??new Map,H=I.activeAttempts??new Map,U=I.requestBindings??new Map,W=I.cancellations??new Map,G=e=>{let t=e.settlementKind!=null,n=!t&&H.get(e.executionId)===e.executionAttemptId;return s({matchesExecution:!0,settled:t,active:n,allocated:n&&e.allocationRef!==null&&!z(e.executionAttemptId)})},K=e=>{let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:S(t,n)?{kind:`resolved`,attempt:t}:n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}},q=(e,t)=>{e.completionEvidence===null&&R.set(e.executionAttemptId,{...e,completionEvidence:t})},J=(e,t)=>{let n=M(e.allocationRef),r=K(e.claim);if(r.kind!==`not-found`&&T(r.attempt,n),r.kind===`resolved`)return{kind:`resolved`,allocationRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i,operation:a}=r;if(i.allocationRef!==null)return f(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let o=H.get(i.executionId)===i.executionAttemptId;return L.set(i.executionAttemptId,{...i,status:i.settlementKind===null?`allocated`:i.status,allocationRef:n,claimable:i.settlementKind===null&&t&&o}),R.set(a.executionAttemptId,{...a,obligation:`allocation-control`}),{kind:`recorded`}},Z={async getAttemptWithAllocation(e){return L.get(e)??null},async recordDiscoveredAllocation(e){return J(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=w(e),r=K(e.claim);if(r.kind===`stale`)return{kind:`stale`,storedRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?{kind:`not-allocated`}:f(i.allocationRef,t)?(L.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=D(new Date().toISOString()),n=[];for(let r of L.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&D(r.claimExpiresAt)<t||n.push(A(r)));return n.sort(O)},async listOpenProviderOperations(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw RangeError(`limit must be a positive safe integer`);let t=D(e.observedAt),n=[];for(let e of R.values()){let r=L.get(e.executionAttemptId);!r||S(r,e)||e.ownerId!==null&&e.leaseExpiresAt!==null&&D(e.leaseExpiresAt)>t||n.push({attempt:r,operation:e})}return n.sort((e,t)=>O(e.attempt,t.attempt)).slice(0,e.limit)}},$=e=>{let t=j(e.bootstrapTimeoutMs);if(L.has(e.executionAttemptId))throw new u(e.executionAttemptId);let n={executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:e.instruction,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,...t,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...N},r=H.get(e.executionId),i=r===void 0?void 0:L.get(r);return i!==void 0&&L.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),L.set(e.executionAttemptId,n),H.set(e.executionId,e.executionAttemptId),n};return{async createAttempt(e){return $({...e,instruction:b(e.instruction)})},async ensureAttempt(e){let t=v(e),n=U.get(t.executionId),r=n?.get(t.requestKey);if(r!==void 0)return y(t,L.get(r)??null);let i=$(t),a=n??new Map;return a.set(t.requestKey,i.executionAttemptId),U.set(t.executionId,a),{kind:`created`,attempt:structuredClone(i)}},async readAttemptSettlement(e){let t=_(e);return x(t,{attempt:L.get(t.executionAttemptId)??null,activeAttemptId:H.get(t.executionId)??null,outcomeText:B.get(t.executionAttemptId)??null,controlObservation:V.get(t.executionAttemptId)??null},F)},async readBootstrapStartState(e){let t=L.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:z(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=k(e.allocationLifetime),n=L.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(H.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.operationStartGate===`closed`)return{kind:`fenced`};if(n.status!==`pending`)return{kind:`already-provisioning`};L.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:C(e.leaseExpiresAt)};return R.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null,completionEvidence:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return R.get(e)??null},async renewProviderOperationClaim(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=C(e.leaseExpiresAt);return R.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(S(t,n))return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&D(n.leaseExpiresAt)>D(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:C(e.leaseExpiresAt)};return R.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async completeProviderOperation(e){let t=X.parse(e.evidence),n=L.get(e.claim.executionAttemptId),r=R.get(e.claim.executionAttemptId);return!n||!r?{kind:`not-found`}:r.token!==e.claim.token||r.generation!==e.claim.generation||r.ownerId!==e.claim.ownerId?{kind:`stale`}:S(n,r)?{kind:`already-completed`}:r.completionEvidence===null?(q(r,t),n.settlementKind===null?{kind:`evidence-recorded`}:{kind:`completed`}):{kind:`evidence-recorded`}},async recordAllocation(e){return J(e,!0)},async recordProvisioningAbsent(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?r.settlementKind===null?(L.set(r.executionAttemptId,Q(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=X.parse(e.proof.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n,a=g(r,e);return a===null?r.settlementKind===null?(L.set(r.executionAttemptId,Q(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):a},async recordAllocationTerminated(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(R.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.settlementKind===null?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(L.set(n.executionAttemptId,Q(n,`infrastructure-failure`)),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},async registerRuntime(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t)??h(t,e);if(n!==null)return n;let r=t.runtimeGeneration+1;return L.set(t.executionAttemptId,{...t,runtimeGeneration:r,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:r}},async admitOperation(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t);if(n!==null)return n;let r=o(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?C(new Date().toISOString()):``,t);if(r!==null)return r;let i=crypto.randomUUID(),a=C(new Date().toISOString());return L.set(t.executionAttemptId,{...t,activeOperationId:i,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:a}),{kind:`admitted`,operationId:i,runtimeGeneration:t.runtimeGeneration,admittedAt:a}},async getInstruction(e){let t=L.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=P(e.result),n=L.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=m({matchesExecution:!0,settled:n.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!z(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=ee([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return L.set(e.executionAttemptId,{...n,preparationReceipts:i,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`accepted`,binding:t.binding}},async completeOperation(t){let n=L.get(t.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlementKind!=null)return{kind:`resolved`};let r=e(n,t);return r===null?(L.set(n.executionAttemptId,{...n,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:t.operationId}),{kind:`completed`}):r},async markRuntimeReady(e){let t=C(e.readyAt),r=L.get(e.executionAttemptId);if(r===void 0||r.executionId!==e.executionId)return{kind:`not-found`};let i=G(r)??n(r,e);return i===null?(L.set(r.executionAttemptId,{...r,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):i},async getAttemptControlState(e){let t=L.get(e);return t===void 0?null:E(t)},async requestAttemptCancellation(e){let t=i(e),n=L.get(t.executionAttemptId);if(n===void 0||n.executionId!==t.executionId)return{kind:`not-found`};let r=c(W.get(t.executionAttemptId)??null,t,new Date().toISOString());return r.kind===`conflict`?r:(W.set(t.executionAttemptId,{...r.intent}),L.set(t.executionAttemptId,{...n,operationStartGate:`closed`}),r)},async requestCancellation(e){let t=a(e),n={...t,requestKey:Y()},r=new Date().toISOString(),i=[...L].filter(([,e])=>e.executionId===t.executionId).map(([e,t])=>{let i=c(W.get(e)??null,n,r);if(i.kind===`conflict`)throw Error(`Conflicting generated cancellation request key`);return{id:e,attempt:t,intent:i.intent}});for(let{id:e,attempt:t,intent:n}of i)W.set(e,{...n}),L.set(e,{...t,operationStartGate:`closed`})},async readCancellation(e){let t=W.get(e);return t===void 0?null:{...t}},async getActiveAttempt(e,t){return H.get(e)===t?L.get(t)??null:null},canonicalizeOutcome(e){return d(F,e)},decodeOutcome(e){return t(F,e)},async commitOutcome(e){let n=e.result;if(H.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let i=L.get(e.executionAttemptId);if(i===void 0)return{kind:`fenced`};let a=B.get(e.executionAttemptId);if(a!==void 0){let i=t(F,a);return r(a,n.text)?{kind:`duplicate`,outcome:i,text:a,controlObservation:structuredClone(V.get(e.executionAttemptId)??null)}:{kind:`conflict`}}if(i.settlementKind!=null)return{kind:`conflict`};l(i,e.runtimeFence);let o=p(W.get(e.executionAttemptId)??null);return B.set(e.executionAttemptId,n.text),V.set(e.executionAttemptId,o),L.set(e.executionAttemptId,Q(i,`outcome`)),{kind:`accepted`,outcome:t(F,n.text),text:n.text,controlObservation:structuredClone(o)}},async abandonPendingAttempt(e,t){if(H.get(t)!==e)return{kind:`fenced`};let n=L.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(L.set(e,Q(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:Z,attempts:L,operations:R,committedOutcomes:B,outcomeControlObservations:V,activeAttempts:H,requestBindings:U,cancellations:W}}export{N as INITIAL_ATTEMPT_CONTROL_STATE,q as TEST_OWNER_ID,H as TEST_PROVIDER_ID,G as TEST_PROVISIONER_INCARNATION_ID,z as allocateTestAttempt,F as beginTestProvisioning,$ as createInMemoryAttemptRepository,U as driveTestAttemptToAllocated,K as leaseAt,I as makeBeginProvisioningInput,B as makeEvidence,J as makeProcessLossProof,L as makeTestAllocationRef,R as makeTestInstruction,W as makeTestWorkflowResult,Z as requireCommittedOutcome,V as workflowRunResultOutcomeCodec};
@@ -1,4 +1,4 @@
1
- import { j as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository--RVils5-.mjs";
1
+ import { j as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository-DSpz2kyW.mjs";
2
2
  import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
3
3
 
4
4
  //#region subsystems/workflow-engine/src/testing/sqlite-attempt-repository.d.ts
@@ -1 +1 @@
1
- import{W as e,bt as t,c as n,d as r,i,k as a,l as o,r as s,s as c,t as l,z as u}from"../authority-state-bootstrap-DgoHPc9J.mjs";import{WORKFLOW_CANCELLED_REASON as d,WorkflowRunContextSchema as f}from"@makaio/framework/contracts";import*as p from"node:os";async function m(n,r,i,a){let o=await y(n,r,i);return await n.request(e.setExecution,{execution:o}),i===`completed`?await n.emit(t.execution.completed,{executionId:r.executionId,workflowId:r.workflowId,totalDuration:0,completedAt:o.completedAt}):await n.emit(t.execution.cancelled,{executionId:r.executionId,workflowId:r.workflowId,reason:a,completedAt:o.completedAt}),i===`cancelled`?{executionId:r.executionId,workflowId:r.workflowId,status:`cancelled`,...a===void 0?{}:{reason:a}}:{executionId:r.executionId,workflowId:r.workflowId,status:`completed`}}function h(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function g(e){let t,n=()=>{t=a({bus:e.bus,activeExecutions:e.activeExecutions,shellAbortControllers:e.shellAbortControllers,activeRunnerSteps:e.activeRunnerSteps,durableLifecycleTransitions:e.durableLifecycleTransitions,lifecyclePublications:e.lifecyclePublications,publishingLifecycleExecutions:e.publishingLifecycleExecutions,cancelTimeoutMs:u.cancelTimeoutMs},e.executionId,d).catch(t=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${e.executionId}:`,t),!1))};return e.signal.addEventListener(`abort`,n,{once:!0}),e.signal.aborted&&n(),async()=>(e.signal.removeEventListener(`abort`,n),t??!1)}async function _(t,n){let r=await t.requestOptional(e.getExecution,{executionId:n});return r.handled?r.data.execution?.startedAt??void 0:void 0}async function v(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function y(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function b(e,t,r,a,s,c,l,u,f){let m=e.suspensionStrategy===`wait-in-process`?void 0:await x(e.executionId,l,{required:!0}),h=await n({definition:t,execution:r,runContext:a,zodSchema:f?.artifact,bus:l}),g=new o(e.executionId,e.workflowId,t,r,s,l,u,void 0,h,{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${p.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:m,runtimeLoopGates:c}),_=g.buildExpressionContext(),v=await i(t.root,g,_);return v.status===`failed`?{status:`failed`,error:v.error}:v.status===`paused`?{status:`paused`,pausedAtGateId:v.pausedAtGateId,pausedAtFrameId:v.pausedAtFrameId}:v.status===`cancelled`||u.aborted?{status:`cancelled`,reason:d}:{status:`completed`,artifact:h?.current}}async function x(t,n,r={}){try{let i=await n.requestOptional(e.listFrames,{executionId:t});if(!i.handled){if(r.required===!0)throw Error(`Frame storage handler is required to resume execution '${t}'.`);return}return i.data.frames.length===0?void 0:c(i.data.frames)}catch(e){if(r.required===!0)throw e;return}}function S(e,t){return f.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source.kind===`path`?{kind:`path`,path:e.materializationSpec?.sourcePath??``}:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}async function C(n,r,i,a,o){i.status=`paused`,await n.request(e.setExecution,{execution:i}),await n.emit(t.execution.paused,{executionId:r.executionId,workflowId:r.workflowId,pausedAtGateId:a,pausedAtFrameId:o})}async function w(e,n,r,i,a,o){r===`completed`?await e.emit(t.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:a-i.startedAt,completedAt:a}):r===`cancelled`?await e.emit(t.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:d,completedAt:a}):await e.emit(t.execution.failed,{executionId:n.executionId,workflowId:n.workflowId,error:o??`Workflow execution failed`,completedAt:a})}async function T(t){let{config:n,loaded:i,bus:a,signal:o}=t,{definition:c}=i;if(o.aborted)return n.terminalAuthority===`authority`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,reason:d}:m(a,n,`cancelled`,d);let u=await v(a,n),f=S(n,c);n.terminalAuthority===`authority`?await l(a,f,c):await r(a,u,f,c);let p=new Map(i.runtimeHandlers),_=i.runtimeLoopGates??new Map,y=new Map,x=new Map,T=new Map,E=new Map,D=new Map,O=new Set;y.set(n.executionId,{execution:u,workflow:c,runContext:f,runtimeHandlers:p,runtimeLoopGates:new Map(_)});let k=n.terminalAuthority===`authority`?async()=>!1:g({signal:o,executionId:n.executionId,bus:a,activeExecutions:y,shellAbortControllers:x,activeRunnerSteps:T,durableLifecycleTransitions:E,lifecyclePublications:D,publishingLifecycleExecutions:O}),A={status:`completed`},j=!1;try{c.root.nodes.length>0&&(s(c,_),A=await b(n,c,u,f,p,_,a,o,i.zodSchemas))}catch(e){A={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{j=await k(),y.clear()}if(j)return h(n,{status:`cancelled`,reason:d});if((o.aborted||u.status===`cancelled`)&&(A={status:`cancelled`,reason:d}),A.status===`paused`)return n.terminalAuthority!==`authority`&&await C(a,n,u,A.pausedAtGateId,A.pausedAtFrameId),h(n,A);if(n.terminalAuthority===`authority`)return h(n,A);let M=Date.now(),N=A.status===`failed`?A.error:void 0;return u.status=A.status,u.completedAt=M,u.error=N,await a.request(e.setExecution,{execution:u}),await w(a,n,A.status,u,M,N),h(n,A)}export{T as runWorkflowOrchestrator};
1
+ import{Ct as e,H as t,M as n,c as r,d as i,i as a,l as o,q as s,r as c,s as l,t as u}from"../authority-state-bootstrap-DVFYemDL.mjs";import{WORKFLOW_CANCELLED_REASON as d,WorkflowRunContextSchema as f}from"@makaio/framework/contracts";import*as p from"node:os";async function m(t,n,r,i){let a=await y(t,n,r);return await t.request(s.setExecution,{execution:a}),r===`completed`?await t.emit(e.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:0,completedAt:a.completedAt}):await t.emit(e.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:i,completedAt:a.completedAt}),r===`cancelled`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,...i===void 0?{}:{reason:i}}:{executionId:n.executionId,workflowId:n.workflowId,status:`completed`}}function h(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function g(e){let r,i=()=>{r=n({bus:e.bus,activeExecutions:e.activeExecutions,shellAbortControllers:e.shellAbortControllers,activeRunnerSteps:e.activeRunnerSteps,durableLifecycleTransitions:e.durableLifecycleTransitions,lifecyclePublications:e.lifecyclePublications,publishingLifecycleExecutions:e.publishingLifecycleExecutions,cancelTimeoutMs:t.cancelTimeoutMs},e.executionId,d).catch(t=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${e.executionId}:`,t),!1))};return e.signal.addEventListener(`abort`,i,{once:!0}),e.signal.aborted&&i(),async()=>(e.signal.removeEventListener(`abort`,i),r??!1)}async function _(e,t){let n=await e.requestOptional(s.getExecution,{executionId:t});return n.handled?n.data.execution?.startedAt??void 0:void 0}async function v(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function y(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function b(e,t,n,i,s,c,l,u,f){let m=e.suspensionStrategy===`wait-in-process`?void 0:await x(e.executionId,l,{required:!0}),h=await r({definition:t,execution:n,runContext:i,zodSchema:f?.artifact,bus:l}),g=new o(e.executionId,e.workflowId,t,n,s,l,u,void 0,h,{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${p.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:m,runtimeLoopGates:c}),_=g.buildExpressionContext(),v=await a(t.root,g,_);return v.status===`failed`?{status:`failed`,error:v.error}:v.status===`paused`?{status:`paused`,pausedAtGateId:v.pausedAtGateId,pausedAtFrameId:v.pausedAtFrameId}:v.status===`cancelled`||u.aborted?{status:`cancelled`,reason:d}:{status:`completed`,artifact:h?.current}}async function x(e,t,n={}){try{let r=await t.requestOptional(s.listFrames,{executionId:e});if(!r.handled){if(n.required===!0)throw Error(`Frame storage handler is required to resume execution '${e}'.`);return}return r.data.frames.length===0?void 0:l(r.data.frames)}catch(e){if(n.required===!0)throw e;return}}function S(e,t){return f.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source.kind===`path`?{kind:`path`,path:e.materializationSpec?.sourcePath??``}:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}async function C(t,n,r,i,a){r.status=`paused`,await t.request(s.setExecution,{execution:r}),await t.emit(e.execution.paused,{executionId:n.executionId,workflowId:n.workflowId,pausedAtGateId:i,pausedAtFrameId:a})}async function w(t,n,r,i,a,o){r===`completed`?await t.emit(e.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:a-i.startedAt,completedAt:a}):r===`cancelled`?await t.emit(e.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:d,completedAt:a}):await t.emit(e.execution.failed,{executionId:n.executionId,workflowId:n.workflowId,error:o??`Workflow execution failed`,completedAt:a})}async function T(e){let{config:t,loaded:n,bus:r,signal:a}=e,{definition:o}=n;if(a.aborted)return t.terminalAuthority===`authority`?{executionId:t.executionId,workflowId:t.workflowId,status:`cancelled`,reason:d}:m(r,t,`cancelled`,d);let l=await v(r,t),f=S(t,o);t.terminalAuthority===`authority`?await u(r,f,o):await i(r,l,f,o);let p=new Map(n.runtimeHandlers),_=n.runtimeLoopGates??new Map,y=new Map,x=new Map,T=new Map,E=new Map,D=new Map,O=new Set;y.set(t.executionId,{execution:l,workflow:o,runContext:f,runtimeHandlers:p,runtimeLoopGates:new Map(_)});let k=t.terminalAuthority===`authority`?async()=>!1:g({signal:a,executionId:t.executionId,bus:r,activeExecutions:y,shellAbortControllers:x,activeRunnerSteps:T,durableLifecycleTransitions:E,lifecyclePublications:D,publishingLifecycleExecutions:O}),A={status:`completed`},j=!1;try{o.root.nodes.length>0&&(c(o,_),A=await b(t,o,l,f,p,_,r,a,n.zodSchemas))}catch(e){A={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{j=await k(),y.clear()}if(j)return h(t,{status:`cancelled`,reason:d});if((a.aborted||l.status===`cancelled`)&&(A={status:`cancelled`,reason:d}),A.status===`paused`)return t.terminalAuthority!==`authority`&&await C(r,t,l,A.pausedAtGateId,A.pausedAtFrameId),h(t,A);if(t.terminalAuthority===`authority`)return h(t,A);let M=Date.now(),N=A.status===`failed`?A.error:void 0;return l.status=A.status,l.completedAt=M,l.error=N,await r.request(s.setExecution,{execution:l}),await w(r,t,A.status,l,M,N),h(t,A)}export{T as runWorkflowOrchestrator};
@@ -1 +1 @@
1
- import{u as e}from"./framework-packages-BOPhhtK7.mjs";function t(){let t=new Map;return{filter:e=>!!(e.transitionRules?.rules?.length||e.transitionActions?.actions),async processActivated(i,a,o){let s=o.getService(e);if(!s)throw Error(`TransitionContributionProcessor: TransitionPipelineService is not available — ensure '${e.name}' is started before extensions with transitionRules or transitionActions.`);let c=a.transitionRules?.rules??[],l=a.transitionActions?.actions,u=c.length>0,d=l!==void 0;u&&n(i,c),d&&r(i,l);let f=!1,p=!1;try{u&&(s.ruleRegistry.register(i,c),f=!0),d&&(s.actionRegistry.register(i,l),p=!0)}catch(e){throw f&&s.ruleRegistry.deregister(i),p&&s.actionRegistry.deregister(i),e}t.set(i,()=>{u&&s.ruleRegistry.deregister(i),d&&s.actionRegistry.deregister(i)})},async processStopped(e){let n=t.get(e);if(n){try{n()}catch(t){console.error(`[TransitionContributionProcessor] Deregister error for "${e}":`,t)}t.delete(e)}}}}function n(e,t){let n=`${e}.`;for(let e of t)if(!e.id.startsWith(n))throw Error(`TransitionContributionProcessor: rule '${e.id}' must be namespaced by extension '${n}'`)}function r(e,t){let n=`${e}.`;for(let e of Object.keys(t))if(!e.startsWith(n))throw Error(`TransitionContributionProcessor: action type '${e}' must be namespaced by extension '${n}'`)}export{t};
1
+ import{u as e}from"./framework-packages-DdCJ4JsE.mjs";function t(){let t=new Map;return{filter:e=>!!(e.transitionRules?.rules?.length||e.transitionActions?.actions),async processActivated(i,a,o){let s=o.getService(e);if(!s)throw Error(`TransitionContributionProcessor: TransitionPipelineService is not available — ensure '${e.name}' is started before extensions with transitionRules or transitionActions.`);let c=a.transitionRules?.rules??[],l=a.transitionActions?.actions,u=c.length>0,d=l!==void 0;u&&n(i,c),d&&r(i,l);let f=!1,p=!1;try{u&&(s.ruleRegistry.register(i,c),f=!0),d&&(s.actionRegistry.register(i,l),p=!0)}catch(e){throw f&&s.ruleRegistry.deregister(i),p&&s.actionRegistry.deregister(i),e}t.set(i,()=>{u&&s.ruleRegistry.deregister(i),d&&s.actionRegistry.deregister(i)})},async processStopped(e){let n=t.get(e);if(n){try{n()}catch(t){console.error(`[TransitionContributionProcessor] Deregister error for "${e}":`,t)}t.delete(e)}}}}function n(e,t){let n=`${e}.`;for(let e of t)if(!e.id.startsWith(n))throw Error(`TransitionContributionProcessor: rule '${e.id}' must be namespaced by extension '${n}'`)}function r(e,t){let n=`${e}.`;for(let e of Object.keys(t))if(!e.startsWith(n))throw Error(`TransitionContributionProcessor: action type '${e}' must be namespaced by extension '${n}'`)}export{t};
@@ -0,0 +1,2 @@
1
+ import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-Dr7JXjLS.mjs";import{b as n,c as r,g as i,l as a,n as o,u as s,v as c}from"./bootstrap-start-client-rW55mDI-.mjs";import{mintOrRotateWorkflowExecutionBusSecret as l}from"./runtime-node/workflow-execution-bus-access.mjs";import{z as u}from"zod";import{execFile as d,spawn as f}from"node:child_process";import{promisify as p}from"node:util";import*as m from"node:fs/promises";import{access as ee}from"node:fs/promises";import*as h from"node:path";import{basename as te,isAbsolute as ne,join as g,relative as re}from"node:path";import*as _ from"node:crypto";import{randomUUID as v}from"node:crypto";import{constants as ie}from"node:fs";import{AdapterSubjects as ae,BoundedRecoveryEvidenceSchema as y,ExecutionAttemptSchemas as b,ExecutionAttemptSubjects as x,FrameworkContractNamespaces as oe,FrameworkStorageNamespaces as se,JsonValueSchema as ce,PRE_REQUEST_REJECTION_CODE as le,PROVIDER_ALLOCATION_REF_VERSION as ue,ProviderAllocationRefSchema as de,RECOVERY_EVIDENCE_LIMITS as S,WorkerCapabilitiesSchema as fe,WorkerSchemas as pe,WorkerSubjects as C,WorkflowRunContextSchema as me,WorkflowRunResultSchema as he,WorkflowWorkerConfigSchema as w,createWorkflowCancelSubject as ge}from"@makaio/framework/contracts";import{BusAbortError as _e,createBusInstance as ve,isRequestCancellation as T,waitForSubscriptionPropagation as ye}from"@makaio/framework/bus";import{ExtensionCoordinator as be,KernelSubjects as xe,coalesceExtensionOverrides as Se,filterEligibleExtensions as Ce}from"@makaio/framework/kernel";import{BaseService as we}from"@makaio/framework/service-base";import{AdapterRuntimeSubjects as Te,registerAdapterRuntimeIdentityHandlers as Ee}from"@makaio/framework/services/adapter-runtime";import{devNull as E}from"node:os";import{CLIDetectionNamespace as De,CLIDetectionSubjects as Oe}from"@makaio/framework/services/cli-detection/namespace";import{SessionOrchestratorToken as ke,ToolRegistryToken as Ae,canonicalModelPackage as je,createSubagentServicePackage as Me,createToolContributionProcessor as Ne,frameworkCorePackages as D,sessionBridgePackage as Pe,sessionOrchestratorPackage as Fe,sessionPackage as Ie,sessionStoragePackage as Le,toolRegistryPackage as Re}from"@makaio/framework/services";import{AdapterSubsystemSubjects as ze}from"@makaio/framework/services/adapter-subsystem";import{createClientsCorePackage as Be}from"@makaio/framework/clients";import{AdapterSubsystemToken as O,createAdapterSubsystemContributionProcessor as Ve,createAdapterSubsystemPackage as He,orderAfterAdapterSubsystem as Ue}from"@makaio/framework/adapter-subsystem";import{execa as We}from"execa";import Ge from"piscina";import{ExecutionAttemptAuthority as Ke,WORKFLOW_WORKLOAD_KIND as qe,WORKFLOW_WORKLOAD_VERSION as Je,WorkflowStorageSubjects as Ye,buildWorkflowAttemptInstruction as Xe,parseWorkflowAttemptInstruction as k,runAuthorityDispatchedAttempt as Ze,toCommittedWorkflowRunnerCompletion as Qe}from"@makaio/framework/workflow-engine";import{runWorkflowOrchestrator as $e}from"@makaio/framework/workflow-engine/workflow-orchestrator";import{setTimeout as et}from"node:timers/promises";function tt(e){return e.on(ae.getCapabilities,async t=>{let{adapterName:n,adapterId:r}=t.payload;if(r){await t.next();return}if(n){let r=await e.requestOptional(Te.resolveId,{adapterName:n}),i=r.handled?r.data.adapterId:void 0;i&&(t.payload.adapterId=i)}await t.next()},{priority:20})}function nt(e){let{coordinator:t,configRepository:n,platformDefaults:r,prepareAuthRuntime:i,runtimeSnapshotHandlerPriority:a,runtimeDefinitionHandlerPriority:o}=e,s=He({configRepository:n,coordinator:t,platformDefaults:r,...i!==void 0&&{prepareAuthRuntime:i},...a!==void 0&&{runtimeSnapshotHandlerPriority:a},...o!==void 0&&{runtimeDefinitionHandlerPriority:o}});return t.registerContributionProcessor(Ve({getAdapterSubsystemService:()=>t.getExtensionService(O)})),{adapterSubsystemPackage:s}}function rt(e){let{bus:t,currentMachineId:n}=e,r=Ee(t,{currentMachineId:n,listKnownAdapterNames:e.listKnownAdapterNames??(async()=>{let{configs:e}=await t.request(ze.listAdapterConfigs,{});return e.map(e=>e.name)}),...e.resolveLiveAdapterId!==void 0&&{resolveLiveAdapterId:e.resolveLiveAdapterId},...e.resolveLiveAdapterIdentity!==void 0&&{resolveLiveAdapterIdentity:e.resolveLiveAdapterIdentity},...e.listLiveAdapterIdentities!==void 0&&{listLiveAdapterIdentities:e.listLiveAdapterIdentities}}),i=tt(t);return{cleanup:()=>{r.cleanup(),i()}}}function it(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=ot(t),i=(r===void 0?[t]:[t,n]).flatMap(e=>[`Cannot find package '${e}'`,`Cannot find module '${e}'`,`Cannot find package "${e}"`,`Cannot find module "${e}"`]),a=e;return(a.code===`ERR_MODULE_NOT_FOUND`||a.code===`MODULE_NOT_FOUND`)&&i.some(t=>e.message.includes(t))||a.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`&&r!==void 0&&e.message.includes(`Package subpath '${r}' is not defined by "exports"`)&&st(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function at(e){try{return await import(e)}catch(t){if(it(t,e))return null;throw t}}function ot(e){let t=e.split(`/`);return e.startsWith(`@`)?{rootPackageName:t.slice(0,2).join(`/`),subpath:t.length>2?`./${t.slice(2).join(`/`)}`:void 0}:{rootPackageName:t[0]??e,subpath:t.length>1?`./${t.slice(1).join(`/`)}`:void 0}}function st(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function A(e,t=process.env,n=process.platform){let r=t[Object.keys(t).find(e=>e.toUpperCase()===`PATH`)??`PATH`]??``,i=(t.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`).filter(Boolean),a=n===`win32`?h.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(h.delimiter)){let n=t.replace(/^"|"$/gu,``),r=h.resolve(n||process.cwd());for(let t of a){let n=h.join(r,`${e}${t}`);try{return await ee(n,ie.X_OK),n}catch{}}}}async function j(e,t=5e3,n=1e3){let{stdout:r}=await We(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function ct(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function lt(e,t=A,n=j){try{let r=await t(e);if(r===void 0)return{binary:e,found:!1};let i=await n(r);return i.length===0?{binary:e,found:!1}:{binary:e,found:!0,path:r,version:ct(i)}}catch{return{binary:e,found:!1}}}async function ut(e,t=A,n=j){return Promise.all(e.map(e=>lt(e,t,n)))}var dt=class extends we{constructor(e){super(e)}onInit(){this.registerHandler(Oe.scan,async e=>{let t=await ut(e.payload.binaries);e.setResult({results:t})})}};const M={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[De],create:e=>new dt(e.bus)};function N(e,t){e.push(...ft(t))}function ft(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function pt(e,t=[]){let n=new Set([e]),r=new Set,i=new Map;for(let e of t)typeof e==`string`?n.add(e):(r.add(e.id),e.version!==void 0&&i.set(e.id,e.version));return{hosts:n,capabilities:r,...i.size>0?{capabilityVersions:i}:{}}}function mt(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function P(e){return Se(Ce(gt(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function ht(e,n){let r=P(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function gt(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function F(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function _t(e,t){let n=F(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function I(e){return _t(e,`sessionOrchestrator`),F(e,`sessionOrchestrator`).length===0}function vt(e){return e===!0||I(e)?D:D.filter(e=>e.name!==ke.name)}function L(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&N(r,e.configure({bus:t,registerContributionProcessor:e=>{r.push(n.registerContributionProcessor(e))},forEachActiveExtension:e=>{n.forEachActiveExtension(e)}}))}}catch(e){let t=[];for(let e of[...r].reverse())try{e()}catch(e){t.push(e)}throw t.length>0?AggregateError([e,...t],`Extension boot contribution failed and rollback cleanup reported additional errors`,{cause:e}):e}return r}function yt(){let e=process.env.MAKAIO_SKIP_EXTENSIONS;if(!e)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(t)}var R=class{pool;constructor(e){this.pool=new Ge({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t,n){return this.pool.run(e,{signal:t,transferList:n})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},z=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function B(e,t,n){let r=h.resolve(t)+h.sep,i=h.resolve(e);if(i!==h.resolve(t)&&!i.startsWith(r))throw new z(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function V(e,t,n,r){let i=r??await m.realpath(t),a;try{a=await m.realpath(e)}catch{return e}let o=i+h.sep;if(a!==i&&!a.startsWith(o))throw new z(`${n} escapes allowed root via symlink: real path ${a} is not within ${i}`,`symlink-escape`);return a}function H(e){let t=e.indexOf(`-`);if(t===-1)throw new z(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function bt(e,t){let n=await m.readFile(e);return _.createHash(t).update(n).digest(`base64`)}const U=new Set([`.git`,`node_modules`]);function xt(e){return U.has(e.toLowerCase())}async function St(e,t){let n=t.toLowerCase();if(!U.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([m.lstat(h.join(e,t)),m.lstat(h.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const Ct=U,wt=new Set([`.DS_Store`]);async function W(e,t){let n=_.createHash(t),r=[];async function i(t){let n=await m.readdir(t,{withFileTypes:!0});for(let a of n){let n=h.join(t,a.name);if(a.isSymbolicLink())throw new z(`Contribution package contains a symbolic link: ${h.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){Ct.has(a.name)||await i(n);continue}if(a.isFile()){wt.has(a.name)||r.push(h.relative(e,n));continue}throw new z(`Contribution package contains an unsupported filesystem entry: ${h.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(h.sep).join(`/`)),n.update(`\0`),n.update(await m.readFile(h.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function G(e,t=`sha256`){let n=_.createHash(t),r=[];async function i(t){let n=await m.readdir(t,{withFileTypes:!0});for(let a of n){let n=h.join(t,a.name);if(!await St(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(h.relative(e,n));continue}throw a.isSymbolicLink()?new z(`Workspace root contains a symbolic link: ${h.relative(e,n)}`,`symlink-escape`):new z(`Workspace root contains an unsupported filesystem entry: ${h.relative(e,n)}`,`unsupported-filesystem-entry`)}}}await i(e),r.sort();for(let t of r){n.update(t),n.update(`\0`);let r=await m.readFile(h.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function K(e,t,n){let r=h.join(t,`node_modules`,e.packageName);B(r,t,`Contribution package directory`),await V(r,t,`Contribution package directory`,n);let i=h.join(r,`package.json`),a;try{a=await m.readFile(i,`utf-8`)}catch{throw new z(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let o=JSON.parse(a);if(o.name!==e.packageName)throw new z(`Contribution identity mismatch: expected ${e.packageName}, found ${o.name??`<none>`}`,`contribution-missing`);if(o.version!==e.version)throw new z(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${o.version??`<none>`}`,`contribution-version-mismatch`);let s=h.join(r,e.entrypoint);B(s,r,`Contribution entrypoint`),await V(s,t,`Contribution entrypoint`,n);try{await m.access(s)}catch{throw new z(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:c}=H(e.integrity),l;try{l=await W(r,c)}catch(t){if(t instanceof z)throw t;let n=typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`?t.code:void 0;throw n!==void 0&&!n.startsWith(`ERR_`)?new z(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(l!==e.integrity)throw new z(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${l}`,`contribution-integrity-mismatch`);return s}async function Tt(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new z(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await m.stat(r)).isDirectory())throw new z(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof z?e:new z(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await m.realpath(r),a=h.resolve(r,e.sourcePath);if(B(a,r,`Source path`),h.relative(r,a).split(h.sep).some(xt))throw new z(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await V(a,r,`Source path`,i);let o=await G(r);if(o!==e.rootDigest)throw new z(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${o}`,`digest-mismatch`);try{await m.access(a)}catch{throw new z(`Workflow source file not found: ${a}`,`source-missing`)}return{workspaceRoot:r,sourcePath:a,contributionEntrypoints:await Promise.all(t.map(e=>K(e,r,i))),platform:process.platform,arch:process.arch}}var Et=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new R(this.options);let r=n??this.manifest,i=await this.materializeTask(e,r,t);return{state:`uncommitted`,result:await this.pool.run(i,t)}}runWithReadiness(e,t,r,a){this.pool??=new R(this.options);let o=this.pool,s,c=!1,l,u=new Promise((t,r)=>{l=r,s=o.onMessage(r=>{n(r)&&r.executionAttemptId===a.executionAttemptId&&(r.executionId!==e.executionId||r.cancelSubject!==e.cancelSubject||(c=!0,s?.(),t(r)))})}),d=r??this.manifest,f=i(a.bootstrapDeadlineAt,t,async(t,n)=>{let r=await this.materializeTask(e,d,n);return o.run({...r,kind:`attempt-bound`,executionAttemptId:a.executionAttemptId,bootstrapDeadlineAt:a.bootstrapDeadlineAt,bootstrapPort:t},n,[t])});return f.then(()=>{c||(c=!0,s?.(),l(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{c||(c=!0,s?.(),l(e instanceof Error?e:Error(String(e))))}),{result:f,ready:u}}async dispose(){await this.pool?.dispose()}async materializeTask(e,t,n){if(n.throwIfAborted(),!(e.source.kind===`path`||t.contributionRefs.length>0))return{kind:`unbound`,config:e,manifest:t,contributionEntrypoints:[]};let r=e.materializationSpec;if(r?.kind!==`local-directory`)throw Error(`ThinWorkflowPiscinaRunner requires a local-directory materialization spec for path-backed workflows or declared contributions.`);if(this.options.resolveWorkspaceRoot===void 0)throw Error(`ThinWorkflowPiscinaRunner requires a host workspace-root resolver for local-directory materialization.`);let i=await Tt(r,t.contributionRefs,{resolveWorkspaceRoot:this.options.resolveWorkspaceRoot});if(n.throwIfAborted(),e.source.kind!==`path`)throw Error(`local-directory materialization requires a path-backed workflow source.`);return{kind:`unbound`,config:{...e,source:{kind:`path`,path:i.sourcePath}},manifest:t,contributionEntrypoints:i.contributionEntrypoints}}};function Dt(e){return e.mode===`source`?g(e.moduleDir,`workflow-worker`,`worker-entry.ts`):g(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var Ot=class{options;terminalAuthority=`authority`;constructor(e){this.options=e}async run(e,t,n,r){let i={...e,terminalAuthority:`authority`},a=n??this.options.manifest,o=this.options.requirements,s=r?.dispatchMetadata;t.throwIfAborted();let c=e.source.kind===`path`?await this.options.readRunContext?.(e.executionId,t):void 0;t.throwIfAborted();let l=Xe({id:v(),revision:`1`,config:e,...c==null?{}:{runContext:c},preservation:{required:[]}});return Qe(await Ze({authority:this.options.authority,executionId:e.executionId,instruction:l,withAttemptCreation:r?.withAttemptCreation,dispatch:e=>this.options.dispatch({executionAttemptId:e,config:i,...a!==void 0&&{manifest:a},...o!==void 0&&{requirements:o},...s!==void 0&&{metadata:s}},t)}),e)}},kt=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let r=w.parse(e),i=await s(r);return{state:`uncommitted`,result:await $e({config:await a(r,i,this.#e,t),loaded:i,bus:this.#e,signal:t})}}};function At(){return{contributionRefs:[]}}function jt(e){if(e.workflowRunner?.mode===`worker`&&!e.executionAttemptRepository)throw Error(`Worker dispatch mode requires an ExecutionAttemptRepository. Pass 'executionAttemptRepository' to createNodeWorkflowRunnerPackageOptions when workflowRunner.mode is 'worker'.`);let t;if(e.executionAttemptRepository){let n=e.executionAttemptBootstrapTimeoutMs;if(n===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);t=new Ke(e.executionAttemptRepository,{bootstrapTimeoutMs:n})}let n=te(e.runtimeModuleDir)===`src`?`source`:`dist`,r=Mt({moduleDir:e.runtimeModuleDir,defaultWorkerEntryMode:n,runner:e.workflowRunner,bus:e.bus,authority:t});return{...r!==void 0&&{workflowRunner:r},executorConfig:{busUrl:e.busUrl,busAuth:{kind:`none`},platformDefaults:e.platformDefaults,makaioHome:e.makaioHome},...e.executionAttemptRepository!==void 0&&{executionAttemptRepository:e.executionAttemptRepository},...t!==void 0&&{executionAttemptAuthority:t},...e.workflowMaterializationSpecResolvers!==void 0&&{workflowMaterializationSpecResolvers:e.workflowMaterializationSpecResolvers}}}function Mt(e){let{runner:t}=e;if(t)switch(t.mode){case void 0:case`in-process`:if(e.bus===void 0)throw Error(`InProcessWorkflowRunner requires a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'in-process'.`);return new kt({bus:e.bus});case`worker`:{if(e.authority===void 0)throw Error(`WorkerRunner requires an ExecutionAttemptAuthority. Pass 'authority' to createNodeWorkflowRunner when runner.mode is 'worker'.`);let n=e.bus,r=t.dispatch??(n===void 0?void 0:(e,t)=>n.request(C.dispatch,{executionAttemptId:e.executionAttemptId,config:e.config,manifest:e.manifest,requirements:e.requirements,metadata:e.metadata},{signal:t}));if(r===void 0)throw Error(`WorkerRunner requires either a dispatch function or a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'worker'.`);return new Ot({dispatch:r,authority:e.authority,...n!==void 0&&{readRunContext:async(e,t)=>(await n.request(Ye.getRunContext,{executionId:e},{signal:t})).runContext},...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new Et({workerEntry:t.workerEntry??Dt({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??At(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const Nt=new Set([`accepted`,`duplicate`]);var q=class extends Error{decision;result;reason;constructor(e,t,n=`authority-rejected`){super(`Outcome delivery ${n===`deadline-exceeded`?`deadline exceeded`:`rejected by Authority`} (decision=${e}, executionId=${t.executionId}, status=${t.status})`),this.decision=e,this.result=t,this.reason=n,this.name=`OutcomeDeliveryError`}},J=class extends Error{decision;payload;reason;constructor(e,t,n=`authority-rejected`){super(`Attempt outcome delivery ${n===`deadline-exceeded`?`deadline exceeded`:`rejected by Authority`} (decision=${e}, executionAttemptId=${t.executionAttemptId}, outcome=${t.outcome.kind})`),this.decision=e,this.payload=t,this.reason=n,this.name=`AttemptOutcomeDeliveryError`}},Pt=class extends Error{reason;constructor(e=`deadline-exceeded`){super(`Authority request delivery deadline exceeded`),this.reason=e,this.name=`AuthorityRequestDeliveryError`}};function Ft(e){let t={maxRetries:e?.maxRetries??7,baseDelayMs:e?.baseDelayMs??1e3,maxDelayMs:e?.maxDelayMs??3e4,deadlineMs:e?.deadlineMs??12e4};if(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0)throw TypeError(`Outcome submission maxRetries must be a non-negative safe integer, got ${t.maxRetries}`);for(let[e,n]of Object.entries({baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,deadlineMs:t.deadlineMs}))if(!Number.isFinite(n)||n<=0)throw TypeError(`Outcome submission ${e} must be a positive finite number, got ${n}`);return t}async function It(e,t,n,r){let i=t.baseDelayMs*2**(e-1),a=n-Date.now(),o=Math.min(i,t.maxDelayMs,a);await new Promise(e=>setTimeout(e,o));let s=n-Date.now();if(s<=0)return!1;if(r!==void 0){let e;try{await Promise.race([r(),new Promise(t=>{e=setTimeout(t,s)})])}catch{}finally{e!==void 0&&clearTimeout(e)}}return Date.now()<n}async function Lt(e,t,n,r){let i=Ft(n?.retry),a=n?.reconnect,o=Date.now()+i.deadlineMs,s;for(let n=0;n<=i.maxRetries;n++){if(o-Date.now()<=0||n>0&&!await It(n,i,o,a))throw t();try{let n=o-Date.now();if(n<=0)throw t();return await e(n)}catch(e){if(r(e))throw e;if(s=e,Date.now()>=o)throw t()}}throw s??t()}async function Rt(e,t){return await Lt(e,()=>new Pt,t,()=>!1)}async function zt(e,t,n){return await Lt(async n=>{let r=await e(n);if(Nt.has(r))return r;throw t(r)},()=>t(`deadline-exceeded`,`deadline-exceeded`),n,e=>e instanceof q||e instanceof J)}async function Bt(e,t,n){return await zt(async n=>(await e.request(C.control.outcome.submit,{executionAttemptId:t.executionAttemptId,executionId:t.executionId,result:t.result},{timeout:n})).decision,(e,n)=>n===void 0?new q(e,t.result):new q(e,t.result,n),n)}async function Vt(e,t,n){return await zt(async n=>(await e.request(x.outcome.submit,t,{timeout:n})).decision,(e,n)=>n===void 0?new J(e,t):new J(e,t,n),n)}const Ht={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},Ut={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]},Wt={code:`outcome-acknowledged`,summary:`Piscina runner settled and the Authority acknowledged its workflow outcome`},Gt={code:`outcome-delivery-ended`,summary:`Piscina runner settled and its bounded workflow outcome delivery ended`};function Y(e){let t=new Set,n;return{publish:r=>{if(n!==void 0)return;let i=r();n=i;let a=[...t];t.clear();for(let t of a)try{t(i)}catch(t){console.error(`${e} observer failed:`,t)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}function Kt(e){let t=Y(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion`);return{conclude:n=>{t.publish(()=>({evidence:y.parse({source:e.slice(0,S.source),summary:n.slice(0,S.summary),observedAt:new Date().toISOString()})}))},observe:t.observe}}function qt(e,t){let n=Y(`[PiscinaThinWorkflowProvider] Provider-completion`),r=Y(`[PiscinaThinWorkflowProvider] Local-observation-loss`),i;return{completion:{complete:r=>{i===void 0&&n.publish(()=>{let n=y.parse({source:e.slice(0,S.source),code:r.code,summary:r.summary,observedAt:new Date().toISOString()});return t(),i=`completion`,n})},observe:n.observe},localObservationLoss:{lose:()=>{i===void 0&&r.publish(()=>(i=`local-observation-loss`,{}))},observe:e=>r.observe(()=>e())}}}var Jt=class{executionAttemptId;controller;detachCallerAbort;infrastructure;completion;localObservationLoss;revokeBusIdentity;constructor(e,t,n,r,i,a,o){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r,this.completion=i,this.localObservationLoss=a,this.revokeBusIdentity=o}cancel(e){return this.controller.abort(e??`Worker cancelled`),this.detachCallerAbort(),Promise.resolve()}terminate(){return this.controller.abort(`Worker terminated`),this.detachCallerAbort(),this.revokeBusIdentity(),Promise.resolve()}release(){return this.detachCallerAbort(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}observeProviderCompletion(e){return this.completion.observe(e)}observeLocalObservationLoss(e){return this.localObservationLoss.observe(e)}},Yt=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=fe.parse({...Ut,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??Ut.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=await this.resolveLaunchBeforeAllocation(e,t);if(t.throwIfAborted(),`kind`in n)return n;let r=n,i=new AbortController,a=Kt(this.id),o=()=>{i.abort(t.reason)};t.addEventListener(`abort`,o,{once:!0});let s=()=>t.removeEventListener(`abort`,o),c;try{let{executionAttemptId:n,executionId:o}=e,u=this.buildAllocationRef(n),d=l({executionAttemptId:n,executionId:o}),f=!1,p=()=>{f||(f=!0,d.cleanup())};c=p;let m=qt(this.id,p),ee=new Jt(n,i,s,a,m.completion,m.localObservationLoss,p);t.throwIfAborted();let h=this.options.runner.runWithReadiness({...r,busAuth:{kind:`hmac`,secret:d.secret}},i.signal,e.runtimeInputs.workerManifest,{executionAttemptId:n,bootstrapDeadlineAt:e.bootstrapDeadlineAt});return h.ready.then(()=>this.submitOutcomeOnSettlement(h.result,o,n,r.workflowId,a.conclude,m.completion.complete),e=>{i.abort(e),h.result.catch(()=>void 0),c?.(),a.conclude(`Piscina worker for attempt '${n}' was refused before its workflow run was admitted: `+(e instanceof Error?e.message:String(e))),m.localObservationLoss.lose()}),{kind:`allocated`,allocationRef:u,handle:ee}}catch(e){throw i.abort(e),s(),c?.(),e}}async resolveLaunchBeforeAllocation(e,t){try{let n=await this.options.launchResolver(e,t);return t.throwIfAborted(),n.busUrl?n:this.confirmedAbsent(`Piscina workflow configuration has no bus URL before local allocation setup`)}catch{return t.throwIfAborted(),this.confirmedAbsent(`Workflow launch resolution failed before Piscina local allocation setup`)}}confirmedAbsent(e){return{kind:`confirmed-absent`,evidence:y.parse({source:`piscina-thin-workflow-provider`,code:le,summary:e,observedAt:new Date().toISOString()})}}async submitOutcomeOnSettlement(e,t,n,r,i,a){let o;try{o=await e}catch(e){o={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...Ht,...this.options.outcomeRetry};await Bt(this.options.bus,{executionAttemptId:n,executionId:t,result:o},{retry:e})}catch(e){e instanceof q?console.error(`[PiscinaThinWorkflowProvider] Outcome rejected for execution '${t}' attempt '${n}' (decision=${e.decision}):`,e):console.error(`[PiscinaThinWorkflowProvider] Failed to submit outcome for execution '${t}' attempt '${n}':`,e),i(`Piscina worker for attempt '${n}' ended without an acknowledged outcome because outcome submission could not be completed`),a(Gt);return}a(Wt)}buildAllocationRef(e){let t={version:ue,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return de.parse(t)}};function Xt(e){return async(t,n)=>{n.throwIfAborted();let r=await e({executionId:t.executionId,executionAttemptId:t.executionAttemptId});if(n.throwIfAborted(),r===null)throw Error(`Workflow launch instruction is unavailable for execution '${t.executionId}' attempt '${t.executionAttemptId}'`);let i=k(r);if(i.executionId!==t.executionId)throw Error(`Workflow instruction execution '${i.executionId}' does not match Worker request '${t.executionId}'`);return w.parse({source:i.source,...i.definitionSnapshot===void 0?{}:{definition:i.definitionSnapshot},executionId:i.executionId,workflowId:i.workflowId,triggerPayload:i.triggerPayload,...i.triggerMode===void 0?{}:{triggerMode:i.triggerMode},inputs:i.inputs,...i.config===void 0?{}:{config:i.config},...i.artifactRef===void 0?{}:{artifactRef:i.artifactRef},scope:i.scope,...t.connection.busUrl===void 0?{}:{busUrl:t.connection.busUrl},busAuth:t.connection.busAuth,...t.connection.env===void 0?{}:{env:t.connection.env},coordinatorSessionId:i.coordinatorSessionId,cancelSubject:i.cancelSubject,suspensionStrategy:t.runtimeInputs.suspensionStrategy,terminalAuthority:i.terminalAuthority,...i.materializationSpec===void 0?{}:{materializationSpec:i.materializationSpec}})}}const Zt=[Le,Pe,Ie];function Qt(e){let t;return()=>(t??=(async()=>{let t=[];for(let n of[...e].reverse())try{await n()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Isolated workflow runtime shutdown reported errors`)})(),t)}function $t(e,t,n){return rt({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(O)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(O)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(O)?.getLiveAdapterIdentities()??[]})}async function en(e){let t=ve();t.registerNamespaces([...oe,...se]);let{context:n}=e,r=new be(t,{surface:`headless`,extensionContextBase:{cwd:n.cwd,platform:n.platform,homedir:n.homedir,makaioHome:n.makaioHome,username:n.username,machineId:n.machineId,tryImport:at}}),i,a=[()=>t.disconnect()],o=Qt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=nt({coordinator:r,configRepository:e.configRepository,platformDefaults:{cwd:n.cwd},runtimeSnapshotHandlerPriority:1,runtimeDefinitionHandlerPriority:1,...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}}),l=Be({definitions:s.flatMap(e=>e.clients??[]),binaryResolutionPolicy:`global-only`});r.registerContributionProcessor(Ne());let u=[...Zt,c,je,...I(s)?[Fe]:[],Me(1),Re,M,l,...Ue(s)];r.load(u),a.push(...L(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=$t(t,r,n.machineId),a.push(()=>{i?.cleanup(),i=void 0});let d=r.getExtensionService(Ae);if(d===void 0)throw Error(`Isolated workflow tool registry did not start.`);for(let t of e.toolsets)await d.register(t);return await t.emit(xe.ready,{machineId:n.machineId}),{bus:t,coordinator:r,machineId:n.machineId,shutdown:o}}catch(e){throw await o().catch(()=>void 0),e}}function tn(e){return Number.isInteger(e)&&e>=1&&e<=2147483647}function X(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function nn(e,t){try{process.kill(-e,0)}catch(e){if(e.code===`ESRCH`)return!1;if(e.code!==`EPERM`)throw e}let n;try{n=await rn(t)}catch{return!0}let r=!1;for(let t of n.trim().split(`
2
+ `)){let[n,i,a]=t.trim().split(/\s+/);if(n===``||i===void 0||a!==void 0||!/^\d+$/.test(n)||i===``||Number(n)===e&&(r=!0,!i.startsWith(`Z`)))return!0}return!r}function rn(e){return new Promise((t,n)=>{d(`ps`,[`-A`,`-o`,`pgid=,stat=`],{timeout:e,maxBuffer:1024*1024},(e,r)=>{if(e!==null){n(e);return}t(r)})})}async function an(e){if(e===void 0)return!0;try{try{X(e,`SIGKILL`)}catch(e){if(e.code!==`EPERM`)throw e}let t=Date.now()+2e3;for(;Date.now()<t;){let n=t-Date.now();if(n<=0)break;if(!await nn(e,Math.min(1e3,n)))return!0;await et(20)}}catch{}return!1}async function on(e){if(e.signal?.aborted)return{status:`cancelled`,exitCode:null};if(!tn(e.recipe.timeoutMs))return{status:`spawn-failed`,exitCode:null,message:`Setup timeout must be an integer between 1 and 2147483647 milliseconds`};if(process.platform===`win32`)return{status:`spawn-failed`,exitCode:null,message:`Setup process groups require a POSIX host`};try{return await sn(e)}catch{return{status:`spawn-failed`,exitCode:null,message:`Could not start the setup command`}}}function sn(e){return new Promise(t=>{let n=f(e.recipe.command,e.recipe.args,{cwd:e.workspaceRoot,env:{...process.env,...e.recipe.env,...e.env},shell:!1,detached:!0,stdio:`ignore`}),r,i,a=e=>{if(r===void 0&&(r=e,n.pid!==void 0)){try{X(n.pid,`SIGTERM`)}catch(e){if(e.code!==`EPERM`){r=`stop-failed`;return}}i=setTimeout(()=>{try{n.pid!==void 0&&X(n.pid,`SIGKILL`)}catch(e){e.code!==`EPERM`&&(r=`stop-failed`)}},200)}},o=()=>a(`cancelled`),s=setTimeout(()=>a(`timed-out`),e.recipe.timeoutMs);e.signal?.addEventListener(`abort`,o,{once:!0}),e.signal?.aborted&&o(),n.once(`error`,()=>{r=`spawn-failed`}),n.once(`close`,a=>{clearTimeout(s),clearTimeout(i),e.signal?.removeEventListener(`abort`,o),an(n.pid).then(e=>{t({status:e?r??(a===0?`completed`:`failed`):`stop-failed`,exitCode:a})})})})}async function cn(e,t,n){if(h.isAbsolute(t)||t.includes(`\\`)||t.split(`/`).includes(`..`))throw Error(`Source root must be workspace-relative`);let r=e;for(let i of t.split(`/`).filter(e=>e!==``&&e!==`.`))if(r=h.join(r,i),B(r,e,`Source root`),await V(r,e,`Source root`,e),n&&await m.mkdir(r).catch(e=>{if(e.code!==`EEXIST`)throw e}),!(await m.stat(r)).isDirectory())throw Error(`Source root must be a directory`);return V(r,e,`Source root`,e)}async function ln(e){e.signal?.throwIfAborted();let{requirement:t}=e,n=h.resolve(e.workspaceRoot);if(!h.isAbsolute(e.workspaceRoot)||n===h.parse(n).root)throw Error(`Workspace root must be an absolute, non-filesystem-root directory`);if(t.sourceRoots.length>1)throw Error(`Multiple source roots are not implemented`);if(t.sourceRoots.some(e=>e.source!==void 0)){if(e.realizeSource===void 0)throw Error(`Source acquisition requires an installed strategy`);if(t.provisioning!==`create`||t.custody!==`disposable`)throw Error(`Source acquisition currently requires a created disposable workspace`)}if(t.provisioning===`create`&&await m.mkdir(n),!(await m.lstat(n)).isDirectory())throw Error(`Workspace root must be a directory, not a symlink`);let r=await m.realpath(n),i=[];for(let n of t.sourceRoots){let a=await cn(r,n.path,t.provisioning===`create`);n.source!==void 0&&(await e.realizeSource({source:n.source,destination:a,signal:e.signal}),e.signal?.throwIfAborted()),i.push({id:n.id,path:a})}return un(t,{workspaceRoot:r,sourceRoots:i})}function un(e,t){let n=t.workspaceRoot,r=e.custody,i=!1,a=!0,o;return{binding:t,async runSetup(t={}){if(o!==void 0||i||!a)throw Error(`Workspace setup is unavailable`);if(t.signal?.aborted)return{status:`cancelled`,exitCode:null};i=!0;try{for(let[r,i]of e.setup.entries()){let e=await on({...t,recipe:i,workspaceRoot:n});if(a=e.status!==`stop-failed`,e.status!==`completed`)return{...e,commandIndex:r}}return{status:`completed`,exitCode:0}}finally{i=!1}},release(){return i||!a?Promise.reject(Error(`Workspace commands have not stopped`)):(o??=r===`external`?Promise.resolve():m.rm(n,{recursive:!0,force:!0}),o)}}}function Z(e,t){return e instanceof _e?T(e,t):t?.aborted===!0?e===t.reason||e instanceof DOMException&&e.name===`AbortError`?!0:e instanceof Error&&e.name===`AbortError`&&`code`in e&&e.code===`ABORT_ERR`&&Object.is(e.cause,t.reason):!1}async function dn(e,t,n,r){let i=b[`instruction.get`].response.parse(await e.request(x.instruction.get,{executionAttemptId:t,runtimeGeneration:n},{signal:r}));if(i.decision===`found`)return i.instruction;throw Error(`Attempt instruction read refused: ${i.refusalReason}`)}async function fn(e,t,n,r){let{executionAttemptId:i,runtimeGeneration:a}=t,o=b[`operation.admit`].response.parse(await Rt(async t=>await e.request(x.operation.admit,{executionAttemptId:i,runtimeGeneration:a,operationKind:n,admissionKey:r},{timeout:t}),{retry:t.retry,reconnect:t.reconnect}));if(o.decision===`refused`||o.operationId===void 0)throw Error(`Attempt ${n} admission refused: ${o.refusalReason??`missing-operation-id`}`);return o.operationId}function Q(e){return(e instanceof Error?e.message:String(e)).slice(0,8192)||`Local execution failed without a diagnostic message`}function pn(e,t){return e.find(e=>e.kind===t.workload.kind&&e.version===t.workload.version)}function mn(e){return{signal:e??new AbortController().signal,release:()=>{}}}async function $(e,t,n,r,i,a){let o=await Vt(e,{executionAttemptId:t.executionAttemptId,runtimeGeneration:t.runtimeGeneration,...i===void 0?{}:{operationId:i},outcome:r},{retry:t.retry,reconnect:t.reconnect});if(a!==void 0&&n!==void 0&&r.kind===`workload-result`&&n.preservation.required.length===0)try{await a.release()}catch{console.warn(`[makaio-worker] Acknowledged workspace cleanup failed.`)}return{outcome:r,decision:o}}async function hn(e,t,n,r){let i=b[`operation.report`].response.parse(await Rt(async i=>await e.request(x.operation.report,{executionAttemptId:t.executionAttemptId,runtimeGeneration:t.runtimeGeneration,operationId:n,result:{kind:`workspace-prepared`,binding:r.binding}},{timeout:i}),{retry:t.retry,reconnect:t.reconnect}));return i.decision===`refused`?void 0:i.binding}function gn(e){if(e.status!==`completed`)return e.status===`cancelled`?{kind:`cancelled`}:e.status===`stop-failed`?{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace setup stop-failed`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace setup ${e.status}`}}async function _n(e,t,n,r){if(r.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,void 0);let i=await fn(e,t,`workspace-preparation`,`workspace-preparation:${n.id}:${t.runtimeGeneration}`);if(r.aborted)return await $(e,t,n,{kind:`cancelled`},i,void 0);let a,o;try{if(t.workspaceRoot===void 0)throw Error(`Workspace preparation requires an explicit local root`);let e=await(t.preparation??{prepare:ln}).prepare({requirement:n.workspace,workspaceRoot:t.workspaceRoot,signal:r});a=e,o=await e.runSetup({signal:r,env:t.setupEnv})}catch(o){return await $(e,t,n,Z(o,r)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:Q(o)},i,a)}let s=gn(o);if(s!==void 0)return await $(e,t,n,s,i,a);if(r.aborted)return await $(e,t,n,{kind:`cancelled`},i,a);let c=await hn(e,t,i,a);return c===void 0?await $(e,t,n,{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace preparation report refused by the Authority`},i,a):r.aborted?await $(e,t,n,{kind:`cancelled`},void 0,a):{handle:a,binding:c}}async function vn(e,t,n,r,i){if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,void 0);let a,o;if(n.workspace!==void 0){let r=await _n(e,t,n,i.signal);if(`outcome`in r)return r;a=r.handle,o=r.binding}if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,a);let s=await fn(e,t,`workload-invocation`,`workload-invocation:${n.id}:${t.runtimeGeneration}`);if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},s,a);let c;try{c={kind:`workload-result`,result:ce.parse(await r.invoke({instruction:n,...o===void 0?{}:{workspace:o},signal:i.signal}))}}catch(e){c=Z(e,i.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workload-invocation`,message:Q(e)}}return await $(e,t,n,c,s,a)}async function yn(e,t){let n;try{n=await dn(e,t.executionAttemptId,t.runtimeGeneration,t.signal)}catch(n){if(T(n,t.signal))return await $(e,t,void 0,{kind:`cancelled`},void 0,void 0);throw n}let r=pn(t.adapters,n);if(r===void 0)return await $(e,t,n,{kind:`technical-failure`,stage:`startup`,message:`Required adapter '${n.workload.kind}' version '${n.workload.version}' is unavailable`},void 0,void 0);let i;try{i=await(r.bindControl?.({instruction:n,signal:t.signal})??mn(t.signal))}catch(r){let i=Z(r,t.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`startup`,message:Q(r)};return await $(e,t,n,i,void 0,void 0)}try{return await vn(e,t,n,r,i)}finally{try{i.release()}catch{console.warn(`[makaio-worker] Workload control release failed.`)}}}async function bn(e,t,n,r,i){let a=pe[`runtime.inputs.get`].response.parse(await e.request(C.runtime.inputs.get,{executionAttemptId:t},{signal:i}));if(a.runtimeInputs===null)throw Error(`Selected Worker Runtime inputs are unavailable`);return me.parse({...n,...a.runtimeInputs,createdAt:0,env:r})}function xn(e,t){let n=(e,t)=>{let n=re(e,t);return n===``||!ne(n)&&n!==`..`&&!n.startsWith(`../`)&&!n.startsWith(`..\\`)};return n(e,t)||n(t,e)}async function Sn(t,n,r,i){let a=await t.loadContributions(r,i);i.throwIfAborted();let o=e();return await en({connectAuthority:e=>t.connectBus(e,n,i),contributedPackages:[...a],configRepository:t.configRepository,context:{cwd:r.workspaceRoot,platform:r.platform,homedir:o,makaioHome:o,username:`workflow-worker`,machineId:`headless-worker-${t.executionAttemptId}`},toolsets:[...t.toolsets],...t.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:t.prepareAuthRuntime}})}function Cn(e,t,n){let r={...e.workflowEnv},i,a=!0;return{adapter:{kind:qe,version:Je,async bindControl({instruction:t,signal:r}){let i=k(t);if(i.executionId!==e.executionId)throw Error(`Workflow instruction execution identity mismatch`);let a=new AbortController,o=n.on(ge(i.cancelSubject),()=>a.abort());try{return await ye(o),{signal:AbortSignal.any([...r===void 0?[]:[r],a.signal]),release:o}}catch(e){throw o(),e}},async invoke({instruction:o,workspace:s,signal:c}){let l=k(o);a=o.preservation.required.length!==0;let u=c??new AbortController().signal,d;try{u.throwIfAborted();let a=await bn(n,e.executionAttemptId,l,r,u),o=await e.materialize(a,u);(s===void 0||!xn(o.context.workspaceRoot,s.workspaceRoot))&&(i=o.cleanup);let c=wn(o.context,s);return u.throwIfAborted(),d=await Sn(e,t,c,u),u.throwIfAborted(),await e.execute(d.bus,a,c,u)}finally{await d?.shutdown()}}},async releaseExecutable(e){e===void 0||a||e.outcome.kind===`workload-result`&&(e.decision!==`accepted`&&e.decision!==`duplicate`||await i?.().catch(()=>void 0))}}}function wn(e,t){return t===void 0?e:{...e,workspaceRoot:t.workspaceRoot}}async function Tn(e,t){if(!(t.outcome.kind!==`workload-result`||e.onPostCommit===void 0))try{let n=he.parse(t.outcome.result);await e.onPostCommit(n,t.decision)}catch{}}async function En(e,t){t.throwIfAborted();let n={...e.workflowEnv},i=v(),a=await c(e.bootstrapDeadlineAt,t,t=>e.bootstrap(t)),{connection:s,endpoint:l}=await o({executionAttemptId:e.executionAttemptId,runtimeIncarnationId:i,bootstrapDeadlineAt:e.bootstrapDeadlineAt,signal:t,createConnection:()=>Dn(e,a)}),u=s.bus,d=Cn({...e,workflowEnv:n},a,u),f;try{let n=await r(u,{executionAttemptId:e.executionAttemptId,runtimeIncarnationId:i,signal:t});return l.bindGeneration(n),f=await yn(u,{executionAttemptId:e.executionAttemptId,runtimeGeneration:n,workspaceRoot:e.workspaceRoot,setupEnv:e.setupEnv,preparation:e.preparation,adapters:[d.adapter],signal:t,retry:e.outcomeRetry,reconnect:()=>u.reconnect()}),await Tn(e,f),f}finally{try{await d.releaseExecutable(f)}finally{l.cleanup(),await s.close()}}}function Dn(e,t){let n=ve();return n.registerNamespaces([...oe,...se]),{bus:n,async connect(r){try{await e.connectBus(n,t,r),r.throwIfAborted()}catch(e){throw n.disconnect(),e}},close:()=>n.disconnect()}}const On=p(d),kn=[`-c`,`core.attributesFile=${E}`],An=u.object({repositoryId:u.string().min(1),revision:u.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,`Git source revision must be a full commit object ID`)}).strict();async function jn(e,t,n){try{let r=await e.resolveRepository(t,n);if(!h.isAbsolute(r))throw Error(`Repository access did not return an absolute path`);return await m.realpath(r)}catch(e){throw Z(e,n)?e:Error(`Git source access failed`)}}async function Mn(e,t,n,r,i){let a;try{a=(await On(`git`,[...kn,`cat-file`,`-t`,t],{cwd:e,env:{...process.env,...n},signal:i,timeout:r,maxBuffer:1024,shell:!1,killSignal:`SIGKILL`,encoding:`utf8`})).stdout.trim()}catch(e){throw Z(e,i)?e:Error(`Git source object inspection failed`)}if(a!==`commit`)throw Error(`Git source revision must identify a commit object`)}function Nn(e){if(!tn(e.timeoutMs))throw Error(`Git command timeout must be an integer between 1 and 2147483647 milliseconds`);if(process.platform===`win32`)throw Error(`Local Git source preparation requires a POSIX host`);return async({source:t,destination:n,signal:r})=>{if(r?.throwIfAborted(),t.kind!==`git`)throw Error(`Unsupported local Git source kind`);let i=An.parse(t.input),a=await jn(e,i.repositoryId,r);r?.throwIfAborted();let o={...Object.fromEntries(Object.keys(process.env).filter(e=>/^git_/i.test(e)).map(e=>[e,void 0])),GIT_CONFIG_GLOBAL:E,GIT_CONFIG_SYSTEM:E,GIT_ATTR_NOSYSTEM:`1`},s=[[`init`,`--object-format=${i.revision.length===64?`sha256`:`sha1`}`],[`fetch`,`--no-tags`,`--no-write-fetch-head`,`--update-shallow`,`--`,a,i.revision],[`checkout`,`--detach`,i.revision,`--`]];for(let t of s){t[0]===`checkout`&&await Mn(n,i.revision,o,e.timeoutMs,r);let a=await on({workspaceRoot:n,signal:r,env:o,recipe:{command:`git`,args:[...kn,...t],env:{},timeoutMs:e.timeoutMs}});if(a.status===`cancelled`&&r?.throwIfAborted(),a.status!==`completed`)throw Error(`Git source ${t[0]} ${a.status}`)}}}function Pn(e){let t=Nn(e);return{prepare:e=>ln({...e,realizeSource:t})}}export{mt as A,nt as B,G as C,K as D,H as E,vt as F,M as I,it as L,L as M,P as N,pt as O,ht as P,at as R,W as S,Tt as T,tt as V,Dt as _,Xt as a,B as b,Pt as c,Vt as d,Bt as f,Ot as g,kt as h,en as i,yt as j,N as k,Nt as l,jt as m,En as n,Yt as o,Mt as p,yn as r,J as s,Pn as t,q as u,Et as v,bt as w,V as x,z as y,rt as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makaio/framework",
3
- "version": "1.0.0-dev-1788966380232",
3
+ "version": "1.0.0-dev-1789000242829",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/makaio-ai/makaio-framework.git",
@@ -1 +0,0 @@
1
- import{C as e,S as t,a as n,c as r,d as i,i as a,l as o,n as s,r as c,y as l}from"./schemas-DRho446W.mjs";import{a as u,c as d,d as f,f as p}from"./kind-registration-DggkrLkv.mjs";import{t as m}from"./zod-json-schema-DGWHUOK0.mjs";import{z as h}from"zod";import{createBusNamespace as g}from"@makaio/framework/core";const _=h.strictObject({evidence:t}),v=h.strictObject({kind:h.literal(`text`),text:h.string()}),[y,b,x]=t.options,S=h.union([y.pick({source:!0,location:!0}).extend({content:v}),b.pick({source:!0,location:!0}).extend({content:v}),x.pick({source:!0,location:!0}).extend({content:v})]);function C(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function w(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function T(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=C(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:C(r);return i===void 0?void 0:{node:i,pointer:n}}function E(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:C(n)?.[t],typeof C(n)?.$id==`string`)return!0}return!1}function D(e,n,r){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let i=t.safeParse(n);if(!i.success)throw Error(`Invalid schema-declared evidence at ${r}`);return{evidence:i.data,dataPath:r}}function O(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=T(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&k(e,i.node,n,E(e,i.pointer))}function k(e,t,n=new WeakSet,r=!1){let i=C(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||O(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>k(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>k(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>k(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=C(i[t]);if(r&&Object.values(r).some(t=>k(e,t,n,a)))return!0}return!1}var A=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(E(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=T(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=D(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=C(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:C(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=C(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=C(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=C(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${w(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(k(this.dataSchema,e[r],void 0,E(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=C(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?C(e.additionalItems):C(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=C(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=C(e.properties),a=C(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=w(o),c=i!==void 0&&Object.hasOwn(i,o),l=C(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let u=this.visitPatterns(a,o,s,`${n}/${t}`,r),d=C(e.additionalProperties);!c&&!u&&d&&this.visit(d,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=C(s);e&&this.visit(e,n,r,`${i}/patternProperties/${w(o)}`)}return a}};function j(e,t,n){return new A(e,n.matchesSchema).extract(t)}function M(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...m(t)};f(i);let a=u.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=h.fromJSONSchema(a.dataSchema),s=h.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{p(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}function N(e){return{hooks:[...e.hooks]}}const P=[`inline`,`summary`,`link`,`omit`],F=h.string().min(1),I=h.object({kinds:h.array(h.string().min(1)).optional(),hint:F.optional(),depth:h.number().int().min(1).max(20).optional(),nested:h.lazy(()=>L).optional()}),L=h.record(h.string().min(1),I);function R(e){return JSON.stringify([e.kind,e.id,e.revision])}const z=h.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),B=h.object({target:o,sourceRef:e,relationType:h.string().min(1),hint:F,status:h.enum([`resolved`,`unresolved`]),reason:z.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:h.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:h.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:h.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),V=h.object({rootRef:e,refs:h.array(B),resolved:h.array(i)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(R));n.has(R(e.rootRef))||t.addIssue({code:h.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(R(e.sourceRef))||t.addIssue({code:h.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(R(e.target))||t.addIssue({code:h.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function H(e){let t=V.parse(e),n=new Map(t.resolved.map(e=>[q(e),e])),r=new Map;for(let e of t.refs){let t=q(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(q(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${q(t.rootRef)}'`);let a=U(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return K(a,e),e}}}function U(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:G(e,r,i,new Set([q(e)]))}}function W(e,t,n,r,i,a,o){let s=q(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:G(e,i,a,c)}}function G(e,t,n,r){return(t.get(q(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=q(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:W(e.target,a,e.relationType,e.hint,t,n,r)})}function K(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)K(n,t)}}function q(e){return JSON.stringify([e.kind,e.id,e.revision])}const J={"kind.register":{request:u,response:h.object({registered:h.boolean()})},"kind.list":{request:h.object({kind:h.string().min(1).optional()}),response:h.object({kinds:h.array(u)})},"relation-type.register":{request:l,response:h.object({registered:h.boolean()})},"relation-type.list":{request:h.object({type:h.string().min(1).optional()}),response:h.object({relationTypes:h.array(l)})},create:{request:i.omit({id:!0,revision:!0,timestamp:!0}).extend({id:e.shape.id.optional()}),response:h.object({artifact:i})},revise:{request:h.object({previous:e,statusPath:h.string().regex(/^(?:\/(?:[^~/]|~[01])*)+$/,`Expected a data-relative JSON Pointer`).optional(),revision:i.omit({id:!0,revision:!0,timestamp:!0})}),response:h.object({artifact:i})},resolve:{request:h.object({ref:e}),response:h.object({artifact:i.nullable()})},query:{request:n,response:h.object({artifacts:h.array(i)})},compare:{request:s,response:c},"evidence.resolve":{request:_,response:S},resolveContext:{request:h.object({ref:e,selectors:L.optional(),maxDepth:h.number().int().min(1).max(20).default(5)}),response:h.object({context:V})},created:h.object({artifact:i}),revised:h.object({previous:e,artifact:i}),"relation.added":h.object({artifact:e,relation:r}),"observation.added":h.object({artifact:e,observation:a}),"status.changed":h.object({artifact:e,path:h.string().min(1),previous:h.unknown().optional(),current:h.unknown().optional()}),"kind.changed":h.object({kind:h.string().min(1),schemaVersion:d})},Y=g(`artifact`,J),X=Y.subjects;export{B as a,P as c,L as d,N as f,S as g,_ as h,H as i,I as l,j as m,J as n,z as o,M as p,X as r,V as s,Y as t,F as u};