@makaio/framework 1.0.0-dev-1788811230746 → 1.0.0-dev-1788863979610

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 (284) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/adapters/config/index.d.mts +1 -1
  3. package/dist/adapters/index.d.mts +2 -2
  4. package/dist/adapters/node.d.mts +1 -1
  5. package/dist/{artifact-Btbuib48.mjs → artifact-ClvHqL3w.mjs} +1 -1
  6. package/dist/attempt-record-codec-BcAPEIW3.mjs +1 -0
  7. package/dist/bus/index.mjs +1 -1
  8. package/dist/clients/index.d.mts +1 -1
  9. package/dist/clients/managed-install.d.mts +1 -1
  10. package/dist/code-execution/worker-entry.d.mts +1 -1
  11. package/dist/{context-resolution-C2VBZhaR.d.mts → context-resolution-BZKEKzu4.d.mts} +98 -19
  12. package/dist/contracts/adapter/index.d.mts +2 -2
  13. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  14. package/dist/contracts/artifact/index.d.mts +3 -3
  15. package/dist/contracts/artifact/index.mjs +1 -1
  16. package/dist/contracts/auth/index.d.mts +2 -2
  17. package/dist/contracts/automation-trigger/index.d.mts +3 -3
  18. package/dist/contracts/canonical-model/index.d.mts +1 -1
  19. package/dist/contracts/capabilities/index.d.mts +1 -1
  20. package/dist/contracts/client/index.d.mts +2 -2
  21. package/dist/contracts/code-execution/index.d.mts +1 -1
  22. package/dist/contracts/common/index.d.mts +1 -1
  23. package/dist/contracts/config/index.d.mts +1 -1
  24. package/dist/contracts/extension/index.d.mts +5 -5
  25. package/dist/contracts/facet/index.d.mts +1 -1
  26. package/dist/contracts/harness/index.d.mts +1 -1
  27. package/dist/contracts/host/index.d.mts +1 -1
  28. package/dist/contracts/index.d.mts +70 -70
  29. package/dist/contracts/index.mjs +1 -1
  30. package/dist/contracts/materialization/index.d.mts +3 -3
  31. package/dist/contracts/materialization/index.mjs +1 -1
  32. package/dist/contracts/model-registry/index.d.mts +1 -1
  33. package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
  34. package/dist/contracts/platform/index.d.mts +1 -1
  35. package/dist/contracts/provider/index.d.mts +2 -2
  36. package/dist/contracts/reaction/index.d.mts +1 -1
  37. package/dist/contracts/session/index.d.mts +2 -2
  38. package/dist/contracts/shared/index.d.mts +2 -2
  39. package/dist/contracts/skill/index.d.mts +1 -1
  40. package/dist/contracts/telemetry/index.d.mts +1 -1
  41. package/dist/contracts/timeout/index.d.mts +1 -1
  42. package/dist/contracts/variant/index.d.mts +1 -1
  43. package/dist/contracts/worker/index.d.mts +1 -1
  44. package/dist/contracts/worker/index.mjs +1 -1
  45. package/dist/contracts/workflow/index.d.mts +2 -2
  46. package/dist/contracts/workflow/index.mjs +1 -1
  47. package/dist/{contribution-Crm-mctl.d.mts → contribution-CQIpPQLl.d.mts} +2 -2
  48. package/dist/{definition-u_5rYQtc.d.mts → definition-Cdpw5l9g.d.mts} +1 -1
  49. package/dist/{detached-extension-handle-DAXKQT9c.mjs → detached-extension-handle-2yUaviLu.mjs} +1 -1
  50. package/dist/execution-attempt-owner-recovery-BRjtmTGv.mjs +1 -0
  51. package/dist/{execution-attempt-repository-OryBjQQI.d.mts → execution-attempt-repository-CPk3F98N.d.mts} +122 -3
  52. package/dist/execution-attempt-repository-D0cCU7dI.mjs +1 -0
  53. package/dist/{hook-responses-DcapjzLb.d.mts → hook-responses-DK6uu35J.d.mts} +1 -1
  54. package/dist/{index-DEpAI8CY.d.mts → index-1y-PUD3B.d.mts} +1 -1
  55. package/dist/{index-9PUmCySn.d.mts → index-B8Tc0urp.d.mts} +6 -5
  56. package/dist/{index-QJW9g1mG.d.mts → index-B9vEfalH.d.mts} +1 -1
  57. package/dist/{index-BDDavX2S.d.mts → index-BDs5tDcM.d.mts} +2 -2
  58. package/dist/{index-CgqEyk9R.d.mts → index-BlJbchHp.d.mts} +1 -1
  59. package/dist/{index-BxTM9lY0.d.mts → index-C3uCMCHI.d.mts} +3 -3
  60. package/dist/{index-J-kv32zv.d.mts → index-COSxBdTp.d.mts} +2 -2
  61. package/dist/{index-DrO6QLwf2.d.mts → index-CXZ8ODDT.d.mts} +1 -1
  62. package/dist/{index-CnGHGFMC.d.mts → index-Cjy1_Hc2.d.mts} +13 -13
  63. package/dist/{index-DIhkK4Y0.d.mts → index-CsDj-DEW.d.mts} +1 -1
  64. package/dist/{index-BwccWakG.d.mts → index-CvWUgywU.d.mts} +1 -1
  65. package/dist/{index-BDzqNCXs.d.mts → index-D5UpsCNq.d.mts} +1 -1
  66. package/dist/{index-Cbv_3Xi12.d.mts → index-D9CdrFKz2.d.mts} +1 -1
  67. package/dist/{index-CfJKwWJa.d.mts → index-DQWEOn6i.d.mts} +1 -1
  68. package/dist/{index-CAYbui7g.d.mts → index-DXv51ZIb.d.mts} +125 -37
  69. package/dist/{index-DsjUnKyr.d.mts → index-DmTBlEzu.d.mts} +1 -1
  70. package/dist/{index-Df9L5wwp.d.mts → index-Dne0xNUI.d.mts} +382 -82
  71. package/dist/{index-Bo3LRb2u.d.mts → index-DtHmaj-q.d.mts} +1 -1
  72. package/dist/{index-CXH1Bk0W.d.mts → index-DvV7vEKt.d.mts} +5 -5
  73. package/dist/{index-B6Kr3cxD2.d.mts → index-DwFnHNoq2.d.mts} +36 -12
  74. package/dist/{index-BTCodvXA.d.mts → index-jZXIrHlY.d.mts} +5 -5
  75. package/dist/{index-BhOMZWZa2.d.mts → index-zCstNu9J2.d.mts} +12 -12
  76. package/dist/kernel/cli/index.d.mts +2 -2
  77. package/dist/kernel/cli/register.d.mts +1 -1
  78. package/dist/kernel/extension/index.d.mts +1 -1
  79. package/dist/kernel/index.d.mts +5 -5
  80. package/dist/kernel/namespace/index.d.mts +1 -1
  81. package/dist/kernel/observability/index.d.mts +1 -1
  82. package/dist/kernel/providers/index.d.mts +1 -1
  83. package/dist/kernel/window/index.d.mts +1 -1
  84. package/dist/{lib-271rPR7A.mjs → lib-BB0XjVs6.mjs} +1 -1
  85. package/dist/{lib-RFpLjUda.mjs → lib-DNGNIb-O.mjs} +1 -1
  86. package/dist/{load-extensions-CY8ELnCp.d.mts → load-extensions-C3Y3y9EW.d.mts} +1 -1
  87. package/dist/{load-extensions-D9inWcDy.mjs → load-extensions-CWlR-8BM.mjs} +1 -1
  88. package/dist/{materialization-lVd9_-jr.mjs → materialization-B_LA9pfy.mjs} +1 -1
  89. package/dist/{namespace-DAINF1II.d.mts → namespace-DeezOMb9.d.mts} +2 -2
  90. package/dist/{namespace-CxXNlHpn.d.mts → namespace-agOiy4kr.d.mts} +3 -3
  91. package/dist/node/bus-server/index.d.mts +1 -1
  92. package/dist/node/bus-server/server-lifecycle.d.mts +1 -1
  93. package/dist/{package-DEYXB80d.mjs → package-BdOoo7XE.mjs} +2 -2
  94. package/dist/{package-eOEt1w6u.d.mts → package-w4WZqO7J.d.mts} +26 -4
  95. package/dist/package.json +1 -1
  96. package/dist/rules/index.d.mts +1 -1
  97. package/dist/rules/schemas.d.mts +1 -1
  98. package/dist/runtime-bun/index.mjs +1 -1
  99. package/dist/runtime-node/code-execution/index.d.mts +2 -2
  100. package/dist/runtime-node/extension-discovery.d.mts +1 -1
  101. package/dist/runtime-node/extension-validation.d.mts +1 -1
  102. package/dist/runtime-node/extension-validation.mjs +1 -1
  103. package/dist/runtime-node/index.d.mts +5 -5
  104. package/dist/runtime-node/index.mjs +2 -2
  105. package/dist/runtime-node/makaio-config.d.mts +1 -1
  106. package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
  107. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  108. package/dist/schemas-CNkUEbIr.mjs +1 -0
  109. package/dist/{schemas-Dn1JDTPw.d.mts → schemas-uaQuIxm4.d.mts} +2 -2
  110. package/dist/services/adapter-runtime/index.d.mts +3 -3
  111. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  112. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  113. package/dist/services/adapter-subsystem/index.d.mts +3 -3
  114. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  115. package/dist/services/agent-runtime/index.d.mts +2 -2
  116. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  117. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  118. package/dist/services/capability/index.d.mts +2 -2
  119. package/dist/services/code-execution/index.d.mts +1 -1
  120. package/dist/services/codebase/index.d.mts +2 -2
  121. package/dist/services/codebase/namespace.d.mts +1 -1
  122. package/dist/services/codebase/schemas.d.mts +1 -1
  123. package/dist/services/compression/index.d.mts +2 -2
  124. package/dist/services/compression/namespace.d.mts +1 -1
  125. package/dist/services/compression/schemas.d.mts +1 -1
  126. package/dist/services/context-rules/index.d.mts +1 -1
  127. package/dist/services/execution-target/index.d.mts +3 -3
  128. package/dist/services/execution-target/namespace.d.mts +1 -1
  129. package/dist/services/execution-target/schemas.d.mts +1 -1
  130. package/dist/services/filesystem/index.d.mts +1 -1
  131. package/dist/services/filesystem/namespace.d.mts +6 -6
  132. package/dist/services/filesystem/schemas.d.mts +3 -3
  133. package/dist/services/index.d.mts +43 -43
  134. package/dist/services/index.mjs +1 -1
  135. package/dist/services/log-import/browser.d.mts +2 -2
  136. package/dist/services/log-import/index.d.mts +2 -2
  137. package/dist/services/log-import/log-import.d.mts +1 -1
  138. package/dist/services/materialization/index.d.mts +1 -1
  139. package/dist/services/model-registry/index.d.mts +1 -1
  140. package/dist/services/preferences/index.d.mts +2 -2
  141. package/dist/services/preferences/schemas.d.mts +1 -1
  142. package/dist/services/preferences/storage-namespace.d.mts +2 -2
  143. package/dist/services/provider-context/index.d.mts +1 -1
  144. package/dist/services/session/handlers/index.d.mts +1 -1
  145. package/dist/services/session/index.d.mts +9 -9
  146. package/dist/services/session/messages/namespace.d.mts +1 -1
  147. package/dist/services/session/orchestrator-testing/index.d.mts +1 -1
  148. package/dist/services/session/session-events/namespace.d.mts +1 -1
  149. package/dist/services/session/storage/namespace.d.mts +1 -1
  150. package/dist/services/session/storage/schema.d.mts +1 -1
  151. package/dist/services/session/testing/orchestrator-shared.d.mts +1 -1
  152. package/dist/services/session/turns/namespace.d.mts +1 -1
  153. package/dist/services/session-editor/index.d.mts +1 -1
  154. package/dist/services/settings/index.d.mts +3 -3
  155. package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
  156. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  157. package/dist/services/settings/storage/index.d.mts +3 -3
  158. package/dist/services/settings/storage/providers-namespace.d.mts +1 -1
  159. package/dist/services/subagent/index.d.mts +1 -1
  160. package/dist/services/subagent-template/index.d.mts +2 -2
  161. package/dist/services/subagent-template/namespace.d.mts +1 -1
  162. package/dist/services/subagent-template/schemas.d.mts +1 -1
  163. package/dist/services/tool-approval/index.d.mts +1 -1
  164. package/dist/services/tools/index.d.mts +1 -1
  165. package/dist/services/tray-menu/index.d.mts +3 -3
  166. package/dist/services/tray-menu/namespace.d.mts +1 -1
  167. package/dist/services/tray-menu/schemas.d.mts +1 -1
  168. package/dist/services/turn/index.d.mts +1 -1
  169. package/dist/services/turn/namespace.d.mts +1 -1
  170. package/dist/services/workflow-transitions/index.d.mts +1 -1
  171. package/dist/{src-DEgV239R.mjs → src-BWEtqWTw.mjs} +1 -1
  172. package/dist/storage/drizzle/client.d.mts +1 -1
  173. package/dist/storage/drizzle/index.d.mts +1 -1
  174. package/dist/storage/handlers/drizzle/index.d.mts +1 -1
  175. package/dist/storage/handlers/index.d.mts +1 -1
  176. package/dist/{transition-BB138WkK.d.mts → transition-CGnHfVIv.d.mts} +2 -2
  177. package/dist/{types-p55qvq922.d.mts → types-B6V3HDRl2.d.mts} +1 -1
  178. package/dist/{types-CR23FzmK.d.mts → types-FPmiU-3J.d.mts} +3 -3
  179. package/dist/ui-kernel/index.d.mts +1 -1
  180. package/dist/ui-kernel/pages/schemas.d.mts +1 -1
  181. package/dist/{view-builder-qIGQrZfs.d.mts → view-builder-CELaqM4Z.d.mts} +1 -1
  182. package/dist/{worker-DPTYFyNP.mjs → worker-B4nD_Erm.mjs} +1 -1
  183. package/dist/{workflow-BomH9DBB.mjs → workflow-H8hsEikC.mjs} +1 -1
  184. package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
  185. package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
  186. package/dist/workflow-engine/index.d.mts +29 -29
  187. package/dist/workflow-engine/index.mjs +1 -1
  188. package/dist/workflow-engine/package.d.mts +1 -1
  189. package/dist/workflow-engine/package.mjs +1 -1
  190. package/dist/workflow-engine/provider-operation.d.mts +1 -1
  191. package/dist/workflow-engine/testing/conformance.d.mts +1 -1
  192. package/dist/workflow-engine/testing/conformance.mjs +3 -1
  193. package/dist/workflow-engine/testing/index.d.mts +9 -6
  194. package/dist/workflow-engine/testing/index.mjs +1 -1
  195. package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
  196. package/dist/workflow-engine/testing/sqlite.mjs +68 -60
  197. package/dist/{workflow-worker-BW3CE0YG.mjs → workflow-worker-CmIkKnpF.mjs} +2 -2
  198. package/package.json +1 -1
  199. package/dist/attempt-record-codec-B32Whx75.mjs +0 -1
  200. package/dist/execution-attempt-repository-Djg3qDRv.mjs +0 -1
  201. package/dist/schemas-C3kyQWGf.mjs +0 -1
  202. /package/dist/{adapter-binding-D68U_Hmh.d.mts → adapter-binding-C6jAAjGu.d.mts} +0 -0
  203. /package/dist/{attempt-fixtures-CnrnF5_4.mjs → attempt-fixtures-gGhCA_WQ.mjs} +0 -0
  204. /package/dist/{base-orchestrator-DA95InJU.d.mts → base-orchestrator-B9OUXDR-.d.mts} +0 -0
  205. /package/dist/{capability-service-s4ZYSEWc.d.mts → capability-service-DA9xdAyh.d.mts} +0 -0
  206. /package/dist/{client-f5A-6La5.d.mts → client-BhRxxVig.d.mts} +0 -0
  207. /package/dist/{client-binary-version-verifier-kd9LP9AQ.d.mts → client-binary-version-verifier-DXu9mjRx.d.mts} +0 -0
  208. /package/dist/{clients-namespace-q4PqU1cA.d.mts → clients-namespace-2TIeXofb.d.mts} +0 -0
  209. /package/dist/{config-namespace-Cp71zTT0.d.mts → config-namespace-Burux0cR.d.mts} +0 -0
  210. /package/dist/{create-static-mount-CmQgA0jq.mjs → create-static-mount-CuiFK6nC.mjs} +0 -0
  211. /package/dist/{definition-BHSzhrUf.d.mts → definition-011l3aQ8.d.mts} +0 -0
  212. /package/dist/{extension-context-BmU5XKjI.d.mts → extension-context-CogUIfZb.d.mts} +0 -0
  213. /package/dist/{extension-discovery-DnO7bINK.d.mts → extension-discovery-CuC5Nd5d.d.mts} +0 -0
  214. /package/dist/{filesystem-service-BBArEDPL.d.mts → filesystem-service-DYYL4fLd.d.mts} +0 -0
  215. /package/dist/{index-CDLf3Fka2.d.mts → index-09JDqcgy2.d.mts} +0 -0
  216. /package/dist/{index-xaBSwHxJ.d.mts → index-B4MG7PBn.d.mts} +0 -0
  217. /package/dist/{index-mK-rgiit.d.mts → index-BD1_BSMP.d.mts} +0 -0
  218. /package/dist/{index-C-cnB1Te.d.mts → index-BDAPOKi3.d.mts} +0 -0
  219. /package/dist/{index-DQD2-jcL.d.mts → index-BKco9D6a.d.mts} +0 -0
  220. /package/dist/{index-DSLTgc7h2.d.mts → index-BNF8osK42.d.mts} +0 -0
  221. /package/dist/{index-KAAnSRZt.d.mts → index-BPX7lMRX.d.mts} +0 -0
  222. /package/dist/{index-B-zl-O-Y.d.mts → index-BRNRgfOm.d.mts} +0 -0
  223. /package/dist/{index-CPWBGotQ.d.mts → index-BlkTzRHz.d.mts} +0 -0
  224. /package/dist/{index-CcrXttC02.d.mts → index-C0uHQitR2.d.mts} +0 -0
  225. /package/dist/{index-CrcfeFOo.d.mts → index-C7ZdyYMT.d.mts} +0 -0
  226. /package/dist/{index-C9xVZ-gt.d.mts → index-CDJUiga3.d.mts} +0 -0
  227. /package/dist/{index-D-JbTXIH.d.mts → index-CKeNzHte.d.mts} +0 -0
  228. /package/dist/{index-COOM1j_L2.d.mts → index-CU90gGDk2.d.mts} +0 -0
  229. /package/dist/{index-DYHxzwok2.d.mts → index-CUxMqAoE2.d.mts} +0 -0
  230. /package/dist/{index-Df1c_2PF.d.mts → index-CbaOOgMX.d.mts} +0 -0
  231. /package/dist/{index-DSN2t48K.d.mts → index-CrA9tCMf.d.mts} +0 -0
  232. /package/dist/{index-CkpR5sIH.d.mts → index-CrUijdhZ.d.mts} +0 -0
  233. /package/dist/{index-D_sMzTvv.d.mts → index-CweK7QAS.d.mts} +0 -0
  234. /package/dist/{index-Dn_SGTgp.d.mts → index-DhCBbChV.d.mts} +0 -0
  235. /package/dist/{index-Co1da7YK.d.mts → index-DiHGEgh-.d.mts} +0 -0
  236. /package/dist/{index-DW4SE_sH.d.mts → index-DmjyHIEH.d.mts} +0 -0
  237. /package/dist/{index-D94yE5Dr.d.mts → index-DsIrU-pP.d.mts} +0 -0
  238. /package/dist/{index-BB0HypzC.d.mts → index-DuoOsxow.d.mts} +0 -0
  239. /package/dist/{index-NhW2h2wH2.d.mts → index-Oejq5WGD2.d.mts} +0 -0
  240. /package/dist/{index-CBixkF0n.d.mts → index-XNbcZBEZ.d.mts} +0 -0
  241. /package/dist/{index-D6RMsZko.d.mts → index-fQIrZBY0.d.mts} +0 -0
  242. /package/dist/{index-Bf2MgOni.d.mts → index-ikP83tJm.d.mts} +0 -0
  243. /package/dist/{index-CsFN2nv7.d.mts → index-luD7oSCA.d.mts} +0 -0
  244. /package/dist/{json-value-pX6xnLGw.d.mts → json-value-DbwI1AMR.d.mts} +0 -0
  245. /package/dist/{jsonl-transport-DQIlRX_y.mjs → jsonl-transport-W03tkPvB.mjs} +0 -0
  246. /package/dist/{lib-6eNAiNK7.mjs → lib-Wtk4Ef-T.mjs} +0 -0
  247. /package/dist/{namespace-2qvc6E2Y.d.mts → namespace-B8i86gVL.d.mts} +0 -0
  248. /package/dist/{namespace-CQEYu8az.d.mts → namespace-BGi71aDN.d.mts} +0 -0
  249. /package/dist/{namespace-Cs-cOyrn.d.mts → namespace-BW2rjW9-.d.mts} +0 -0
  250. /package/dist/{namespace-9ychTEk_.d.mts → namespace-Br7IQt88.d.mts} +0 -0
  251. /package/dist/{namespace-BkOvOAU5.d.mts → namespace-Bz3qcZBD.d.mts} +0 -0
  252. /package/dist/{namespace-CirognbA.d.mts → namespace-C3Ch35nb.d.mts} +0 -0
  253. /package/dist/{namespace-BGDq7HmW.d.mts → namespace-C3l4AsWS.d.mts} +0 -0
  254. /package/dist/{namespace-DokogwAZ.d.mts → namespace-C9X7Qvn5.d.mts} +0 -0
  255. /package/dist/{namespace-CVg_cpkh.d.mts → namespace-D4RJjLv8.d.mts} +0 -0
  256. /package/dist/{namespace-CPR2xem0.d.mts → namespace-D5nHBTPz.d.mts} +0 -0
  257. /package/dist/{namespace-DykqxEyX.d.mts → namespace-Df8uPrMr.d.mts} +0 -0
  258. /package/dist/{namespace-DG0hjPcx.d.mts → namespace-aUe_P5qN.d.mts} +0 -0
  259. /package/dist/{orchestrator-shared-BzqqcY2z.d.mts → orchestrator-shared-B2Lb5Enk.d.mts} +0 -0
  260. /package/dist/{packages-Cx-BwSZr.d.mts → packages-uNYWGMH1.d.mts} +0 -0
  261. /package/dist/{provider-operation-B2wQST6N.d.mts → provider-operation-BwvTdAsv.d.mts} +0 -0
  262. /package/dist/{providers-namespace-DsKTnuO1.d.mts → providers-namespace-D-gdpu0p.d.mts} +0 -0
  263. /package/dist/{schema-zSyY22Ck.d.mts → schema-BwrsXKsP.d.mts} +0 -0
  264. /package/dist/{schemas-DuJs6Iqj.d.mts → schemas-B4MSOlcv.d.mts} +0 -0
  265. /package/dist/{schemas-CHRuwe18.d.mts → schemas-BNf-WkKF.d.mts} +0 -0
  266. /package/dist/{schemas-ClGDFa44.d.mts → schemas-BaWB3EXP.d.mts} +0 -0
  267. /package/dist/{schemas-DqnA42bw.d.mts → schemas-Bw2-j1lm.d.mts} +0 -0
  268. /package/dist/{schemas-Dxvjq-Bi.d.mts → schemas-CMQ2PiO2.d.mts} +0 -0
  269. /package/dist/{schemas-DmULJ7Jk.d.mts → schemas-CsOAG1rB.d.mts} +0 -0
  270. /package/dist/{schemas-Bk50UoMA.d.mts → schemas-DKJyKDpe.d.mts} +0 -0
  271. /package/dist/{schemas-CzGN0eqW.d.mts → schemas-Ds_YMFjX.d.mts} +0 -0
  272. /package/dist/{schemas-D0_kfoDf.d.mts → schemas-Io717dOA.d.mts} +0 -0
  273. /package/dist/{schemas--LAbwXvw.d.mts → schemas-v1W9Gj9m.d.mts} +0 -0
  274. /package/dist/{server-lifecycle-WFZcCMwF.d.mts → server-lifecycle-CmuBMs3O.d.mts} +0 -0
  275. /package/dist/{session-lineage-C9kppcCa.d.mts → session-lineage-BRhnTWqq.d.mts} +0 -0
  276. /package/dist/{src-DIyWekjW.mjs → src-BA_c2cXX.mjs} +0 -0
  277. /package/dist/{storage-namespace-BWU-8rvj.d.mts → storage-namespace-CTXxds3h.d.mts} +0 -0
  278. /package/dist/{storage-namespace-definition-B-8JKvzm.d.mts → storage-namespace-definition-Dkxl1FGw.d.mts} +0 -0
  279. /package/dist/{types-8rMNe3AS.d.mts → types--Sa8Ip8j.d.mts} +0 -0
  280. /package/dist/{types-DxHeL0pF.d.mts → types-BWfAz9Sh.d.mts} +0 -0
  281. /package/dist/{types-BnPJa-C_.d.mts → types-BklZfFWo.d.mts} +0 -0
  282. /package/dist/{types-DQTCNM2i.d.mts → types-C4ayzk8k.d.mts} +0 -0
  283. /package/dist/{types-BFeWU3WM.d.mts → types-DDfy8LgJ.d.mts} +0 -0
  284. /package/dist/{window-registry-DQP5P2_0.d.mts → window-registry-CIlKN806.d.mts} +0 -0
@@ -1 +1 @@
1
- import{c as e,d as t,f as n,g as r,h as i,l as a,m as o,n as s,o as c,p as l,s as u,u as d}from"../../execution-attempt-repository-Djg3qDRv.mjs";import{a as f,c as p,d as m,f as h,i as g,l as _,m as v,n as y,o as b,p as x,r as S,s as C,t as w,u as T}from"../../attempt-record-codec-B32Whx75.mjs";import{a as E,c as D,d as O,f as k,i as A,l as j,m as M,n as N,o as P,p as F,r as I,s as L,t as R,u as z}from"../../attempt-fixtures-CnrnF5_4.mjs";import{BoundedRecoveryEvidenceSchema as B}from"@makaio/framework/contracts";function V(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function H(E,D={}){let O=D.attempts??new Map,k=D.operations??new Map,A=e=>k.get(e)?.obligation===`terminal-convergence`,j=D.committedOutcomes??new Map,M=D.activeAttempts??new Map,N=e=>{let n=e.settlementKind!=null,r=!n&&M.get(e.executionId)===e.executionAttemptId;return t({matchesExecution:!0,settled:n,active:r,allocated:r&&e.allocationRef!==null&&!A(e.executionAttemptId)})},P=e=>{let t=O.get(e.executionAttemptId),n=k.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?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}:{kind:`resolved`,attempt:t}},F=(e,t)=>{k.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},I=(e,t)=>{let n=C(e.allocationRef),r=P(e.claim);if(r.kind!==`not-found`&&h(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:o}=r;if(i.allocationRef!==null)return a(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let s=M.get(i.executionId)===i.executionAttemptId;return O.set(i.executionAttemptId,{...i,status:`allocated`,allocationRef:n,claimable:t&&s}),k.set(o.executionAttemptId,{...o,obligation:`allocation-control`}),{kind:`recorded`}};return{async createAttempt(e){let t=_(e.instruction),n=S(e.bootstrapTimeoutMs);if(O.has(e.executionAttemptId))throw new s(e.executionAttemptId);let r={executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:t,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,...n,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...w},i=M.get(e.executionId),a=i===void 0?void 0:O.get(i);return a!==void 0&&O.set(a.executionAttemptId,{...a,claimable:a.status===`allocated`?!1:a.claimable,operationStartGate:`closed`}),O.set(e.executionAttemptId,r),M.set(e.executionId,e.executionAttemptId),r},async readBootstrapStartState(e){let t=O.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:M.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:A(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=b(e.allocationLifetime),n=O.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(M.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.status!==`pending`)return{kind:`already-provisioning`};O.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:f(e.leaseExpiresAt)};return k.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}),{kind:`started`,claim:r}},async getProviderOperation(e){return k.get(e)??null},async renewProviderOperationClaim(e){let t=P(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=f(e.leaseExpiresAt);return k.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=O.get(e.executionAttemptId),n=k.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&g(n.leaseExpiresAt)>g(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:f(e.leaseExpiresAt)};return k.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:B.parse(e.evidence),n=P(e.claim);return n.kind===`authorized`?(k.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=B.parse(e.evidence),n=P(e.claim);return n.kind===`authorized`?(k.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return I(e,!0)},async recordProvisioningAbsent(e){let t=B.parse(e.evidence),n=P(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(O.set(r.executionAttemptId,V(r,`abandoned`)),F(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=B.parse(e.proof.evidence),n=P(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationLifetime===`provisioner-process-bound`?r.provisionerIncarnationId===null||r.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:r.provisionerIncarnationId}:r.allocationRef===null?(O.set(r.executionAttemptId,V(r,`abandoned`)),F(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-process-bound`,allocationLifetime:r.allocationLifetime}:{kind:`not-found`}},async recordAllocationTerminated(e){let t=B.parse(e.evidence),n=P(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(k.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=P(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(O.set(n.executionAttemptId,V(n,`infrastructure-failure`)),F(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async registerRuntime(e){let t=O.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=N(t)??r(t,e);if(n!==null)return n;let i=t.runtimeGeneration+1;return O.set(t.executionAttemptId,{...t,runtimeGeneration:i,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:i}},async admitOperation(e){let t=O.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let r=N(t);if(r!==null)return r;let i=n(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?f(new Date().toISOString()):``,t);if(i!==null)return i;let a=crypto.randomUUID(),o=f(new Date().toISOString());return O.set(t.executionAttemptId,{...t,activeOperationId:a,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:o}),{kind:`admitted`,operationId:a,runtimeGeneration:t.runtimeGeneration,admittedAt:o}},async getInstruction(e){let t=O.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=m(e.result),n=O.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=o({matchesExecution:!0,settled:n.settlementKind!=null,active:M.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!A(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=T([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return O.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(e){let t=O.get(e.executionAttemptId);if(t===void 0)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};let n=l(t,e);return n===null?(O.set(t.executionAttemptId,{...t,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`completed`}):n},async markRuntimeReady(e){let t=f(e.readyAt),n=O.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=N(n)??i(n,e);return r===null?(O.set(n.executionAttemptId,{...n,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):r},async getAttemptControlState(e){let t=O.get(e);return t===void 0?null:x(t)},async getActiveAttempt(e,t){return M.get(e)===t?O.get(t)??null:null},canonicalizeOutcome(t){return e(E,t)},decodeOutcome(e){return u(E,e)},async commitOutcome(e){let t=e.result;if(M.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let n=O.get(e.executionAttemptId);if(n===void 0)return{kind:`fenced`};let r=j.get(e.executionAttemptId);if(r!==void 0){let e=u(E,r);return d(r,t.text)?{kind:`duplicate`,outcome:e,text:r}:{kind:`conflict`}}if(n.settlementKind!=null)return{kind:`conflict`};c(n,e.runtimeFence),j.set(e.executionAttemptId,t.text),O.set(e.executionAttemptId,V(n,`outcome`));let i=k.get(e.executionAttemptId);return i&&F(i,i.lastFailure),{kind:`accepted`,outcome:u(E,t.text),text:t.text}},async abandonPendingAttempt(e,t){if(M.get(t)!==e)return{kind:`fenced`};let n=O.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`}:(O.set(e,V(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:{async getAttemptWithAllocation(e){return O.get(e)??null},async recordDiscoveredAllocation(e){return I(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=p(e),r=P(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`}:a(i.allocationRef,t)?(O.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=g(new Date().toISOString()),n=[];for(let r of O.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&g(r.claimExpiresAt)<t||n.push(v(r)));return n.sort(y)}},attempts:O,operations:k,committedOutcomes:j,activeAttempts:M}}export{w as INITIAL_ATTEMPT_CONTROL_STATE,R as TEST_OWNER_ID,N as TEST_PROVIDER_ID,I as TEST_PROVISIONER_INCARNATION_ID,A as allocateTestAttempt,E as beginTestProvisioning,H as createInMemoryAttemptRepository,P as driveTestAttemptToAllocated,L as leaseAt,D as makeBeginProvisioningInput,j as makeEvidence,z as makeProcessLossProof,O as makeTestAllocationRef,k as makeTestInstruction,F as makeTestWorkflowResult,M as workflowRunResultOutcomeCodec};
1
+ import{_ as e,c as t,d as n,f as r,g as i,h as a,l as o,m as s,n as c,o as l,p as u,s as d,u as f}from"../../execution-attempt-repository-D0cCU7dI.mjs";import{a as p,i as m,n as h,o as g,t as _}from"../../execution-attempt-owner-recovery-BRjtmTGv.mjs";import{a as v,c as y,d as b,f as x,i as S,l as C,n as w,o as T,p as E,r as D,s as O,t as k,u as A}from"../../attempt-record-codec-BcAPEIW3.mjs";import{a as j,c as M,d as N,f as P,i as F,l as I,m as L,n as R,o as z,p as B,r as V,s as H,t as U,u as W}from"../../attempt-fixtures-gGhCA_WQ.mjs";import{BoundedRecoveryEvidenceSchema as G}from"@makaio/framework/contracts";function K(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function q(j,M={}){let N=M.attempts??new Map,P=M.operations??new Map,F=e=>P.get(e)?.obligation===`terminal-convergence`,I=M.committedOutcomes??new Map,L=M.activeAttempts??new Map,R=M.requestBindings??new Map,z=e=>{let t=e.settlementKind!=null,r=!t&&L.get(e.executionId)===e.executionAttemptId;return n({matchesExecution:!0,settled:t,active:r,allocated:r&&e.allocationRef!==null&&!F(e.executionAttemptId)})},B=e=>{let t=N.get(e.executionAttemptId),n=P.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?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}:{kind:`resolved`,attempt:t}},V=(e,t)=>{P.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},H=(e,t)=>{let n=O(e.allocationRef),r=B(e.claim);if(r.kind!==`not-found`&&b(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 o(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let s=L.get(i.executionId)===i.executionAttemptId;return N.set(i.executionAttemptId,{...i,status:`allocated`,allocationRef:n,claimable:t&&s}),P.set(a.executionAttemptId,{...a,obligation:`allocation-control`}),{kind:`recorded`}},U={async getAttemptWithAllocation(e){return N.get(e)??null},async recordDiscoveredAllocation(e){return H(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=y(e),r=B(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`}:o(i.allocationRef,t)?(N.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=S(new Date().toISOString()),n=[];for(let r of N.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&S(r.claimExpiresAt)<t||n.push(E(r)));return n.sort(w)}},W=e=>{let t=D(e.bootstrapTimeoutMs);if(N.has(e.executionAttemptId))throw new c(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,...k},r=L.get(e.executionId),i=r===void 0?void 0:N.get(r);return i!==void 0&&N.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),N.set(e.executionAttemptId,n),L.set(e.executionId,e.executionAttemptId),n};return{async createAttempt(e){return W({...e,instruction:g(e.instruction)})},async ensureAttempt(e){let t=m(e),n=R.get(t.executionId),r=n?.get(t.requestKey);if(r!==void 0)return h(t,N.get(r)??null);let i=W(t),a=n??new Map;return a.set(t.requestKey,i.executionAttemptId),R.set(t.executionId,a),{kind:`created`,attempt:structuredClone(i)}},async readAttemptSettlement(e){let t=p(e);return _(t,{attempt:N.get(t.executionAttemptId)??null,activeAttemptId:L.get(t.executionId)??null,outcomeText:I.get(t.executionAttemptId)??null},j)},async readBootstrapStartState(e){let t=N.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:L.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:F(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=T(e.allocationLifetime),n=N.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(L.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.status!==`pending`)return{kind:`already-provisioning`};N.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:v(e.leaseExpiresAt)};return P.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}),{kind:`started`,claim:r}},async getProviderOperation(e){return P.get(e)??null},async renewProviderOperationClaim(e){let t=B(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=v(e.leaseExpiresAt);return P.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=N.get(e.executionAttemptId),n=P.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&S(n.leaseExpiresAt)>S(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:v(e.leaseExpiresAt)};return P.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:G.parse(e.evidence),n=B(e.claim);return n.kind===`authorized`?(P.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=G.parse(e.evidence),n=B(e.claim);return n.kind===`authorized`?(P.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return H(e,!0)},async recordProvisioningAbsent(e){let t=G.parse(e.evidence),n=B(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(N.set(r.executionAttemptId,K(r,`abandoned`)),V(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=G.parse(e.proof.evidence),n=B(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n,o=a(r,e);return o===null?(N.set(r.executionAttemptId,K(r,`abandoned`)),V(i,t),{kind:`recorded`}):o},async recordAllocationTerminated(e){let t=G.parse(e.evidence),n=B(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(P.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=B(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(N.set(n.executionAttemptId,K(n,`infrastructure-failure`)),V(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async registerRuntime(t){let n=N.get(t.executionAttemptId);if(n===void 0||n.executionId!==t.executionId)return{kind:`not-found`};let r=z(n)??e(n,t);if(r!==null)return r;let i=n.runtimeGeneration+1;return N.set(n.executionAttemptId,{...n,runtimeGeneration:i,runtimeIncarnationId:t.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:i}},async admitOperation(e){let t=N.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=z(t);if(n!==null)return n;let i=r(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?v(new Date().toISOString()):``,t);if(i!==null)return i;let a=crypto.randomUUID(),o=v(new Date().toISOString());return N.set(t.executionAttemptId,{...t,activeOperationId:a,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:o}),{kind:`admitted`,operationId:a,runtimeGeneration:t.runtimeGeneration,admittedAt:o}},async getInstruction(e){let t=N.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=A(e.result),n=N.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=s({matchesExecution:!0,settled:n.settlementKind!=null,active:L.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!F(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=C([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return N.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(e){let t=N.get(e.executionAttemptId);if(t===void 0)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};let n=u(t,e);return n===null?(N.set(t.executionAttemptId,{...t,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`completed`}):n},async markRuntimeReady(e){let t=v(e.readyAt),n=N.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=z(n)??i(n,e);return r===null?(N.set(n.executionAttemptId,{...n,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):r},async getAttemptControlState(e){let t=N.get(e);return t===void 0?null:x(t)},async getActiveAttempt(e,t){return L.get(e)===t?N.get(t)??null:null},canonicalizeOutcome(e){return t(j,e)},decodeOutcome(e){return d(j,e)},async commitOutcome(e){let t=e.result;if(L.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let n=N.get(e.executionAttemptId);if(n===void 0)return{kind:`fenced`};let r=I.get(e.executionAttemptId);if(r!==void 0){let e=d(j,r);return f(r,t.text)?{kind:`duplicate`,outcome:e,text:r}:{kind:`conflict`}}if(n.settlementKind!=null)return{kind:`conflict`};l(n,e.runtimeFence),I.set(e.executionAttemptId,t.text),N.set(e.executionAttemptId,K(n,`outcome`));let i=P.get(e.executionAttemptId);return i&&V(i,i.lastFailure),{kind:`accepted`,outcome:d(j,t.text),text:t.text}},async abandonPendingAttempt(e,t){if(L.get(t)!==e)return{kind:`fenced`};let n=N.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`}:(N.set(e,K(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:U,attempts:N,operations:P,committedOutcomes:I,activeAttempts:L,requestBindings:R}}export{k as INITIAL_ATTEMPT_CONTROL_STATE,U as TEST_OWNER_ID,R as TEST_PROVIDER_ID,V as TEST_PROVISIONER_INCARNATION_ID,F as allocateTestAttempt,j as beginTestProvisioning,q as createInMemoryAttemptRepository,z as driveTestAttemptToAllocated,H as leaseAt,M as makeBeginProvisioningInput,I as makeEvidence,W as makeProcessLossProof,N as makeTestAllocationRef,P as makeTestInstruction,B as makeTestWorkflowResult,L as workflowRunResultOutcomeCodec};
@@ -1,4 +1,4 @@
1
- import { C as ExecutionAttemptRepository, P as OutcomeCodec } from "../../execution-attempt-repository-OryBjQQI.mjs";
1
+ import { C as ExecutionAttemptRepository, P as OutcomeCodec } from "../../execution-attempt-repository-CPk3F98N.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,4 +1,4 @@
1
- import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p as l,r as u,s as d,t as f,u as te}from"../../execution-attempt-repository-Djg3qDRv.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as p}from"../provider-operation.mjs";import{a as m,c as h,d as ne,f as re,i as g,l as _,m as v,o as y,r as ie,s as ae,t as oe,u as b}from"../../attempt-record-codec-B32Whx75.mjs";import{BoundedRecoveryEvidenceSchema as x,ExecutionAttemptOperationKindSchema as S,ProviderAllocationRefSchema as C,WorkerAllocationLifetimeSchema as w}from"@makaio/framework/contracts";import{getRawSqlExecutor as T,isSqliteUniqueViolationError as E,serializeByKey as D,serializeDatabaseOperation as se}from"@makaio/framework/storage/drizzle";import{sql as O}from"drizzle-orm";const ce=[`CREATE TABLE IF NOT EXISTS test_execution_attempt (
1
+ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o as te,p as ne,r as l,s as u,t as d,u as f}from"../../execution-attempt-repository-D0cCU7dI.mjs";import{a as re,i as ie,n as ae,o as p,t as oe}from"../../execution-attempt-owner-recovery-BRjtmTGv.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as m}from"../provider-operation.mjs";import{a as h,c as g,d as se,i as _,l as v,o as y,p as b,r as x,s as ce,t as le,u as ue}from"../../attempt-record-codec-BcAPEIW3.mjs";import{BoundedRecoveryEvidenceSchema as S,ExecutionAttemptOperationKindSchema as C,ProviderAllocationRefSchema as w,WorkerAllocationLifetimeSchema as T}from"@makaio/framework/contracts";import{getRawSqlExecutor as de,isSqliteUniqueViolationError as E,serializeByKey as D,serializeDatabaseOperation as O}from"@makaio/framework/storage/drizzle";import{sql as k}from"drizzle-orm";const A=[`CREATE TABLE IF NOT EXISTS test_execution_attempt (
2
2
  execution_attempt_id TEXT PRIMARY KEY,
3
3
  execution_id TEXT NOT NULL,
4
4
  instruction TEXT NOT NULL,
@@ -28,6 +28,12 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
28
28
  execution_id TEXT PRIMARY KEY,
29
29
  execution_attempt_id TEXT NOT NULL
30
30
  REFERENCES test_execution_attempt(execution_attempt_id)
31
+ )`,`CREATE TABLE IF NOT EXISTS test_execution_attempt_request (
32
+ execution_id TEXT NOT NULL,
33
+ request_key TEXT NOT NULL,
34
+ execution_attempt_id TEXT NOT NULL
35
+ REFERENCES test_execution_attempt(execution_attempt_id),
36
+ PRIMARY KEY (execution_id, request_key)
31
37
  )`,`CREATE TABLE IF NOT EXISTS test_provider_operation (
32
38
  execution_attempt_id TEXT PRIMARY KEY
33
39
  REFERENCES test_execution_attempt(execution_attempt_id),
@@ -38,50 +44,63 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
38
44
  obligation TEXT NOT NULL,
39
45
  failure_count INTEGER NOT NULL DEFAULT 0,
40
46
  last_failure TEXT
41
- )`];function k(e,t,n){let r=e.find(e=>e===t);if(r===void 0)throw Error(`Stored '${n}' value '${t}' is not part of the port's vocabulary`);return r}function A(e,t){return e===null?null:t(JSON.parse(e))}function j(e){return{runtimeGeneration:e.runtime_generation,runtimeIncarnationId:e.runtime_incarnation_id,runtimeReadyAt:e.runtime_ready_at,operationStartGate:k(f,e.operation_start_gate,`operation_start_gate`),activeOperationId:e.active_operation_id,activeOperationKind:e.active_operation_kind===null?null:S.parse(e.active_operation_kind),activeOperationKey:e.active_operation_key,activeOperationGeneration:e.active_operation_generation,activeOperationAdmittedAt:e.active_operation_admitted_at,lastCompletedOperationId:e.last_completed_operation_id}}function M(e){return{...j(e),executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,instruction:_(JSON.parse(e.instruction)),preparationReceipts:b(JSON.parse(e.preparation_receipts)),status:k(a,e.status,`status`),allocationRef:A(e.allocation_ref,e=>C.parse(e)),createdAt:e.created_at,bootstrapDeadlineAt:e.bootstrap_deadline_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:w.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:k(u,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function le(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:k(p,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:A(e.last_failure,e=>x.parse(e))}}const N=new Map,P=new Map;function F(e){if(typeof e!=`object`||!e)return!1;let t=e,n=typeof t.message==`string`?t.message:``;return n.includes(`SQLITE_BUSY`)||n.startsWith(`Failed query: BEGIN IMMEDIATE`)||n.startsWith(`Failed query: COMMIT`)||F(t.cause)}function I(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||I(t.cause)}async function L(){await new Promise(e=>setImmediate(e))}async function R(e){for(let t=0;;t+=1)try{await e.run(O.raw(`COMMIT`));return}catch(e){if(!F(e)||t===100)throw e;await L()}}async function z(e,t){return D(N,e,t)}async function B(e,t){return D(P,e,t)}const V=new WeakMap;async function H(e,t){let n=(await t.all(O.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=V.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return V.set(e,i),i}async function U(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return t;let r=await e();if(typeof r!=`function`)return r;throw Error(`A guarded transition affected no rows while durable state still permitted it`)}function W(e){return O`EXISTS (SELECT 1 FROM test_provider_operation
47
+ )`];function j(e,t,n){let r=e.find(e=>e===t);if(r===void 0)throw Error(`Stored '${n}' value '${t}' is not part of the port's vocabulary`);return r}function M(e,t){return e===null?null:t(JSON.parse(e))}function N(e){return{runtimeGeneration:e.runtime_generation,runtimeIncarnationId:e.runtime_incarnation_id,runtimeReadyAt:e.runtime_ready_at,operationStartGate:j(d,e.operation_start_gate,`operation_start_gate`),activeOperationId:e.active_operation_id,activeOperationKind:e.active_operation_kind===null?null:C.parse(e.active_operation_kind),activeOperationKey:e.active_operation_key,activeOperationGeneration:e.active_operation_generation,activeOperationAdmittedAt:e.active_operation_admitted_at,lastCompletedOperationId:e.last_completed_operation_id}}function P(e){return{...N(e),executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,instruction:p(JSON.parse(e.instruction)),preparationReceipts:v(JSON.parse(e.preparation_receipts)),status:j(o,e.status,`status`),allocationRef:M(e.allocation_ref,e=>w.parse(e)),createdAt:e.created_at,bootstrapDeadlineAt:e.bootstrap_deadline_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:T.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:j(l,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function fe(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:j(m,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:M(e.last_failure,e=>S.parse(e))}}const F=new Map,I=new Map;function L(e){if(typeof e!=`object`||!e)return!1;let t=e,n=typeof t.message==`string`?t.message:``;return n.includes(`SQLITE_BUSY`)||n.startsWith(`Failed query: BEGIN IMMEDIATE`)||n.startsWith(`Failed query: COMMIT`)||L(t.cause)}function R(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||R(t.cause)}async function z(){await new Promise(e=>setImmediate(e))}async function B(e){for(let t=0;;t+=1)try{await e.run(k.raw(`COMMIT`));return}catch(e){if(!L(e)||t===100)throw e;await z()}}async function pe(e,t){return D(F,e,t)}async function me(e,t){return D(I,e,t)}const V=new WeakMap;async function he(e,t){let n=(await t.all(k.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=V.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return V.set(e,i),i}async function H(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return t;let r=await e();if(typeof r!=`function`)return r;throw Error(`A guarded transition affected no rows while durable state still permitted it`)}function U(e){return k`EXISTS (SELECT 1 FROM test_provider_operation
42
48
  WHERE execution_attempt_id = ${e.executionAttemptId}
43
49
  AND generation = ${e.generation}
44
50
  AND owner_id = ${e.ownerId}
45
- AND token = ${e.token})`}function G(e){return O`EXISTS (SELECT 1 FROM test_execution_attempt
46
- WHERE execution_attempt_id = ${e} AND settlement_kind IS NULL)`}function K(e){return O`${W(e)} AND ${G(e.executionAttemptId)}`}function q(e){return O`EXISTS (SELECT 1 FROM test_provider_operation
51
+ AND token = ${e.token})`}function W(e){return k`EXISTS (SELECT 1 FROM test_execution_attempt
52
+ WHERE execution_attempt_id = ${e} AND settlement_kind IS NULL)`}function G(e){return k`${U(e)} AND ${W(e.executionAttemptId)}`}function K(e){return k`EXISTS (SELECT 1 FROM test_provider_operation
47
53
  WHERE execution_attempt_id = ${e}
48
- AND obligation = ${`terminal-convergence`})`}function J(){return O`EXISTS (SELECT 1 FROM test_active_execution_attempt
54
+ AND obligation = ${`terminal-convergence`})`}function q(){return k`EXISTS (SELECT 1 FROM test_active_execution_attempt
49
55
  WHERE execution_id = test_execution_attempt.execution_id
50
- AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function Y(a,u){let S=T(a);await S.run(O.raw(`PRAGMA busy_timeout = 0`));let C=await H(a,S);await z(C,async()=>{for(let e of ce)await S.run(O.raw(e));(await S.all(O.raw(`PRAGMA table_info(test_execution_attempt)`))).some(e=>e.name===`bootstrap_deadline_at`)||await S.run(O.raw(`ALTER TABLE test_execution_attempt ADD COLUMN bootstrap_deadline_at TEXT`))});let w,D=async e=>se(a,()=>B(C,async()=>{if(w!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:w});for(let t=0;;t+=1)try{return await S.withSession(async t=>{let n=!1;try{await t.run(O.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await e(t);return await R(t),r}catch(e){try{await t.run(O.raw(`ROLLBACK`))}catch(t){throw!n&&I(t)?e:(w=AggregateError([e,t],`Transaction rollback failed`),w)}throw e}})}catch(e){if(!F(e)||t===100)throw e;await L()}})),A=async(e,t)=>(await e.all(O`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],N=async(e,t)=>(await e.all(O`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],P=async(e,t)=>(await N(e,t))?.obligation===`terminal-convergence`,V=async(e,t)=>(await e.all(O`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,Y=async(e,n)=>{let r=n.settlement_kind!==null,i=!r&&await V(e,n.execution_id)===n.execution_attempt_id;return t({matchesExecution:!0,settled:r,active:i,allocated:i&&n.allocation_ref!==null&&!await P(e,n.execution_attempt_id)})},X=async(e,t)=>{let n=await A(e,t.executionAttemptId),r=await N(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=M(n);return i.settlementKind==null?r.token===null||r.token!==t.token||r.generation!==t.generation||r.owner_id!==t.ownerId?{kind:`stale`,attempt:i}:{kind:`authorized`,attempt:i,attemptRow:n,operation:r}:{kind:`resolved`,attempt:i}},Z=async(e,t)=>{let n=await X(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},Q=async(e,t,n,r,i)=>{let a=await e.run(O`UPDATE test_execution_attempt
56
+ AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function J(o,l){let C=de(o);await C.run(k.raw(`PRAGMA busy_timeout = 0`));let w=await he(o,C);await pe(w,async()=>{for(let e of A)await C.run(k.raw(e));(await C.all(k.raw(`PRAGMA table_info(test_execution_attempt)`))).some(e=>e.name===`bootstrap_deadline_at`)||await C.run(k.raw(`ALTER TABLE test_execution_attempt ADD COLUMN bootstrap_deadline_at TEXT`))});let T,D=async e=>O(o,()=>me(w,async()=>{if(T!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:T});for(let t=0;;t+=1)try{return await C.withSession(async t=>{let n=!1;try{await t.run(k.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await e(t);return await B(t),r}catch(e){try{await t.run(k.raw(`ROLLBACK`))}catch(t){throw!n&&R(t)?e:(T=AggregateError([e,t],`Transaction rollback failed`),T)}throw e}})}catch(e){if(!L(e)||t===100)throw e;await z()}})),M=async(e,t)=>(await e.all(k`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],F=async(e,t)=>(await e.all(k`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],I=async(e,t)=>(await F(e,t))?.obligation===`terminal-convergence`,V=async(e,t)=>(await e.all(k`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,J=async(e,t)=>{let r=t.settlement_kind!==null,i=!r&&await V(e,t.execution_id)===t.execution_attempt_id;return n({matchesExecution:!0,settled:r,active:i,allocated:i&&t.allocation_ref!==null&&!await I(e,t.execution_attempt_id)})},Y=async(e,t)=>{let n=await M(e,t.executionAttemptId),r=await F(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=P(n);return i.settlementKind==null?r.token===null||r.token!==t.token||r.generation!==t.generation||r.owner_id!==t.ownerId?{kind:`stale`,attempt:i}:{kind:`authorized`,attempt:i,attemptRow:n,operation:r}:{kind:`resolved`,attempt:i}},X=async(e,t)=>{let n=await Y(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},Z=async(e,t,n,r,i)=>{let a=await e.run(k`UPDATE test_execution_attempt
51
57
  SET status = ${`settled`}, settlement_kind = ${n}, claimable = ${0},
52
58
  operation_start_gate = ${`closed`}
53
59
  WHERE execution_attempt_id = ${t}
54
60
  AND settlement_kind IS NULL
55
- AND ${r}`);return a.rowsAffected===0||await e.run(i===void 0?O`UPDATE test_provider_operation
61
+ AND ${r}`);return a.rowsAffected===0||await e.run(i===void 0?k`UPDATE test_provider_operation
56
62
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL
57
- WHERE execution_attempt_id = ${t}`:O`UPDATE test_provider_operation
63
+ WHERE execution_attempt_id = ${t}`:k`UPDATE test_provider_operation
58
64
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL, last_failure = ${JSON.stringify(i)}
59
- WHERE execution_attempt_id = ${t}`),a},$=(e,t)=>{let n=ae(e.allocationRef),r=t?O`CASE WHEN ${J()} THEN 1 ELSE 0 END`:O`${0}`;return D(t=>U(async()=>{let i=await X(t,e.claim);if(i.kind!==`not-found`&&re(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.allocationRef===null?async()=>{let i=await t.run(O`UPDATE test_execution_attempt
65
+ WHERE execution_attempt_id = ${t}`),a},Q=(e,t)=>{let n=ce(e.allocationRef),r=t?k`CASE WHEN ${q()} THEN 1 ELSE 0 END`:k`${0}`;return D(t=>H(async()=>{let i=await Y(t,e.claim);if(i.kind!==`not-found`&&se(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.allocationRef===null?async()=>{let i=await t.run(k`UPDATE test_execution_attempt
60
66
  SET status = ${`allocated`},
61
67
  allocation_ref = ${JSON.stringify(n)},
62
68
  claimable = ${r}
63
69
  WHERE execution_attempt_id = ${a.executionAttemptId}
64
70
  AND allocation_ref IS NULL
65
- AND ${K(e.claim)}`);return i.rowsAffected===0||await t.run(O`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
66
- WHERE execution_attempt_id = ${a.executionAttemptId}`),i}:o(a.allocationRef,n)?{kind:`duplicate`,allocationRef:a.allocationRef}:{kind:`conflict`,allocationRef:a.allocationRef}},{kind:`recorded`}))};return{async createAttempt(e){let t=_(e.instruction),{createdAt:n,bootstrapDeadlineAt:r}=ie(e.bootstrapTimeoutMs);return D(async i=>{try{await i.run(O`INSERT INTO test_execution_attempt
71
+ AND ${G(e.claim)}`);return i.rowsAffected===0||await t.run(k`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
72
+ WHERE execution_attempt_id = ${a.executionAttemptId}`),i}:s(a.allocationRef,n)?{kind:`duplicate`,allocationRef:a.allocationRef}:{kind:`conflict`,allocationRef:a.allocationRef}},{kind:`recorded`}))},ge={async getAttemptWithAllocation(e){return D(async t=>{let n=await M(t,e);return n===void 0?null:P(n)})},async recordDiscoveredAllocation(e){return Q(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=g(e);return D(r=>H(async()=>{let i=await Y(r,e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a,attemptRow:o}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:s(a.allocationRef,t)?()=>r.run(k`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
73
+ WHERE execution_attempt_id = ${a.executionAttemptId}
74
+ AND execution_id = ${e.executionId}
75
+ AND allocation_ref = ${o.allocation_ref}
76
+ AND ${G(e.claim)}`):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return D(async t=>{let n=new Date().toISOString();return(await t.all(k`SELECT * FROM test_execution_attempt
77
+ WHERE execution_id = ${e}
78
+ AND status = ${`allocated`}
79
+ AND settlement_kind IS NULL
80
+ AND allocation_ref IS NOT NULL
81
+ AND claimable = ${1}
82
+ AND (claim_expires_at IS NULL OR claim_expires_at >= ${n})
83
+ ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>b(P(e)))})}},$=async(e,t,n)=>{let{instruction:r}=t,{createdAt:i,bootstrapDeadlineAt:a}=n;try{await e.run(k`INSERT INTO test_execution_attempt
67
84
  (execution_attempt_id, execution_id, instruction, status, claimable, created_at, bootstrap_deadline_at)
68
- VALUES (${e.executionAttemptId}, ${e.executionId}, ${JSON.stringify(t)}, ${`pending`}, ${0}, ${n}, ${r})`)}catch(t){throw E(t)?new c(e.executionAttemptId,{cause:t}):t}return await i.run(O`UPDATE test_execution_attempt
85
+ VALUES (${t.executionAttemptId}, ${t.executionId}, ${JSON.stringify(r)}, ${`pending`}, ${0}, ${i}, ${a})`)}catch(e){throw E(e)?new ee(t.executionAttemptId,{cause:e}):e}return await e.run(k`UPDATE test_execution_attempt
69
86
  SET claimable = ${0}
70
87
  WHERE execution_attempt_id = (
71
88
  SELECT execution_attempt_id
72
89
  FROM test_active_execution_attempt
73
- WHERE execution_id = ${e.executionId}
90
+ WHERE execution_id = ${t.executionId}
74
91
  )
75
- AND status = ${`allocated`}`),await i.run(O`UPDATE test_execution_attempt
92
+ AND status = ${`allocated`}`),await e.run(k`UPDATE test_execution_attempt
76
93
  SET operation_start_gate = ${`closed`}
77
94
  WHERE execution_attempt_id = (
78
95
  SELECT execution_attempt_id
79
96
  FROM test_active_execution_attempt
80
- WHERE execution_id = ${e.executionId}
81
- )`),await i.run(O`INSERT INTO test_active_execution_attempt (execution_id, execution_attempt_id)
82
- VALUES (${e.executionId}, ${e.executionAttemptId})
97
+ WHERE execution_id = ${t.executionId}
98
+ )`),await e.run(k`INSERT INTO test_active_execution_attempt (execution_id, execution_attempt_id)
99
+ VALUES (${t.executionId}, ${t.executionAttemptId})
83
100
  ON CONFLICT(execution_id)
84
- DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{...oe,executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:t,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,createdAt:n,bootstrapDeadlineAt:r,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}})},async readBootstrapStartState(e){return D(async t=>{let n=await A(t,e.executionAttemptId);return n===void 0||n.execution_id!==e.executionId?null:{settled:n.settlement_kind!==null,active:await V(t,e.executionId)===e.executionAttemptId,allocated:n.allocation_ref!==null,allocationTerminated:await P(t,e.executionAttemptId),operationStartGate:k(f,n.operation_start_gate,`operation_start_gate`),bootstrapDeadlineAt:n.bootstrap_deadline_at}})},async beginProvisioning(e){let t=y(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:m(e.leaseExpiresAt)};return D(r=>U(async()=>{let i=await A(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=M(i);return await V(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.status===`pending`?async()=>{let i=await r.run(O`UPDATE test_execution_attempt
101
+ DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{...le,executionAttemptId:t.executionAttemptId,executionId:t.executionId,instruction:r,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,createdAt:i,bootstrapDeadlineAt:a,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}};return{async createAttempt(e){let t={...e,instruction:p(e.instruction)},n=x(e.bootstrapTimeoutMs);return D(e=>$(e,t,n))},async ensureAttempt(e){let t=ie(e);return D(async e=>{let n=(await e.all(k`SELECT execution_attempt_id FROM test_execution_attempt_request
102
+ WHERE execution_id = ${t.executionId} AND request_key = ${t.requestKey}`))[0];if(n!==void 0){let r=await M(e,n.execution_attempt_id);return ae(t,r===void 0?null:P(r))}let r=await $(e,t,x(t.bootstrapTimeoutMs));return await e.run(k`INSERT INTO test_execution_attempt_request (execution_id, request_key, execution_attempt_id)
103
+ VALUES (${t.executionId}, ${t.requestKey}, ${r.executionAttemptId})`),{kind:`created`,attempt:structuredClone(r)}})},async readAttemptSettlement(e){let t=re(e);return D(async e=>{let n=await M(e,t.executionAttemptId);return n===void 0||n.execution_id!==t.executionId?{kind:`not-found`}:oe(t,{attempt:P(n),activeAttemptId:await V(e,t.executionId),outcomeText:n.workflow_result},l)})},async readBootstrapStartState(e){return D(async t=>{let n=await M(t,e.executionAttemptId);return n===void 0||n.execution_id!==e.executionId?null:{settled:n.settlement_kind!==null,active:await V(t,e.executionId)===e.executionAttemptId,allocated:n.allocation_ref!==null,allocationTerminated:await I(t,e.executionAttemptId),operationStartGate:j(d,n.operation_start_gate,`operation_start_gate`),bootstrapDeadlineAt:n.bootstrap_deadline_at}})},async beginProvisioning(e){let t=y(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:h(e.leaseExpiresAt)};return D(r=>H(async()=>{let i=await M(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=P(i);return await V(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.status===`pending`?async()=>{let i=await r.run(k`UPDATE test_execution_attempt
85
104
  SET status = ${`provisioning`},
86
105
  provider_id = ${e.providerId},
87
106
  allocation_lifetime = ${t},
@@ -91,63 +110,63 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
91
110
  AND status = ${`pending`}
92
111
  AND allocation_ref IS NULL
93
112
  AND settlement_kind IS NULL
94
- AND ${J()}`);return i.rowsAffected===0||await r.run(O`INSERT INTO test_provider_operation
113
+ AND ${q()}`);return i.rowsAffected===0||await r.run(k`INSERT INTO test_provider_operation
95
114
  (execution_attempt_id, generation, owner_id, token, lease_expires_at, obligation, failure_count)
96
115
  VALUES (${e.executionAttemptId}, ${n.generation}, ${n.ownerId}, ${n.token},
97
- ${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return D(async t=>{let n=await N(t,e);return n===void 0?null:le(n)})},async renewProviderOperationClaim(e){let t=m(e.leaseExpiresAt);return D(n=>U(async()=>await Z(n,e.claim)??(()=>n.run(O`UPDATE test_provider_operation SET lease_expires_at = ${t}
116
+ ${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return D(async t=>{let n=await F(t,e);return n===void 0?null:fe(n)})},async renewProviderOperationClaim(e){let t=h(e.leaseExpiresAt);return D(n=>H(async()=>await X(n,e.claim)??(()=>n.run(k`UPDATE test_provider_operation SET lease_expires_at = ${t}
98
117
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
99
- AND ${K(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return D(async t=>{let n=await A(t,e.executionAttemptId),r=await N(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};if(r.owner_id!==null&&r.lease_expires_at!==null&&g(r.lease_expires_at)>g(e.observedAt))return{kind:`stale`};let i={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:m(e.leaseExpiresAt)},{rowsAffected:a}=await t.run(O`UPDATE test_provider_operation
118
+ AND ${G(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return D(async t=>{let n=await M(t,e.executionAttemptId),r=await F(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};if(r.owner_id!==null&&r.lease_expires_at!==null&&_(r.lease_expires_at)>_(e.observedAt))return{kind:`stale`};let i={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:h(e.leaseExpiresAt)},{rowsAffected:a}=await t.run(k`UPDATE test_provider_operation
100
119
  SET generation = ${i.generation}, owner_id = ${i.ownerId}, token = ${i.token},
101
120
  lease_expires_at = ${i.leaseExpiresAt}
102
121
  WHERE execution_attempt_id = ${e.executionAttemptId}
103
122
  AND generation = ${r.generation}
104
- AND ${G(e.executionAttemptId)}`);return a===0?{kind:`stale`}:{kind:`claimed`,claim:i}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:x.parse(e.evidence);return D(n=>U(async()=>await Z(n,e.claim)??(()=>n.run(t===null?O`UPDATE test_provider_operation
123
+ AND ${W(e.executionAttemptId)}`);return a===0?{kind:`stale`}:{kind:`claimed`,claim:i}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:S.parse(e.evidence);return D(n=>H(async()=>await X(n,e.claim)??(()=>n.run(t===null?k`UPDATE test_provider_operation
105
124
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL
106
125
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
107
- AND ${K(e.claim)}`:O`UPDATE test_provider_operation
126
+ AND ${G(e.claim)}`:k`UPDATE test_provider_operation
108
127
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL,
109
128
  last_failure = ${JSON.stringify(t)}
110
129
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
111
- AND ${K(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=x.parse(e.evidence);return D(n=>U(async()=>await Z(n,e.claim)??(()=>n.run(O`UPDATE test_provider_operation
130
+ AND ${G(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=S.parse(e.evidence);return D(n=>H(async()=>await X(n,e.claim)??(()=>n.run(k`UPDATE test_provider_operation
112
131
  SET failure_count = failure_count + 1, last_failure = ${JSON.stringify(t)}
113
132
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
114
- AND ${K(e.claim)}`)),{kind:`recorded`}))},async recordAllocation(e){return $(e,!0)},async recordProvisioningAbsent(e){let t=x.parse(e.evidence);return D(n=>U(async()=>{let r=await X(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?()=>Q(n,i.executionAttemptId,`abandoned`,O`execution_id = ${e.executionId}
133
+ AND ${G(e.claim)}`)),{kind:`recorded`}))},async recordAllocation(e){return Q(e,!0)},async recordProvisioningAbsent(e){let t=S.parse(e.evidence);return D(n=>H(async()=>{let r=await Y(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?()=>Z(n,i.executionAttemptId,`abandoned`,k`execution_id = ${e.executionId}
115
134
  AND allocation_ref IS NULL
116
- AND ${W(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-found`}},{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=x.parse(e.proof.evidence);return D(n=>U(async()=>{let r=await X(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationLifetime===`provisioner-process-bound`?i.provisionerIncarnationId===null||i.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:i.provisionerIncarnationId}:i.allocationRef===null?()=>Q(n,i.executionAttemptId,`abandoned`,O`execution_id = ${e.executionId}
135
+ AND ${U(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-found`}},{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=S.parse(e.proof.evidence);return D(n=>H(async()=>{let r=await Y(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r,o=a(i,e);return o===null?()=>Z(n,i.executionAttemptId,`abandoned`,k`execution_id = ${e.executionId}
117
136
  AND allocation_ref IS NULL
118
137
  AND allocation_lifetime = ${`provisioner-process-bound`}
119
138
  AND provisioner_incarnation_id = ${e.proof.provisionerIncarnationId}
120
- AND ${W(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-process-bound`,allocationLifetime:i.allocationLifetime}:{kind:`not-found`}},{kind:`recorded`}))},async recordAllocationTerminated(e){let t=x.parse(e.evidence);return D(n=>U(async()=>{let r=await X(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(O`UPDATE test_provider_operation
139
+ AND ${U(e.claim)}`,t):o},{kind:`recorded`}))},async recordAllocationTerminated(e){let t=S.parse(e.evidence);return D(n=>H(async()=>{let r=await Y(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(k`UPDATE test_provider_operation
121
140
  SET obligation = ${`terminal-convergence`}, last_failure = ${JSON.stringify(t)}
122
141
  WHERE execution_attempt_id = ${i.executionAttemptId}
123
- AND ${K(e.claim)}
142
+ AND ${G(e.claim)}
124
143
  AND EXISTS (SELECT 1 FROM test_execution_attempt
125
144
  WHERE execution_attempt_id = ${i.executionAttemptId}
126
- AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return D(t=>U(async()=>{let n=await X(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?{kind:`not-allocated`}:k(p,i.obligation,`obligation`)===`terminal-convergence`?()=>Q(t,r.executionAttemptId,`infrastructure-failure`,O`execution_id = ${e.executionId}
145
+ AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return D(t=>H(async()=>{let n=await Y(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?{kind:`not-allocated`}:j(m,i.obligation,`obligation`)===`terminal-convergence`?()=>Z(t,r.executionAttemptId,`infrastructure-failure`,k`execution_id = ${e.executionId}
127
146
  AND allocation_ref IS NOT NULL
128
- AND ${q(r.executionAttemptId)}
129
- AND ${W(e.claim)}`):{kind:`not-terminated`}:{kind:`not-found`}},{kind:`recorded`}))},async registerRuntime(e){return D(async t=>{let n=0,i=await U(async()=>{let i=await A(t,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=await Y(t,i);if(a!==null)return a;let o=j(i),s=r(o,e);return s===null?(n=o.runtimeGeneration+1,()=>t.run(O`UPDATE test_execution_attempt
130
- SET runtime_generation = ${n},
131
- runtime_incarnation_id = ${e.runtimeIncarnationId},
147
+ AND ${K(r.executionAttemptId)}
148
+ AND ${U(e.claim)}`):{kind:`not-terminated`}:{kind:`not-found`}},{kind:`recorded`}))},async registerRuntime(t){return D(async n=>{let r=0,i=await H(async()=>{let i=await M(n,t.executionAttemptId);if(i===void 0||i.execution_id!==t.executionId)return{kind:`not-found`};let a=await J(n,i);if(a!==null)return a;let o=N(i),s=e(o,t);return s===null?(r=o.runtimeGeneration+1,()=>n.run(k`UPDATE test_execution_attempt
149
+ SET runtime_generation = ${r},
150
+ runtime_incarnation_id = ${t.runtimeIncarnationId},
132
151
  runtime_ready_at = NULL,
133
152
  active_operation_id = NULL,
134
153
  active_operation_kind = NULL,
135
154
  active_operation_key = NULL,
136
155
  active_operation_generation = NULL,
137
156
  active_operation_admitted_at = NULL
138
- WHERE execution_attempt_id = ${e.executionAttemptId}
139
- AND execution_id = ${e.executionId}
157
+ WHERE execution_attempt_id = ${t.executionAttemptId}
158
+ AND execution_id = ${t.executionId}
140
159
  AND runtime_generation = ${o.runtimeGeneration}
141
160
  AND settlement_kind IS NULL
142
161
  AND (active_operation_id IS NULL OR active_operation_kind = ${`runtime-probe`})
143
162
  AND allocation_ref IS NOT NULL
144
- AND NOT ${q(e.executionAttemptId)}
145
- AND ${J()}`)):s},{kind:`applied`});return i.kind===`applied`?{kind:`registered`,runtimeGeneration:n}:i})},async admitOperation(e){let t=crypto.randomUUID(),r=m(new Date().toISOString()),i=e.operationKind===`runtime-probe`?O`1 = 1`:O`runtime_ready_at IS NOT NULL`;return D(a=>U(async()=>{let o=await A(a,e.executionAttemptId);if(o===void 0||o.execution_id!==e.executionId)return{kind:`not-found`};let s=await Y(a,o);if(s!==null)return s;let c=n(j(o),e,r,M(o));return c===null?()=>a.run(O`UPDATE test_execution_attempt
163
+ AND NOT ${K(t.executionAttemptId)}
164
+ AND ${q()}`)):s},{kind:`applied`});return i.kind===`applied`?{kind:`registered`,runtimeGeneration:r}:i})},async admitOperation(e){let t=crypto.randomUUID(),n=h(new Date().toISOString()),i=e.operationKind===`runtime-probe`?k`1 = 1`:k`runtime_ready_at IS NOT NULL`;return D(a=>H(async()=>{let o=await M(a,e.executionAttemptId);if(o===void 0||o.execution_id!==e.executionId)return{kind:`not-found`};let s=await J(a,o);if(s!==null)return s;let c=r(N(o),e,n,P(o));return c===null?()=>a.run(k`UPDATE test_execution_attempt
146
165
  SET active_operation_id = ${t},
147
166
  active_operation_kind = ${e.operationKind},
148
167
  active_operation_key = ${e.admissionKey},
149
168
  active_operation_generation = ${e.runtimeGeneration},
150
- active_operation_admitted_at = ${r}
169
+ active_operation_admitted_at = ${n}
151
170
  WHERE execution_attempt_id = ${e.executionAttemptId}
152
171
  AND execution_id = ${e.executionId}
153
172
  AND active_operation_id IS NULL
@@ -157,9 +176,9 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
157
176
  AND preparation_receipts = ${o.preparation_receipts}
158
177
  AND settlement_kind IS NULL
159
178
  AND allocation_ref IS NOT NULL
160
- AND NOT ${q(e.executionAttemptId)}
179
+ AND NOT ${K(e.executionAttemptId)}
161
180
  AND ${i}
162
- AND ${J()}`):c},{kind:`admitted`,operationId:t,runtimeGeneration:e.runtimeGeneration,admittedAt:r}))},async getInstruction(e){return D(async t=>{let n=await A(t,e.executionAttemptId);return n?.execution_id===e.executionId?_(JSON.parse(n.instruction)):null})},async reportOperation(e){let t=ne(e.result);return D(n=>U(async()=>{let r=await A(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let i=M(r),a=s({matchesExecution:!0,settled:r.settlement_kind!==null,active:await V(n,e.executionId)===e.executionAttemptId,allocated:r.allocation_ref!==null&&!await P(n,e.executionAttemptId)},i,i,{...e,result:t});if(a!==null)return a;let o=b([...i.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return()=>n.run(O`UPDATE test_execution_attempt
181
+ AND ${q()}`):c},{kind:`admitted`,operationId:t,runtimeGeneration:e.runtimeGeneration,admittedAt:n}))},async getInstruction(e){return D(async t=>{let n=await M(t,e.executionAttemptId);return n?.execution_id===e.executionId?p(JSON.parse(n.instruction)):null})},async reportOperation(e){let t=ue(e.result);return D(n=>H(async()=>{let r=await M(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let i=P(r),a=c({matchesExecution:!0,settled:r.settlement_kind!==null,active:await V(n,e.executionId)===e.executionAttemptId,allocated:r.allocation_ref!==null&&!await I(n,e.executionAttemptId)},i,i,{...e,result:t});if(a!==null)return a;let o=v([...i.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return()=>n.run(k`UPDATE test_execution_attempt
163
182
  SET preparation_receipts = ${JSON.stringify(o)},
164
183
  active_operation_id = NULL,
165
184
  active_operation_kind = NULL,
@@ -177,8 +196,8 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
177
196
  AND instruction = ${r.instruction}
178
197
  AND preparation_receipts = ${r.preparation_receipts}
179
198
  AND allocation_ref IS NOT NULL
180
- AND NOT ${q(e.executionAttemptId)}
181
- AND ${J()}`)},{kind:`accepted`,binding:t.binding}))},async completeOperation(e){return D(t=>U(async()=>{let n=await A(t,e.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};let r=l(j(n),e);return r===null?()=>t.run(O`UPDATE test_execution_attempt
199
+ AND NOT ${K(e.executionAttemptId)}
200
+ AND ${q()}`)},{kind:`accepted`,binding:t.binding}))},async completeOperation(e){return D(t=>H(async()=>{let n=await M(t,e.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};let r=ne(N(n),e);return r===null?()=>t.run(k`UPDATE test_execution_attempt
182
201
  SET active_operation_id = NULL,
183
202
  active_operation_kind = NULL,
184
203
  active_operation_key = NULL,
@@ -189,7 +208,7 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
189
208
  AND settlement_kind IS NULL
190
209
  AND active_operation_id = ${e.operationId}
191
210
  AND active_operation_kind IN (${`runtime-probe`}, ${`workflow-run`})
192
- AND active_operation_generation = ${e.runtimeGeneration}`):r},{kind:`completed`}))},async markRuntimeReady(e){let t=m(e.readyAt);return D(n=>U(async()=>{let r=await A(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let a=await Y(n,r);if(a!==null)return a;let o=i(j(r),e);return o===null?()=>n.run(O`UPDATE test_execution_attempt SET runtime_ready_at = ${t}
211
+ AND active_operation_generation = ${e.runtimeGeneration}`):r},{kind:`completed`}))},async markRuntimeReady(e){let t=h(e.readyAt);return D(n=>H(async()=>{let r=await M(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let a=await J(n,r);if(a!==null)return a;let o=i(N(r),e);return o===null?()=>n.run(k`UPDATE test_execution_attempt SET runtime_ready_at = ${t}
193
212
  WHERE execution_attempt_id = ${e.executionAttemptId}
194
213
  AND execution_id = ${e.executionId}
195
214
  AND settlement_kind IS NULL
@@ -197,31 +216,20 @@ import{c as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,n as c,o as ee,p
197
216
  AND runtime_ready_at IS NULL
198
217
  AND active_operation_id IS NULL
199
218
  AND allocation_ref IS NOT NULL
200
- AND NOT ${q(e.executionAttemptId)}
201
- AND ${J()}`):o},{kind:`ready`,acceptedAt:t}))},async getAttemptControlState(e){return D(async t=>{let n=await A(t,e);return n===void 0?null:j(n)})},async getActiveAttempt(e,t){return D(async n=>{if(await V(n,e)!==t)return null;let r=await A(n,t);return r===void 0?null:M(r)})},canonicalizeOutcome(t){return e(u,t)},decodeOutcome(e){return d(u,e)},async commitOutcome(e){let t=e.result,n=e.runtimeFence,r=n===void 0?O`1 = 1`:O`
219
+ AND NOT ${K(e.executionAttemptId)}
220
+ AND ${q()}`):o},{kind:`ready`,acceptedAt:t}))},async getAttemptControlState(e){return D(async t=>{let n=await M(t,e);return n===void 0?null:N(n)})},async getActiveAttempt(e,t){return D(async n=>{if(await V(n,e)!==t)return null;let r=await M(n,t);return r===void 0?null:P(r)})},canonicalizeOutcome(e){return t(l,e)},decodeOutcome(e){return u(l,e)},async commitOutcome(e){let t=e.result,n=e.runtimeFence,r=n===void 0?k`1 = 1`:k`
202
221
  runtime_generation = ${n.runtimeGeneration}
203
- AND ${n.operationId===null?O`active_operation_id IS NULL`:O`active_operation_id = ${n.operationId}
204
- AND active_operation_generation = ${n.runtimeGeneration}`}`;return D(i=>U(async()=>{if(await V(i,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let a=await A(i,e.executionAttemptId);if(a===void 0)return{kind:`fenced`};let o=a.workflow_result;if(o!==null){let e=d(u,o);return te(o,t.text)?{kind:`duplicate`,outcome:e,text:o}:{kind:`conflict`}}return a.settlement_kind===null?(n!==void 0&&ee(j(a),n),async()=>{let n=await i.run(O`UPDATE test_execution_attempt SET workflow_result = ${t.text}
222
+ AND ${n.operationId===null?k`active_operation_id IS NULL`:k`active_operation_id = ${n.operationId}
223
+ AND active_operation_generation = ${n.runtimeGeneration}`}`;return D(i=>H(async()=>{if(await V(i,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let a=await M(i,e.executionAttemptId);if(a===void 0)return{kind:`fenced`};let o=a.workflow_result;if(o!==null){let e=u(l,o);return f(o,t.text)?{kind:`duplicate`,outcome:e,text:o}:{kind:`conflict`}}return a.settlement_kind===null?(n!==void 0&&te(N(a),n),async()=>{let n=await i.run(k`UPDATE test_execution_attempt SET workflow_result = ${t.text}
205
224
  WHERE execution_attempt_id = ${e.executionAttemptId}
206
225
  AND workflow_result IS NULL
207
226
  AND settlement_kind IS NULL
208
227
  AND ${r}
209
- AND ${J()}`);return n.rowsAffected===0?n:Q(i,e.executionAttemptId,`outcome`,O`workflow_result IS NOT NULL`)}):{kind:`conflict`}},{kind:`accepted`,outcome:d(u,t.text),text:t.text}))},async abandonPendingAttempt(e,t){return D(n=>U(async()=>{if(await V(n,t)!==e)return{kind:`fenced`};let r=await A(n,e);if(r===void 0)return{kind:`fenced`};let i=M(r);return i.status===`allocated`?{kind:`allocated`}:i.status===`provisioning`?{kind:`provisioning`}:i.status===`settled`?{kind:i.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:()=>n.run(O`UPDATE test_execution_attempt
228
+ AND ${q()}`);return n.rowsAffected===0?n:Z(i,e.executionAttemptId,`outcome`,k`workflow_result IS NOT NULL`)}):{kind:`conflict`}},{kind:`accepted`,outcome:u(l,t.text),text:t.text}))},async abandonPendingAttempt(e,t){return D(n=>H(async()=>{if(await V(n,t)!==e)return{kind:`fenced`};let r=await M(n,e);if(r===void 0)return{kind:`fenced`};let i=P(r);return i.status===`allocated`?{kind:`allocated`}:i.status===`provisioning`?{kind:`provisioning`}:i.status===`settled`?{kind:i.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:()=>n.run(k`UPDATE test_execution_attempt
210
229
  SET status = ${`settled`}, settlement_kind = ${`abandoned`}, claimable = ${0},
211
230
  operation_start_gate = ${`closed`}
212
231
  WHERE execution_attempt_id = ${e}
213
232
  AND execution_id = ${t}
214
233
  AND status = ${`pending`}
215
234
  AND settlement_kind IS NULL
216
- AND ${J()}`)},{kind:`abandoned`}))},recovery:{async getAttemptWithAllocation(e){return D(async t=>{let n=await A(t,e);return n===void 0?null:M(n)})},async recordDiscoveredAllocation(e){return $(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=h(e);return D(r=>U(async()=>{let i=await X(r,e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a,attemptRow:s}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:o(a.allocationRef,t)?()=>r.run(O`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
217
- WHERE execution_attempt_id = ${a.executionAttemptId}
218
- AND execution_id = ${e.executionId}
219
- AND allocation_ref = ${s.allocation_ref}
220
- AND ${K(e.claim)}`):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return D(async t=>{let n=new Date().toISOString();return(await t.all(O`SELECT * FROM test_execution_attempt
221
- WHERE execution_id = ${e}
222
- AND status = ${`allocated`}
223
- AND settlement_kind IS NULL
224
- AND allocation_ref IS NOT NULL
225
- AND claimable = ${1}
226
- AND (claim_expires_at IS NULL OR claim_expires_at >= ${n})
227
- ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>v(M(e)))})}}}}export{Y as createSqliteAttemptRepository};
235
+ AND ${q()}`)},{kind:`abandoned`}))},recovery:ge}}export{J as createSqliteAttemptRepository};
@@ -1,2 +1,2 @@
1
- import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-aYrZuS4W.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-DrvofWwi.mjs";import{mintOrRotateWorkflowExecutionBusSecret as l}from"./runtime-node/workflow-execution-bus-access.mjs";import{execFile as u,spawn as d}from"node:child_process";import*as f from"node:fs/promises";import{access as p}from"node:fs/promises";import*as m from"node:path";import{basename as ee,isAbsolute as te,join as ne,relative as re}from"node:path";import*as h from"node:crypto";import{randomUUID as g}from"node:crypto";import{constants as ie}from"node:fs";import{BusAbortError as ae,createBusInstance as _,isRequestCancellation as oe,waitForSubscriptionPropagation as se}from"@makaio/framework/bus";import{AdapterSubjects as ce,BoundedRecoveryEvidenceSchema as le,ExecutionAttemptSchemas as v,ExecutionAttemptSubjects as y,FrameworkContractNamespaces as ue,FrameworkStorageNamespaces as b,JsonValueSchema as de,PROVIDER_ALLOCATION_REF_VERSION as fe,ProviderAllocationRefSchema as pe,RECOVERY_EVIDENCE_LIMITS as x,WorkerCapabilitiesSchema as me,WorkerSchemas as he,WorkerSubjects as S,WorkflowRunContextSchema as ge,WorkflowRunResultSchema as _e,WorkflowWorkerConfigSchema as ve,createWorkflowCancelSubject as ye}from"@makaio/framework/contracts";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{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 C,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 w,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 T,runAuthorityDispatchedAttempt as Ze,toCommittedWorkflowRunnerResult 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 E(e){return e.on(ce.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 D(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(w)})),{adapterSubsystemPackage:s}}function O(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=E(t);return{cleanup:()=>{r.cleanup(),i()}}}function k(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=tt(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"`)&&nt(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function A(e){try{return await import(e)}catch(t){if(k(t,e))return null;throw t}}function tt(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 nt(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function j(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`?m.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(m.delimiter)){let n=t.replace(/^"|"$/gu,``),r=m.resolve(n||process.cwd());for(let t of a){let n=m.join(r,`${e}${t}`);try{return await p(n,ie.X_OK),n}catch{}}}}async function M(e,t=5e3,n=1e3){let{stdout:r}=await We(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function rt(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function it(e,t=j,n=M){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:rt(i)}}catch{return{binary:e,found:!1}}}async function at(e,t=j,n=M){return Promise.all(e.map(e=>it(e,t,n)))}var ot=class extends we{constructor(e){super(e)}onInit(){this.registerHandler(Oe.scan,async e=>{let t=await at(e.payload.binaries);e.setResult({results:t})})}};const N={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[De],create:e=>new ot(e.bus)};function P(e,t){e.push(...st(t))}function st(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function ct(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 lt(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function F(e){return Se(Ce(dt(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function ut(e,n){let r=F(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function dt(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function I(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function ft(e,t){let n=I(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function L(e){return ft(e,`sessionOrchestrator`),I(e,`sessionOrchestrator`).length===0}function pt(e){return e===!0||L(e)?C:C.filter(e=>e.name!==ke.name)}function R(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&P(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 mt(){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 z=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()}},B=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function V(e,t,n){let r=m.resolve(t)+m.sep,i=m.resolve(e);if(i!==m.resolve(t)&&!i.startsWith(r))throw new B(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function H(e,t,n,r){let i=r??await f.realpath(t),a;try{a=await f.realpath(e)}catch{return e}let o=i+m.sep;if(a!==i&&!a.startsWith(o))throw new B(`${n} escapes allowed root via symlink: real path ${a} is not within ${i}`,`symlink-escape`);return a}function U(e){let t=e.indexOf(`-`);if(t===-1)throw new B(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function ht(e,t){let n=await f.readFile(e);return h.createHash(t).update(n).digest(`base64`)}const W=new Set([`.git`,`node_modules`]);function gt(e){return W.has(e.toLowerCase())}async function _t(e,t){let n=t.toLowerCase();if(!W.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([f.lstat(m.join(e,t)),f.lstat(m.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const vt=W,yt=new Set([`.DS_Store`]);async function G(e,t){let n=h.createHash(t),r=[];async function i(t){let n=await f.readdir(t,{withFileTypes:!0});for(let a of n){let n=m.join(t,a.name);if(a.isSymbolicLink())throw new B(`Contribution package contains a symbolic link: ${m.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){vt.has(a.name)||await i(n);continue}if(a.isFile()){yt.has(a.name)||r.push(m.relative(e,n));continue}throw new B(`Contribution package contains an unsupported filesystem entry: ${m.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(m.sep).join(`/`)),n.update(`\0`),n.update(await f.readFile(m.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function K(e,t=`sha256`){let n=h.createHash(t),r=[];async function i(t){let n=await f.readdir(t,{withFileTypes:!0});for(let a of n){let n=m.join(t,a.name);if(!await _t(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(m.relative(e,n));continue}throw a.isSymbolicLink()?new B(`Workspace root contains a symbolic link: ${m.relative(e,n)}`,`symlink-escape`):new B(`Workspace root contains an unsupported filesystem entry: ${m.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 f.readFile(m.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function bt(e,t,n){let r=m.join(t,`node_modules`,e.packageName);V(r,t,`Contribution package directory`),await H(r,t,`Contribution package directory`,n);let i=m.join(r,`package.json`),a;try{a=await f.readFile(i,`utf-8`)}catch{throw new B(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let o=JSON.parse(a);if(o.name!==e.packageName)throw new B(`Contribution identity mismatch: expected ${e.packageName}, found ${o.name??`<none>`}`,`contribution-missing`);if(o.version!==e.version)throw new B(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${o.version??`<none>`}`,`contribution-version-mismatch`);let s=m.join(r,e.entrypoint);V(s,r,`Contribution entrypoint`),await H(s,t,`Contribution entrypoint`,n);try{await f.access(s)}catch{throw new B(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:c}=U(e.integrity),l;try{l=await G(r,c)}catch(t){if(t instanceof B)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 B(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(l!==e.integrity)throw new B(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${l}`,`contribution-integrity-mismatch`);return s}async function xt(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new B(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await f.stat(r)).isDirectory())throw new B(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof B?e:new B(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await f.realpath(r),a=m.resolve(r,e.sourcePath);if(V(a,r,`Source path`),m.relative(r,a).split(m.sep).some(gt))throw new B(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await H(a,r,`Source path`,i);let o=await K(r);if(o!==e.rootDigest)throw new B(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${o}`,`digest-mismatch`);try{await f.access(a)}catch{throw new B(`Workflow source file not found: ${a}`,`source-missing`)}return{workspaceRoot:r,sourcePath:a,contributionEntrypoints:await Promise.all(t.map(e=>bt(e,r,i))),platform:process.platform,arch:process.arch}}var St=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new z(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 z(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 xt(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 Ct(e){return e.mode===`source`?ne(e.moduleDir,`workflow-worker`,`worker-entry.ts`):ne(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var wt=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:g(),revision:`1`,config:e,...c==null?{}:{runContext:c},preservation:{required:[]}});return{state:`authority-committed`,result:Qe(await Ze({authority:this.options.authority,executionId:e.executionId,instruction:l,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)}}},Tt=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let r=ve.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 Et(){return{contributionRefs:[]}}function Dt(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=ee(e.runtimeModuleDir)===`src`?`source`:`dist`,r=Ot({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 Ot(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 Tt({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(S.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 wt({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 St({workerEntry:t.workerEntry??Ct({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??Et(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const kt=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`}},At=class extends Error{reason;constructor(e=`deadline-exceeded`){super(`Authority request delivery deadline exceeded`),this.reason=e,this.name=`AuthorityRequestDeliveryError`}};function jt(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 Mt(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 Nt(e,t,n,r){let i=jt(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 Mt(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 Pt(e,t){return await Nt(e,()=>new At,t,()=>!1)}async function Ft(e,t,n){return await Nt(async n=>{let r=await e(n);if(kt.has(r))return r;throw t(r)},()=>t(`deadline-exceeded`,`deadline-exceeded`),n,e=>e instanceof q||e instanceof J)}async function It(e,t,n){return await Ft(async n=>(await e.request(S.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 Lt(e,t,n){return await Ft(async n=>(await e.request(y.outcome.submit,t,{timeout:n})).decision,(e,n)=>n===void 0?new J(e,t):new J(e,t,n),n)}const Rt={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},zt={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]};function Bt(e){let t=new Set,n;return{conclude:r=>{if(n!==void 0)return;n={evidence:le.parse({source:e.slice(0,x.source),summary:r.slice(0,x.summary),observedAt:new Date().toISOString()})};let i=[...t];t.clear();for(let e of i)try{e(n)}catch(e){console.error(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion observer failed:`,e)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}var Vt=class{executionAttemptId;controller;detachCallerAbort;infrastructure;revokeBusIdentity;constructor(e,t,n,r,i){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r,this.revokeBusIdentity=i}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(),this.revokeBusIdentity(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}},Ht=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=me.parse({...zt,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??zt.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=new AbortController,r=Bt(this.id),i=()=>{n.abort(t.reason)};t.addEventListener(`abort`,i,{once:!0});let a=()=>t.removeEventListener(`abort`,i),o;try{let{executionAttemptId:i,executionId:s,workerConfig:c}=e;if(!c.busUrl)throw Error(`PiscinaThinWorkflowProvider requires a bus URL to provision an execution attempt (executionAttemptId=${i}, executionId=${s})`);let u=this.buildAllocationRef(i),d=l({executionAttemptId:i,executionId:s});o=d.cleanup;let f=new Vt(i,n,a,r,d.cleanup);t.throwIfAborted();let p=this.options.runner.runWithReadiness({...c,busAuth:{kind:`hmac`,secret:d.secret}},n.signal,e.workerManifest,{executionAttemptId:i,bootstrapDeadlineAt:e.bootstrapDeadlineAt});return p.ready.then(()=>this.submitOutcomeOnSettlement(p.result,s,i,c.workflowId,r.conclude),e=>{n.abort(e),p.result.catch(()=>void 0),r.conclude(`Piscina worker for attempt '${i}' was refused before its workflow run was admitted: `+(e instanceof Error?e.message:String(e)))}),{kind:`allocated`,allocationRef:u,handle:f}}catch(e){throw n.abort(e),a(),o?.(),e}}async submitOutcomeOnSettlement(e,t,n,r,i){let a;try{a=await e}catch(e){a={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...Rt,...this.options.outcomeRetry};await It(this.options.bus,{executionAttemptId:n,executionId:t,result:a},{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`)}}buildAllocationRef(e){let t={version:fe,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return pe.parse(t)}};const Ut=[Le,Pe,Ie];function Wt(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 Gt(e,t,n){return O({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(w)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(w)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(w)?.getLiveAdapterIdentities()??[]})}async function Kt(e){let t=_();t.registerNamespaces([...ue,...b]);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:A}}),i,a=[()=>t.disconnect()],o=Wt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=D({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=[...Ut,c,je,...L(s)?[Fe]:[],Me(1),Re,N,l,...Ue(s)];r.load(u),a.push(...R(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=Gt(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 Y(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function qt(e,t){try{process.kill(-e,0)}catch(e){if(e.code===`ESRCH`)return!1;throw e}let n;try{n=await Jt(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 Jt(e){return new Promise((t,n)=>{u(`ps`,[`-A`,`-o`,`pgid=,stat=`],{timeout:e,maxBuffer:1024*1024},(e,r)=>{if(e!==null){n(e);return}t(r)})})}async function Yt(e){if(e===void 0)return!0;try{Y(e,`SIGKILL`);let t=Date.now()+2e3;for(;Date.now()<t;){let n=t-Date.now();if(n<=0)break;if(!await qt(e,Math.min(1e3,n)))return!0;await et(20)}}catch{}return!1}async function Xt(e){if(e.signal?.aborted)return{status:`cancelled`,exitCode:null};if(process.platform===`win32`)return{status:`spawn-failed`,exitCode:null,message:`Setup process groups require a POSIX host`};try{return await Zt(e)}catch{return{status:`spawn-failed`,exitCode:null,message:`Could not start the setup command`}}}function Zt(e){return new Promise(t=>{let n=d(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{Y(n.pid,`SIGTERM`),i=setTimeout(()=>{try{n.pid!==void 0&&Y(n.pid,`SIGKILL`)}catch{r=`stop-failed`}},200)}catch{r=`stop-failed`}},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),Yt(n.pid).then(e=>{t({status:e?r??(a===0?`completed`:`failed`):`stop-failed`,exitCode:a})})})})}async function Qt(e,t,n){if(m.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=m.join(r,i),V(r,e,`Source root`),await H(r,e,`Source root`,e),n&&await f.mkdir(r).catch(e=>{if(e.code!==`EEXIST`)throw e}),!(await f.stat(r)).isDirectory())throw Error(`Source root must be a directory`);return H(r,e,`Source root`,e)}async function $t(e){let{requirement:t}=e,n=m.resolve(e.workspaceRoot);if(!m.isAbsolute(e.workspaceRoot)||n===m.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))throw Error(`Source acquisition is not implemented`);if(t.provisioning===`create`&&await f.mkdir(n),!(await f.lstat(n)).isDirectory())throw Error(`Workspace root must be a directory, not a symlink`);let r=await f.realpath(n),i=[];for(let e of t.sourceRoots)i.push({id:e.id,path:await Qt(r,e.path,t.provisioning===`create`)});return en(t,{workspaceRoot:r,sourceRoots:i})}function en(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 Xt({...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():f.rm(n,{recursive:!0,force:!0}),o)}}}async function tn(e,t,n,r){let i=v[`instruction.get`].response.parse(await e.request(y.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 nn(e,t,n,r){let{executionAttemptId:i,runtimeGeneration:a}=t,o=v[`operation.admit`].response.parse(await Pt(async t=>await e.request(y.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 X(e){return(e instanceof Error?e.message:String(e)).slice(0,8192)||`Local execution failed without a diagnostic message`}function rn(e,t){return e.find(e=>e.kind===t.workload.kind&&e.version===t.workload.version)}function an(e){return{signal:e??new AbortController().signal,release:()=>{}}}function Z(e,t){return e instanceof ae?oe(e,t):t?.aborted===!0&&(e===t.reason||e instanceof DOMException&&e.name===`AbortError`)}async function Q(e,t,n,r,i,a){let o=await Lt(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 on(e,t,n,r){let i=v[`operation.report`].response.parse(await Pt(async i=>await e.request(y.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 sn(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 cn(e,t,n,r){if(r.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,void 0);let i=await nn(e,t,`workspace-preparation`,`workspace-preparation:${n.id}:${t.runtimeGeneration}`);if(r.aborted)return await Q(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:$t}).prepare({requirement:n.workspace,workspaceRoot:t.workspaceRoot});a=e,o=await e.runSetup({signal:r,env:t.setupEnv})}catch(o){return await Q(e,t,n,Z(o,r)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:X(o)},i,a)}let s=sn(o);if(s!==void 0)return await Q(e,t,n,s,i,a);if(r.aborted)return await Q(e,t,n,{kind:`cancelled`},i,a);let c=await on(e,t,i,a);return c===void 0?await Q(e,t,n,{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace preparation report refused by the Authority`},i,a):r.aborted?await Q(e,t,n,{kind:`cancelled`},void 0,a):{handle:a,binding:c}}async function ln(e,t,n,r,i){if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,void 0);let a,o;if(n.workspace!==void 0){let r=await cn(e,t,n,i.signal);if(`outcome`in r)return r;a=r.handle,o=r.binding}if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,a);let s=await nn(e,t,`workload-invocation`,`workload-invocation:${n.id}:${t.runtimeGeneration}`);if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},s,a);let c;try{c={kind:`workload-result`,result:de.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:X(e)}}return await Q(e,t,n,c,s,a)}async function $(e,t){let n;try{n=await tn(e,t.executionAttemptId,t.runtimeGeneration,t.signal)}catch(n){if(oe(n,t.signal))return await Q(e,t,void 0,{kind:`cancelled`},void 0,void 0);throw n}let r=rn(t.adapters,n);if(r===void 0)return await Q(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})??an(t.signal))}catch(r){let i=Z(r,t.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`startup`,message:X(r)};return await Q(e,t,n,i,void 0,void 0)}try{return await ln(e,t,n,r,i)}finally{try{i.release()}catch{console.warn(`[makaio-worker] Workload control release failed.`)}}}async function un(e,t,n,r,i){let a=he[`runtime.inputs.get`].response.parse(await e.request(S.runtime.inputs.get,{executionAttemptId:t},{signal:i}));if(a.runtimeInputs===null)throw Error(`Selected Worker Runtime inputs are unavailable`);return ge.parse({...n,...a.runtimeInputs,createdAt:0,env:r})}function dn(e,t){let n=(e,t)=>{let n=re(e,t);return n===``||!te(n)&&n!==`..`&&!n.startsWith(`../`)&&!n.startsWith(`..\\`)};return n(e,t)||n(t,e)}async function fn(t,n,r,i){let a=await t.loadContributions(r,i);i.throwIfAborted();let o=e();return await Kt({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 pn(e,t,n){let r={...e.workflowEnv},i,a=!0;return{adapter:{kind:qe,version:Je,async bindControl({instruction:t,signal:r}){let i=T(t);if(i.executionId!==e.executionId)throw Error(`Workflow instruction execution identity mismatch`);let a=new AbortController,o=n.on(ye(i.cancelSubject),()=>a.abort());try{return await se(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=T(o);a=o.preservation.required.length!==0;let u=c??new AbortController().signal,d;try{u.throwIfAborted();let a=await un(n,e.executionAttemptId,l,r,u),o=await e.materialize(a,u);(s===void 0||!dn(o.context.workspaceRoot,s.workspaceRoot))&&(i=o.cleanup);let c=mn(o.context,s);return u.throwIfAborted(),d=await fn(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 mn(e,t){return t===void 0?e:{...e,workspaceRoot:t.workspaceRoot}}async function hn(e,t){if(!(t.outcome.kind!==`workload-result`||e.onPostCommit===void 0))try{let n=_e.parse(t.outcome.result);await e.onPostCommit(n,t.decision)}catch{}}async function gn(e,t){t.throwIfAborted();let n={...e.workflowEnv},i=g(),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:()=>_n(e,a)}),u=s.bus,d=pn({...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 $(u,{executionAttemptId:e.executionAttemptId,runtimeGeneration:n,workspaceRoot:e.workspaceRoot,setupEnv:e.setupEnv,adapters:[d.adapter],signal:t,retry:e.outcomeRetry,reconnect:()=>u.reconnect()}),await hn(e,f),f}finally{try{await d.releaseExecutable(f)}finally{l.cleanup(),await s.close()}}}function _n(e,t){let n=_();return n.registerNamespaces([...ue,...b]),{bus:n,async connect(r){try{await e.connectBus(n,t,r),r.throwIfAborted()}catch(e){throw n.disconnect(),e}},close:()=>n.disconnect()}}export{R as A,xt as C,P as D,ct as E,k as F,A as I,O as L,ut as M,pt as N,lt as O,N as P,D as R,ht as S,bt as T,B as _,J as a,G as b,q as c,Ot as d,Dt as f,St as g,Ct as h,Ht as i,F as j,mt as k,Lt as l,wt as m,$ as n,At as o,Tt as p,Kt as r,kt as s,gn as t,It as u,V as v,U as w,K as x,H as y,E as z};
1
+ import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-aYrZuS4W.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-DrvofWwi.mjs";import{mintOrRotateWorkflowExecutionBusSecret as l}from"./runtime-node/workflow-execution-bus-access.mjs";import{execFile as u,spawn as d}from"node:child_process";import*as f from"node:fs/promises";import{access as p}from"node:fs/promises";import*as m from"node:path";import{basename as ee,isAbsolute as te,join as ne,relative as re}from"node:path";import*as h from"node:crypto";import{randomUUID as g}from"node:crypto";import{constants as ie}from"node:fs";import{BusAbortError as ae,createBusInstance as _,isRequestCancellation as oe,waitForSubscriptionPropagation as se}from"@makaio/framework/bus";import{AdapterSubjects as ce,BoundedRecoveryEvidenceSchema as le,ExecutionAttemptSchemas as v,ExecutionAttemptSubjects as y,FrameworkContractNamespaces as ue,FrameworkStorageNamespaces as b,JsonValueSchema as de,PROVIDER_ALLOCATION_REF_VERSION as fe,ProviderAllocationRefSchema as pe,RECOVERY_EVIDENCE_LIMITS as x,WorkerCapabilitiesSchema as me,WorkerSchemas as he,WorkerSubjects as S,WorkflowRunContextSchema as ge,WorkflowRunResultSchema as _e,WorkflowWorkerConfigSchema as ve,createWorkflowCancelSubject as ye}from"@makaio/framework/contracts";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{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 C,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 w,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 T,runAuthorityDispatchedAttempt as Ze,toCommittedWorkflowRunnerResult 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 E(e){return e.on(ce.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 D(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(w)})),{adapterSubsystemPackage:s}}function O(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=E(t);return{cleanup:()=>{r.cleanup(),i()}}}function k(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=tt(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"`)&&nt(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function A(e){try{return await import(e)}catch(t){if(k(t,e))return null;throw t}}function tt(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 nt(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function j(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`?m.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(m.delimiter)){let n=t.replace(/^"|"$/gu,``),r=m.resolve(n||process.cwd());for(let t of a){let n=m.join(r,`${e}${t}`);try{return await p(n,ie.X_OK),n}catch{}}}}async function M(e,t=5e3,n=1e3){let{stdout:r}=await We(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function rt(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function it(e,t=j,n=M){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:rt(i)}}catch{return{binary:e,found:!1}}}async function at(e,t=j,n=M){return Promise.all(e.map(e=>it(e,t,n)))}var ot=class extends we{constructor(e){super(e)}onInit(){this.registerHandler(Oe.scan,async e=>{let t=await at(e.payload.binaries);e.setResult({results:t})})}};const N={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[De],create:e=>new ot(e.bus)};function P(e,t){e.push(...st(t))}function st(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function ct(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 lt(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function F(e){return Se(Ce(dt(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function ut(e,n){let r=F(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function dt(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function I(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function ft(e,t){let n=I(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function L(e){return ft(e,`sessionOrchestrator`),I(e,`sessionOrchestrator`).length===0}function pt(e){return e===!0||L(e)?C:C.filter(e=>e.name!==ke.name)}function R(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&P(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 mt(){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 z=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()}},B=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function V(e,t,n){let r=m.resolve(t)+m.sep,i=m.resolve(e);if(i!==m.resolve(t)&&!i.startsWith(r))throw new B(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function H(e,t,n,r){let i=r??await f.realpath(t),a;try{a=await f.realpath(e)}catch{return e}let o=i+m.sep;if(a!==i&&!a.startsWith(o))throw new B(`${n} escapes allowed root via symlink: real path ${a} is not within ${i}`,`symlink-escape`);return a}function U(e){let t=e.indexOf(`-`);if(t===-1)throw new B(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function ht(e,t){let n=await f.readFile(e);return h.createHash(t).update(n).digest(`base64`)}const W=new Set([`.git`,`node_modules`]);function gt(e){return W.has(e.toLowerCase())}async function _t(e,t){let n=t.toLowerCase();if(!W.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([f.lstat(m.join(e,t)),f.lstat(m.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const vt=W,yt=new Set([`.DS_Store`]);async function G(e,t){let n=h.createHash(t),r=[];async function i(t){let n=await f.readdir(t,{withFileTypes:!0});for(let a of n){let n=m.join(t,a.name);if(a.isSymbolicLink())throw new B(`Contribution package contains a symbolic link: ${m.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){vt.has(a.name)||await i(n);continue}if(a.isFile()){yt.has(a.name)||r.push(m.relative(e,n));continue}throw new B(`Contribution package contains an unsupported filesystem entry: ${m.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(m.sep).join(`/`)),n.update(`\0`),n.update(await f.readFile(m.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function K(e,t=`sha256`){let n=h.createHash(t),r=[];async function i(t){let n=await f.readdir(t,{withFileTypes:!0});for(let a of n){let n=m.join(t,a.name);if(!await _t(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(m.relative(e,n));continue}throw a.isSymbolicLink()?new B(`Workspace root contains a symbolic link: ${m.relative(e,n)}`,`symlink-escape`):new B(`Workspace root contains an unsupported filesystem entry: ${m.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 f.readFile(m.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function bt(e,t,n){let r=m.join(t,`node_modules`,e.packageName);V(r,t,`Contribution package directory`),await H(r,t,`Contribution package directory`,n);let i=m.join(r,`package.json`),a;try{a=await f.readFile(i,`utf-8`)}catch{throw new B(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let o=JSON.parse(a);if(o.name!==e.packageName)throw new B(`Contribution identity mismatch: expected ${e.packageName}, found ${o.name??`<none>`}`,`contribution-missing`);if(o.version!==e.version)throw new B(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${o.version??`<none>`}`,`contribution-version-mismatch`);let s=m.join(r,e.entrypoint);V(s,r,`Contribution entrypoint`),await H(s,t,`Contribution entrypoint`,n);try{await f.access(s)}catch{throw new B(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:c}=U(e.integrity),l;try{l=await G(r,c)}catch(t){if(t instanceof B)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 B(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(l!==e.integrity)throw new B(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${l}`,`contribution-integrity-mismatch`);return s}async function xt(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new B(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await f.stat(r)).isDirectory())throw new B(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof B?e:new B(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await f.realpath(r),a=m.resolve(r,e.sourcePath);if(V(a,r,`Source path`),m.relative(r,a).split(m.sep).some(gt))throw new B(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await H(a,r,`Source path`,i);let o=await K(r);if(o!==e.rootDigest)throw new B(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${o}`,`digest-mismatch`);try{await f.access(a)}catch{throw new B(`Workflow source file not found: ${a}`,`source-missing`)}return{workspaceRoot:r,sourcePath:a,contributionEntrypoints:await Promise.all(t.map(e=>bt(e,r,i))),platform:process.platform,arch:process.arch}}var St=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new z(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 z(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 xt(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 Ct(e){return e.mode===`source`?ne(e.moduleDir,`workflow-worker`,`worker-entry.ts`):ne(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var wt=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:g(),revision:`1`,config:e,...c==null?{}:{runContext:c},preservation:{required:[]}});return{state:`authority-committed`,result:Qe(await Ze({authority:this.options.authority,executionId:e.executionId,instruction:l,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)}}},Tt=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let r=ve.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 Et(){return{contributionRefs:[]}}function Dt(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=ee(e.runtimeModuleDir)===`src`?`source`:`dist`,r=Ot({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 Ot(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 Tt({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(S.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 wt({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 St({workerEntry:t.workerEntry??Ct({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??Et(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const kt=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`}},At=class extends Error{reason;constructor(e=`deadline-exceeded`){super(`Authority request delivery deadline exceeded`),this.reason=e,this.name=`AuthorityRequestDeliveryError`}};function jt(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 Mt(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 Nt(e,t,n,r){let i=jt(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 Mt(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 Pt(e,t){return await Nt(e,()=>new At,t,()=>!1)}async function Ft(e,t,n){return await Nt(async n=>{let r=await e(n);if(kt.has(r))return r;throw t(r)},()=>t(`deadline-exceeded`,`deadline-exceeded`),n,e=>e instanceof q||e instanceof J)}async function It(e,t,n){return await Ft(async n=>(await e.request(S.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 Lt(e,t,n){return await Ft(async n=>(await e.request(y.outcome.submit,t,{timeout:n})).decision,(e,n)=>n===void 0?new J(e,t):new J(e,t,n),n)}const Rt={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},zt={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]};function Bt(e){let t=new Set,n;return{conclude:r=>{if(n!==void 0)return;n={evidence:le.parse({source:e.slice(0,x.source),summary:r.slice(0,x.summary),observedAt:new Date().toISOString()})};let i=[...t];t.clear();for(let e of i)try{e(n)}catch(e){console.error(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion observer failed:`,e)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}var Vt=class{executionAttemptId;controller;detachCallerAbort;infrastructure;revokeBusIdentity;constructor(e,t,n,r,i){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r,this.revokeBusIdentity=i}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(),this.revokeBusIdentity(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}},Ht=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=me.parse({...zt,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??zt.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=new AbortController,r=Bt(this.id),i=()=>{n.abort(t.reason)};t.addEventListener(`abort`,i,{once:!0});let a=()=>t.removeEventListener(`abort`,i),o;try{let{executionAttemptId:i,executionId:s,workerConfig:c}=e;if(!c.busUrl)throw Error(`PiscinaThinWorkflowProvider requires a bus URL to provision an execution attempt (executionAttemptId=${i}, executionId=${s})`);let u=this.buildAllocationRef(i),d=l({executionAttemptId:i,executionId:s});o=d.cleanup;let f=new Vt(i,n,a,r,d.cleanup);t.throwIfAborted();let p=this.options.runner.runWithReadiness({...c,busAuth:{kind:`hmac`,secret:d.secret}},n.signal,e.workerManifest,{executionAttemptId:i,bootstrapDeadlineAt:e.bootstrapDeadlineAt});return p.ready.then(()=>this.submitOutcomeOnSettlement(p.result,s,i,c.workflowId,r.conclude),e=>{n.abort(e),p.result.catch(()=>void 0),r.conclude(`Piscina worker for attempt '${i}' was refused before its workflow run was admitted: `+(e instanceof Error?e.message:String(e)))}),{kind:`allocated`,allocationRef:u,handle:f}}catch(e){throw n.abort(e),a(),o?.(),e}}async submitOutcomeOnSettlement(e,t,n,r,i){let a;try{a=await e}catch(e){a={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...Rt,...this.options.outcomeRetry};await It(this.options.bus,{executionAttemptId:n,executionId:t,result:a},{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`)}}buildAllocationRef(e){let t={version:fe,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return pe.parse(t)}};const Ut=[Le,Pe,Ie];function Wt(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 Gt(e,t,n){return O({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(w)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(w)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(w)?.getLiveAdapterIdentities()??[]})}async function Kt(e){let t=_();t.registerNamespaces([...ue,...b]);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:A}}),i,a=[()=>t.disconnect()],o=Wt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=D({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=[...Ut,c,je,...L(s)?[Fe]:[],Me(1),Re,N,l,...Ue(s)];r.load(u),a.push(...R(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=Gt(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 qt(e){return Number.isInteger(e)&&e>=1&&e<=2147483647}function Y(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function Jt(e,t){try{process.kill(-e,0)}catch(e){if(e.code===`ESRCH`)return!1;throw e}let n;try{n=await Yt(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 Yt(e){return new Promise((t,n)=>{u(`ps`,[`-A`,`-o`,`pgid=,stat=`],{timeout:e,maxBuffer:1024*1024},(e,r)=>{if(e!==null){n(e);return}t(r)})})}async function Xt(e){if(e===void 0)return!0;try{Y(e,`SIGKILL`);let t=Date.now()+2e3;for(;Date.now()<t;){let n=t-Date.now();if(n<=0)break;if(!await Jt(e,Math.min(1e3,n)))return!0;await et(20)}}catch{}return!1}async function Zt(e){if(e.signal?.aborted)return{status:`cancelled`,exitCode:null};if(!qt(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 Qt(e)}catch{return{status:`spawn-failed`,exitCode:null,message:`Could not start the setup command`}}}function Qt(e){return new Promise(t=>{let n=d(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{Y(n.pid,`SIGTERM`),i=setTimeout(()=>{try{n.pid!==void 0&&Y(n.pid,`SIGKILL`)}catch{r=`stop-failed`}},200)}catch{r=`stop-failed`}},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),Xt(n.pid).then(e=>{t({status:e?r??(a===0?`completed`:`failed`):`stop-failed`,exitCode:a})})})})}async function $t(e,t,n){if(m.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=m.join(r,i),V(r,e,`Source root`),await H(r,e,`Source root`,e),n&&await f.mkdir(r).catch(e=>{if(e.code!==`EEXIST`)throw e}),!(await f.stat(r)).isDirectory())throw Error(`Source root must be a directory`);return H(r,e,`Source root`,e)}async function en(e){e.signal?.throwIfAborted();let{requirement:t}=e,n=m.resolve(e.workspaceRoot);if(!m.isAbsolute(e.workspaceRoot)||n===m.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 f.mkdir(n),!(await f.lstat(n)).isDirectory())throw Error(`Workspace root must be a directory, not a symlink`);let r=await f.realpath(n),i=[];for(let n of t.sourceRoots){let a=await $t(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 tn(t,{workspaceRoot:r,sourceRoots:i})}function tn(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 Zt({...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():f.rm(n,{recursive:!0,force:!0}),o)}}}function X(e,t){return e instanceof ae?oe(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 nn(e,t,n,r){let i=v[`instruction.get`].response.parse(await e.request(y.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 rn(e,t,n,r){let{executionAttemptId:i,runtimeGeneration:a}=t,o=v[`operation.admit`].response.parse(await Pt(async t=>await e.request(y.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 Z(e){return(e instanceof Error?e.message:String(e)).slice(0,8192)||`Local execution failed without a diagnostic message`}function an(e,t){return e.find(e=>e.kind===t.workload.kind&&e.version===t.workload.version)}function on(e){return{signal:e??new AbortController().signal,release:()=>{}}}async function Q(e,t,n,r,i,a){let o=await Lt(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 sn(e,t,n,r){let i=v[`operation.report`].response.parse(await Pt(async i=>await e.request(y.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 cn(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 ln(e,t,n,r){if(r.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,void 0);let i=await rn(e,t,`workspace-preparation`,`workspace-preparation:${n.id}:${t.runtimeGeneration}`);if(r.aborted)return await Q(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:en}).prepare({requirement:n.workspace,workspaceRoot:t.workspaceRoot,signal:r});a=e,o=await e.runSetup({signal:r,env:t.setupEnv})}catch(o){return await Q(e,t,n,X(o,r)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:Z(o)},i,a)}let s=cn(o);if(s!==void 0)return await Q(e,t,n,s,i,a);if(r.aborted)return await Q(e,t,n,{kind:`cancelled`},i,a);let c=await sn(e,t,i,a);return c===void 0?await Q(e,t,n,{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace preparation report refused by the Authority`},i,a):r.aborted?await Q(e,t,n,{kind:`cancelled`},void 0,a):{handle:a,binding:c}}async function un(e,t,n,r,i){if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,void 0);let a,o;if(n.workspace!==void 0){let r=await ln(e,t,n,i.signal);if(`outcome`in r)return r;a=r.handle,o=r.binding}if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},void 0,a);let s=await rn(e,t,`workload-invocation`,`workload-invocation:${n.id}:${t.runtimeGeneration}`);if(i.signal.aborted)return await Q(e,t,n,{kind:`cancelled`},s,a);let c;try{c={kind:`workload-result`,result:de.parse(await r.invoke({instruction:n,...o===void 0?{}:{workspace:o},signal:i.signal}))}}catch(e){c=X(e,i.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workload-invocation`,message:Z(e)}}return await Q(e,t,n,c,s,a)}async function $(e,t){let n;try{n=await nn(e,t.executionAttemptId,t.runtimeGeneration,t.signal)}catch(n){if(oe(n,t.signal))return await Q(e,t,void 0,{kind:`cancelled`},void 0,void 0);throw n}let r=an(t.adapters,n);if(r===void 0)return await Q(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})??on(t.signal))}catch(r){let i=X(r,t.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`startup`,message:Z(r)};return await Q(e,t,n,i,void 0,void 0)}try{return await un(e,t,n,r,i)}finally{try{i.release()}catch{console.warn(`[makaio-worker] Workload control release failed.`)}}}async function dn(e,t,n,r,i){let a=he[`runtime.inputs.get`].response.parse(await e.request(S.runtime.inputs.get,{executionAttemptId:t},{signal:i}));if(a.runtimeInputs===null)throw Error(`Selected Worker Runtime inputs are unavailable`);return ge.parse({...n,...a.runtimeInputs,createdAt:0,env:r})}function fn(e,t){let n=(e,t)=>{let n=re(e,t);return n===``||!te(n)&&n!==`..`&&!n.startsWith(`../`)&&!n.startsWith(`..\\`)};return n(e,t)||n(t,e)}async function pn(t,n,r,i){let a=await t.loadContributions(r,i);i.throwIfAborted();let o=e();return await Kt({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 mn(e,t,n){let r={...e.workflowEnv},i,a=!0;return{adapter:{kind:qe,version:Je,async bindControl({instruction:t,signal:r}){let i=T(t);if(i.executionId!==e.executionId)throw Error(`Workflow instruction execution identity mismatch`);let a=new AbortController,o=n.on(ye(i.cancelSubject),()=>a.abort());try{return await se(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=T(o);a=o.preservation.required.length!==0;let u=c??new AbortController().signal,d;try{u.throwIfAborted();let a=await dn(n,e.executionAttemptId,l,r,u),o=await e.materialize(a,u);(s===void 0||!fn(o.context.workspaceRoot,s.workspaceRoot))&&(i=o.cleanup);let c=hn(o.context,s);return u.throwIfAborted(),d=await pn(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 hn(e,t){return t===void 0?e:{...e,workspaceRoot:t.workspaceRoot}}async function gn(e,t){if(!(t.outcome.kind!==`workload-result`||e.onPostCommit===void 0))try{let n=_e.parse(t.outcome.result);await e.onPostCommit(n,t.decision)}catch{}}async function _n(e,t){t.throwIfAborted();let n={...e.workflowEnv},i=g(),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:()=>vn(e,a)}),u=s.bus,d=mn({...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 $(u,{executionAttemptId:e.executionAttemptId,runtimeGeneration:n,workspaceRoot:e.workspaceRoot,setupEnv:e.setupEnv,adapters:[d.adapter],signal:t,retry:e.outcomeRetry,reconnect:()=>u.reconnect()}),await gn(e,f),f}finally{try{await d.releaseExecutable(f)}finally{l.cleanup(),await s.close()}}}function vn(e,t){let n=_();return n.registerNamespaces([...ue,...b]),{bus:n,async connect(r){try{await e.connectBus(n,t,r),r.throwIfAborted()}catch(e){throw n.disconnect(),e}},close:()=>n.disconnect()}}export{R as A,xt as C,P as D,ct as E,k as F,A as I,O as L,ut as M,pt as N,lt as O,N as P,D as R,ht as S,bt as T,B as _,J as a,G as b,q as c,Ot as d,Dt as f,St as g,Ct as h,Ht as i,F as j,mt as k,Lt as l,wt as m,$ as n,At as o,Tt as p,Kt as r,kt as s,_n as t,It as u,V as v,U as w,K as x,H as y,E as z};