@ixo/editor 6.33.0 → 6.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (526) hide show
  1. package/dist/BidConfig-YLGSEIOS.js +154 -0
  2. package/dist/BidConfig-YLGSEIOS.js.map +1 -0
  3. package/dist/BidFlowDetail-U2SX5M7F.js +365 -0
  4. package/dist/BidFlowDetail-U2SX5M7F.js.map +1 -0
  5. package/dist/CalendarEventCreateConfig-J2LU6LJO.js +155 -0
  6. package/dist/CalendarEventCreateConfig-J2LU6LJO.js.map +1 -0
  7. package/dist/CalendarEventCreateFlowDetail-ZWHZWDOK.js +174 -0
  8. package/dist/CalendarEventCreateFlowDetail-ZWHZWDOK.js.map +1 -0
  9. package/dist/CalendarEventListConfig-GQNNF4ZB.js +116 -0
  10. package/dist/CalendarEventListConfig-GQNNF4ZB.js.map +1 -0
  11. package/dist/CalendarEventListFlowDetail-SSRTOXIX.js +58 -0
  12. package/dist/CalendarEventListFlowDetail-SSRTOXIX.js.map +1 -0
  13. package/dist/CalendarEventUpdateConfig-KACZA6GH.js +133 -0
  14. package/dist/CalendarEventUpdateConfig-KACZA6GH.js.map +1 -0
  15. package/dist/CalendarEventUpdateFlowDetail-CD6NHHOU.js +155 -0
  16. package/dist/CalendarEventUpdateFlowDetail-CD6NHHOU.js.map +1 -0
  17. package/dist/ClaimConfig-3HKPGK55.js +200 -0
  18. package/dist/ClaimConfig-3HKPGK55.js.map +1 -0
  19. package/dist/ClaimFlowDetail-I4OQSHAB.js +641 -0
  20. package/dist/ClaimFlowDetail-I4OQSHAB.js.map +1 -0
  21. package/dist/CollectionLifecycleConfig-LCCGZ3CJ.js +149 -0
  22. package/dist/CollectionLifecycleConfig-LCCGZ3CJ.js.map +1 -0
  23. package/dist/CollectionLifecycleFlowDetail-LQHKB227.js +647 -0
  24. package/dist/CollectionLifecycleFlowDetail-LQHKB227.js.map +1 -0
  25. package/dist/CollectionUsersConfig-RI2X3YY2.js +271 -0
  26. package/dist/CollectionUsersConfig-RI2X3YY2.js.map +1 -0
  27. package/dist/CollectionUsersFlowDetail-LHXVCCPQ.js +1276 -0
  28. package/dist/CollectionUsersFlowDetail-LHXVCCPQ.js.map +1 -0
  29. package/dist/CredentialStoreConfig-G66AQDGZ.js +75 -0
  30. package/dist/CredentialStoreConfig-G66AQDGZ.js.map +1 -0
  31. package/dist/CredentialStoreFlowDetail-FL7QAM3S.js +99 -0
  32. package/dist/CredentialStoreFlowDetail-FL7QAM3S.js.map +1 -0
  33. package/dist/DesignPodConfig-LJ7H2CZ6.js +8 -0
  34. package/dist/DesignPodConfig-LJ7H2CZ6.js.map +1 -0
  35. package/dist/DesignPodFlowDetail-JHJWGNVY.js +309 -0
  36. package/dist/DesignPodFlowDetail-JHJWGNVY.js.map +1 -0
  37. package/dist/DomainCardPreviewConfig-Q3X5M4WF.js +37 -0
  38. package/dist/DomainCardPreviewConfig-Q3X5M4WF.js.map +1 -0
  39. package/dist/DomainCardPreviewFlowDetail-Y2FE7O5Z.js +131 -0
  40. package/dist/DomainCardPreviewFlowDetail-Y2FE7O5Z.js.map +1 -0
  41. package/dist/DomainIndexerLookupConfig-N4VONQUY.js +41 -0
  42. package/dist/DomainIndexerLookupConfig-N4VONQUY.js.map +1 -0
  43. package/dist/DomainIndexerLookupFlowDetail-GJ7WWK7I.js +70 -0
  44. package/dist/DomainIndexerLookupFlowDetail-GJ7WWK7I.js.map +1 -0
  45. package/dist/DomainSignConfig-XFIXROVK.js +47 -0
  46. package/dist/DomainSignConfig-XFIXROVK.js.map +1 -0
  47. package/dist/DomainSignFlowDetail-BXZ6JBPR.js +206 -0
  48. package/dist/DomainSignFlowDetail-BXZ6JBPR.js.map +1 -0
  49. package/dist/DomainSingleSelectionConfig-ZNKIXB4P.js +101 -0
  50. package/dist/DomainSingleSelectionConfig-ZNKIXB4P.js.map +1 -0
  51. package/dist/DomainSingleSelectionFlowDetail-HWTQXSLA.js +147 -0
  52. package/dist/DomainSingleSelectionFlowDetail-HWTQXSLA.js.map +1 -0
  53. package/dist/EmailSendConfig-YEGZ5Q77.js +215 -0
  54. package/dist/EmailSendConfig-YEGZ5Q77.js.map +1 -0
  55. package/dist/EntityCreateOracleConfig-UZ6ZIMP5.js +150 -0
  56. package/dist/EntityCreateOracleConfig-UZ6ZIMP5.js.map +1 -0
  57. package/dist/EntityCreateOracleFlowDetail-H2X7CPYU.js +120 -0
  58. package/dist/EntityCreateOracleFlowDetail-H2X7CPYU.js.map +1 -0
  59. package/dist/EntitySingleSelectionConfig-DL57KNKM.js +30 -0
  60. package/dist/EntitySingleSelectionConfig-DL57KNKM.js.map +1 -0
  61. package/dist/EntitySingleSelectionFlowDetail-GFQGX3GA.js +118 -0
  62. package/dist/EntitySingleSelectionFlowDetail-GFQGX3GA.js.map +1 -0
  63. package/dist/EntityTransferConfig-JVZ3H35B.js +62 -0
  64. package/dist/EntityTransferConfig-JVZ3H35B.js.map +1 -0
  65. package/dist/EntityTransferFlowDetail-XEXM34XB.js +132 -0
  66. package/dist/EntityTransferFlowDetail-XEXM34XB.js.map +1 -0
  67. package/dist/EvalEngineConfig-CHC4IRN3.js +464 -0
  68. package/dist/EvalEngineConfig-CHC4IRN3.js.map +1 -0
  69. package/dist/EvalEngineFlowDetail-PUFRNO4U.js +4291 -0
  70. package/dist/EvalEngineFlowDetail-PUFRNO4U.js.map +1 -0
  71. package/dist/EvaluateBidConfig-OE4CM43G.js +151 -0
  72. package/dist/EvaluateBidConfig-OE4CM43G.js.map +1 -0
  73. package/dist/EvaluateBidFlowDetail-2EXGNBYC.js +564 -0
  74. package/dist/EvaluateBidFlowDetail-2EXGNBYC.js.map +1 -0
  75. package/dist/EvaluateClaimConfig-3D4F5LHU.js +297 -0
  76. package/dist/EvaluateClaimConfig-3D4F5LHU.js.map +1 -0
  77. package/dist/EvaluateClaimFlowDetail-QKHJVEDE.js +2237 -0
  78. package/dist/EvaluateClaimFlowDetail-QKHJVEDE.js.map +1 -0
  79. package/dist/FormSubmitConfig-UFZYMLUN.js +59 -0
  80. package/dist/FormSubmitConfig-UFZYMLUN.js.map +1 -0
  81. package/dist/FormSubmitFlowDetail-IAHDJS6P.js +169 -0
  82. package/dist/FormSubmitFlowDetail-IAHDJS6P.js.map +1 -0
  83. package/dist/GovernanceAuthzExecFlowDetail-SQBGU5BX.js +166 -0
  84. package/dist/GovernanceAuthzExecFlowDetail-SQBGU5BX.js.map +1 -0
  85. package/dist/GovernanceAuthzGrantFlowDetail-DZPNLANT.js +88 -0
  86. package/dist/GovernanceAuthzGrantFlowDetail-DZPNLANT.js.map +1 -0
  87. package/dist/GovernanceAuthzRevokeFlowDetail-3JZ4IUJG.js +88 -0
  88. package/dist/GovernanceAuthzRevokeFlowDetail-3JZ4IUJG.js.map +1 -0
  89. package/dist/GovernanceChainVoteFlowDetail-475UDNG6.js +83 -0
  90. package/dist/GovernanceChainVoteFlowDetail-475UDNG6.js.map +1 -0
  91. package/dist/GovernanceConfigConfig-V3WM4WBP.js +30 -0
  92. package/dist/GovernanceConfigConfig-V3WM4WBP.js.map +1 -0
  93. package/dist/GovernanceConfigFlowDetail-SQ5PPDRX.js +267 -0
  94. package/dist/GovernanceConfigFlowDetail-SQ5PPDRX.js.map +1 -0
  95. package/dist/GovernanceContractExecuteFlowDetail-H2ZV6W2E.js +113 -0
  96. package/dist/GovernanceContractExecuteFlowDetail-H2ZV6W2E.js.map +1 -0
  97. package/dist/GovernanceContractInstantiateFlowDetail-YJJMGM54.js +144 -0
  98. package/dist/GovernanceContractInstantiateFlowDetail-YJJMGM54.js.map +1 -0
  99. package/dist/GovernanceContractManageCw20FlowDetail-OCBMW3YJ.js +72 -0
  100. package/dist/GovernanceContractManageCw20FlowDetail-OCBMW3YJ.js.map +1 -0
  101. package/dist/GovernanceContractMigrateFlowDetail-JDNIKTT3.js +104 -0
  102. package/dist/GovernanceContractMigrateFlowDetail-JDNIKTT3.js.map +1 -0
  103. package/dist/GovernanceContractUpdateAdminFlowDetail-SZBOAOCC.js +68 -0
  104. package/dist/GovernanceContractUpdateAdminFlowDetail-SZBOAOCC.js.map +1 -0
  105. package/dist/GovernanceCustomMessageFlowDetail-CXD4ZATO.js +78 -0
  106. package/dist/GovernanceCustomMessageFlowDetail-CXD4ZATO.js.map +1 -0
  107. package/dist/GovernanceDaoAcceptToMarketplaceFlowDetail-Q6ZBNY7Z.js +98 -0
  108. package/dist/GovernanceDaoAcceptToMarketplaceFlowDetail-Q6ZBNY7Z.js.map +1 -0
  109. package/dist/GovernanceDaoAdminExecFlowDetail-JAEAY2US.js +94 -0
  110. package/dist/GovernanceDaoAdminExecFlowDetail-JAEAY2US.js.map +1 -0
  111. package/dist/GovernanceDaoCreateEntityFlowDetail-7RVNTVAB.js +96 -0
  112. package/dist/GovernanceDaoCreateEntityFlowDetail-7RVNTVAB.js.map +1 -0
  113. package/dist/GovernanceDaoJoinFlowDetail-XYCTCNHO.js +68 -0
  114. package/dist/GovernanceDaoJoinFlowDetail-XYCTCNHO.js.map +1 -0
  115. package/dist/GovernanceDaoManageStorageFlowDetail-LMLYLYYC.js +93 -0
  116. package/dist/GovernanceDaoManageStorageFlowDetail-LMLYLYYC.js.map +1 -0
  117. package/dist/GovernanceDaoManageSubDaosFlowDetail-YUFQ67JN.js +84 -0
  118. package/dist/GovernanceDaoManageSubDaosFlowDetail-YUFQ67JN.js.map +1 -0
  119. package/dist/GovernanceDaoUpdateInfoFlowDetail-G5FIBY4L.js +104 -0
  120. package/dist/GovernanceDaoUpdateInfoFlowDetail-G5FIBY4L.js.map +1 -0
  121. package/dist/GovernanceMemberProposalConfig-IGPXEFDB.js +42 -0
  122. package/dist/GovernanceMemberProposalConfig-IGPXEFDB.js.map +1 -0
  123. package/dist/GovernanceMemberProposalFlowDetail-T3VURONF.js +240 -0
  124. package/dist/GovernanceMemberProposalFlowDetail-T3VURONF.js.map +1 -0
  125. package/dist/GovernanceNftBurnFlowDetail-AG4I2O7H.js +69 -0
  126. package/dist/GovernanceNftBurnFlowDetail-AG4I2O7H.js.map +1 -0
  127. package/dist/GovernanceNftManageCollectionsFlowDetail-UAAGO3Q6.js +71 -0
  128. package/dist/GovernanceNftManageCollectionsFlowDetail-UAAGO3Q6.js.map +1 -0
  129. package/dist/GovernanceNftTransferFlowDetail-KXM7DTOV.js +130 -0
  130. package/dist/GovernanceNftTransferFlowDetail-KXM7DTOV.js.map +1 -0
  131. package/dist/GovernanceSettingsProposalConfig-4SLJTBLW.js +42 -0
  132. package/dist/GovernanceSettingsProposalConfig-4SLJTBLW.js.map +1 -0
  133. package/dist/GovernanceSettingsProposalFlowDetail-VFZPSCLR.js +165 -0
  134. package/dist/GovernanceSettingsProposalFlowDetail-VFZPSCLR.js.map +1 -0
  135. package/dist/GovernanceStakingStakeFlowDetail-ULLJ7FLM.js +123 -0
  136. package/dist/GovernanceStakingStakeFlowDetail-ULLJ7FLM.js.map +1 -0
  137. package/dist/GovernanceStakingStakeToGroupFlowDetail-CSPKJA3H.js +84 -0
  138. package/dist/GovernanceStakingStakeToGroupFlowDetail-CSPKJA3H.js.map +1 -0
  139. package/dist/GovernanceSubmissionConfigProposalFlowDetail-MZCPSZF2.js +111 -0
  140. package/dist/GovernanceSubmissionConfigProposalFlowDetail-MZCPSZF2.js.map +1 -0
  141. package/dist/GovernanceTransactionMintFlowDetail-Y2WRAODH.js +66 -0
  142. package/dist/GovernanceTransactionMintFlowDetail-Y2WRAODH.js.map +1 -0
  143. package/dist/GovernanceTransactionPerformTokenSwapFlowDetail-GEK6PMMI.js +133 -0
  144. package/dist/GovernanceTransactionPerformTokenSwapFlowDetail-GEK6PMMI.js.map +1 -0
  145. package/dist/GovernanceTransactionSendFundsConfig-VBKMLSF3.js +42 -0
  146. package/dist/GovernanceTransactionSendFundsConfig-VBKMLSF3.js.map +1 -0
  147. package/dist/GovernanceTransactionSendFundsFlowDetail-5TZB64VL.js +182 -0
  148. package/dist/GovernanceTransactionSendFundsFlowDetail-5TZB64VL.js.map +1 -0
  149. package/dist/GovernanceTransactionSendGroupTokenFlowDetail-EGOWVZM2.js +155 -0
  150. package/dist/GovernanceTransactionSendGroupTokenFlowDetail-EGOWVZM2.js.map +1 -0
  151. package/dist/GovernanceTransactionWithdrawTokenSwapFlowDetail-6XWVO5O6.js +56 -0
  152. package/dist/GovernanceTransactionWithdrawTokenSwapFlowDetail-6XWVO5O6.js.map +1 -0
  153. package/dist/GovernanceValidatorActionsFlowDetail-ZMLPAFUB.js +117 -0
  154. package/dist/GovernanceValidatorActionsFlowDetail-ZMLPAFUB.js.map +1 -0
  155. package/dist/HarvestConfig-AIGOGBFR.js +56 -0
  156. package/dist/HarvestConfig-AIGOGBFR.js.map +1 -0
  157. package/dist/HarvestFlowDetail-X3RUH3X3.js +131 -0
  158. package/dist/HarvestFlowDetail-X3RUH3X3.js.map +1 -0
  159. package/dist/HttpRequestConfig-OQEJIIJY.js +194 -0
  160. package/dist/HttpRequestConfig-OQEJIIJY.js.map +1 -0
  161. package/dist/HttpRequestFlowDetail-JVLV533Z.js +116 -0
  162. package/dist/HttpRequestFlowDetail-JVLV533Z.js.map +1 -0
  163. package/dist/IdentityCreateConfig-ZBUOJ6AL.js +94 -0
  164. package/dist/IdentityCreateConfig-ZBUOJ6AL.js.map +1 -0
  165. package/dist/IdentityCreateFlowDetail-4TE6UCEB.js +83 -0
  166. package/dist/IdentityCreateFlowDetail-4TE6UCEB.js.map +1 -0
  167. package/dist/IidCreateConfig-RRV2DYXI.js +75 -0
  168. package/dist/IidCreateConfig-RRV2DYXI.js.map +1 -0
  169. package/dist/IidCreateFlowDetail-HPVZAHVY.js +57 -0
  170. package/dist/IidCreateFlowDetail-HPVZAHVY.js.map +1 -0
  171. package/dist/KycVerifyConfig-VCG65K5K.js +65 -0
  172. package/dist/KycVerifyConfig-VCG65K5K.js.map +1 -0
  173. package/dist/KycVerifyFlowDetail-FEU43HML.js +421 -0
  174. package/dist/KycVerifyFlowDetail-FEU43HML.js.map +1 -0
  175. package/dist/ListDomainFlowsConfig-3JZEPTOJ.js +37 -0
  176. package/dist/ListDomainFlowsConfig-3JZEPTOJ.js.map +1 -0
  177. package/dist/ListDomainFlowsFlowDetail-XX5AXDZZ.js +257 -0
  178. package/dist/ListDomainFlowsFlowDetail-XX5AXDZZ.js.map +1 -0
  179. package/dist/LoadBatchesConfig-IMODIWRT.js +38 -0
  180. package/dist/LoadBatchesConfig-IMODIWRT.js.map +1 -0
  181. package/dist/LoadBatchesFlowDetail-GB24T76O.js +101 -0
  182. package/dist/LoadBatchesFlowDetail-GB24T76O.js.map +1 -0
  183. package/dist/MatrixDmConfig-NBII27CS.js +120 -0
  184. package/dist/MatrixDmConfig-NBII27CS.js.map +1 -0
  185. package/dist/MatrixRegisterConfig-N2U4FBYF.js +62 -0
  186. package/dist/MatrixRegisterConfig-N2U4FBYF.js.map +1 -0
  187. package/dist/MatrixRegisterFlowDetail-D5YNL5QX.js +86 -0
  188. package/dist/MatrixRegisterFlowDetail-D5YNL5QX.js.map +1 -0
  189. package/dist/MemberMultiSelectConfig-E7WUB2WD.js +30 -0
  190. package/dist/MemberMultiSelectConfig-E7WUB2WD.js.map +1 -0
  191. package/dist/MemberMultiSelectFlowDetail-6C4ZMSDR.js +392 -0
  192. package/dist/MemberMultiSelectFlowDetail-6C4ZMSDR.js.map +1 -0
  193. package/dist/OracleConfig-R7TDTTKN.js +56 -0
  194. package/dist/OracleConfig-R7TDTTKN.js.map +1 -0
  195. package/dist/OracleConfigureOracleConfig-QFF74X3N.js +198 -0
  196. package/dist/OracleConfigureOracleConfig-QFF74X3N.js.map +1 -0
  197. package/dist/OracleConfigureOracleFlowDetail-MIBXUEKC.js +255 -0
  198. package/dist/OracleConfigureOracleFlowDetail-MIBXUEKC.js.map +1 -0
  199. package/dist/OracleContractConfig-PHY5L7W2.js +38 -0
  200. package/dist/OracleContractConfig-PHY5L7W2.js.map +1 -0
  201. package/dist/OracleContractFlowDetail-M3PM4AU4.js +78 -0
  202. package/dist/OracleContractFlowDetail-M3PM4AU4.js.map +1 -0
  203. package/dist/OracleDeployConfig-QBG76ATZ.js +10 -0
  204. package/dist/OracleDeployConfig-QBG76ATZ.js.map +1 -0
  205. package/dist/OracleDeployFlowDetail-WKTMD2AD.js +231 -0
  206. package/dist/OracleDeployFlowDetail-WKTMD2AD.js.map +1 -0
  207. package/dist/OracleDeploySetupConfig-75XPGFJQ.js +10 -0
  208. package/dist/OracleDeploySetupConfig-75XPGFJQ.js.map +1 -0
  209. package/dist/OracleDeploySetupFlowDetail-R3BQ7EAU.js +165 -0
  210. package/dist/OracleDeploySetupFlowDetail-R3BQ7EAU.js.map +1 -0
  211. package/dist/OracleDeployStartConfig-NA6GZ4VQ.js +10 -0
  212. package/dist/OracleDeployStartConfig-NA6GZ4VQ.js.map +1 -0
  213. package/dist/OracleDeployStartFlowDetail-EL3CMDMG.js +89 -0
  214. package/dist/OracleDeployStartFlowDetail-EL3CMDMG.js.map +1 -0
  215. package/dist/OracleFlowDetail-5JCJK3GH.js +76 -0
  216. package/dist/OracleFlowDetail-5JCJK3GH.js.map +1 -0
  217. package/dist/OraclePromptConfig-YBRESISH.js +39 -0
  218. package/dist/OraclePromptConfig-YBRESISH.js.map +1 -0
  219. package/dist/OraclePromptFlowDetail-O3XNK7HY.js +112 -0
  220. package/dist/OraclePromptFlowDetail-O3XNK7HY.js.map +1 -0
  221. package/dist/OracleStoreConfigConfig-TUZWTJMA.js +134 -0
  222. package/dist/OracleStoreConfigConfig-TUZWTJMA.js.map +1 -0
  223. package/dist/OracleStoreConfigFlowDetail-Q6AUUSUL.js +99 -0
  224. package/dist/OracleStoreConfigFlowDetail-Q6AUUSUL.js.map +1 -0
  225. package/dist/OracleStoreSecretsAndConfigConfig-SZPYEK7U.js +198 -0
  226. package/dist/OracleStoreSecretsAndConfigConfig-SZPYEK7U.js.map +1 -0
  227. package/dist/OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js +220 -0
  228. package/dist/OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js.map +1 -0
  229. package/dist/OracleStoreSecretsConfig-PQMF7LFT.js +191 -0
  230. package/dist/OracleStoreSecretsConfig-PQMF7LFT.js.map +1 -0
  231. package/dist/OracleStoreSecretsFlowDetail-5RXWQ3KA.js +197 -0
  232. package/dist/OracleStoreSecretsFlowDetail-5RXWQ3KA.js.map +1 -0
  233. package/dist/ProposalCreateConfig-U5IHZNT7.js +161 -0
  234. package/dist/ProposalCreateConfig-U5IHZNT7.js.map +1 -0
  235. package/dist/ProposalCreateFlowDetail-2FCRCNYV.js +235 -0
  236. package/dist/ProposalCreateFlowDetail-2FCRCNYV.js.map +1 -0
  237. package/dist/ProposalVoteConfig-MH4MU7SL.js +150 -0
  238. package/dist/ProposalVoteConfig-MH4MU7SL.js.map +1 -0
  239. package/dist/ProposalVoteFlowDetail-IJJ3OHAB.js +280 -0
  240. package/dist/ProposalVoteFlowDetail-IJJ3OHAB.js.map +1 -0
  241. package/dist/ProtocolSelectConfig-S5U3P6K7.js +48 -0
  242. package/dist/ProtocolSelectConfig-S5U3P6K7.js.map +1 -0
  243. package/dist/ProtocolSelectFlowDetail-XBSJIEIH.js +116 -0
  244. package/dist/ProtocolSelectFlowDetail-XBSJIEIH.js.map +1 -0
  245. package/dist/RetireConfig-MV37WWZ6.js +59 -0
  246. package/dist/RetireConfig-MV37WWZ6.js.map +1 -0
  247. package/dist/RetireFlowDetail-VZ5O4SXI.js +147 -0
  248. package/dist/RetireFlowDetail-VZ5O4SXI.js.map +1 -0
  249. package/dist/SandboxProvisionConfig-ZGG4IRHM.js +46 -0
  250. package/dist/SandboxProvisionConfig-ZGG4IRHM.js.map +1 -0
  251. package/dist/SandboxProvisionFlowDetail-RUY64INV.js +79 -0
  252. package/dist/SandboxProvisionFlowDetail-RUY64INV.js.map +1 -0
  253. package/dist/WalletFundConfig-CMM3EP3B.js +117 -0
  254. package/dist/WalletFundConfig-CMM3EP3B.js.map +1 -0
  255. package/dist/WalletFundFlowDetail-TXWCZA4K.js +279 -0
  256. package/dist/WalletFundFlowDetail-TXWCZA4K.js.map +1 -0
  257. package/dist/WalletGenerateAndFundConfig-364RSEND.js +10 -0
  258. package/dist/WalletGenerateAndFundConfig-364RSEND.js.map +1 -0
  259. package/dist/WalletGenerateAndFundFlowDetail-C2LZW3NO.js +54 -0
  260. package/dist/WalletGenerateAndFundFlowDetail-C2LZW3NO.js.map +1 -0
  261. package/dist/WalletGenerateConfig-YYLCS65G.js +10 -0
  262. package/dist/WalletGenerateConfig-YYLCS65G.js.map +1 -0
  263. package/dist/WalletGenerateFlowDetail-CQCNDGJA.js +53 -0
  264. package/dist/WalletGenerateFlowDetail-CQCNDGJA.js.map +1 -0
  265. package/dist/XeroContactCreateConfig-OWG5PA3B.js +102 -0
  266. package/dist/XeroContactCreateConfig-OWG5PA3B.js.map +1 -0
  267. package/dist/XeroContactCreateFlowDetail-6MAINCF6.js +127 -0
  268. package/dist/XeroContactCreateFlowDetail-6MAINCF6.js.map +1 -0
  269. package/dist/XeroInvoiceCreateConfig-O74RUSZM.js +403 -0
  270. package/dist/XeroInvoiceCreateConfig-O74RUSZM.js.map +1 -0
  271. package/dist/XeroInvoiceCreateFlowDetail-UL7KS6CZ.js +631 -0
  272. package/dist/XeroInvoiceCreateFlowDetail-UL7KS6CZ.js.map +1 -0
  273. package/dist/XeroInvoiceListConfig-UR3GONBJ.js +113 -0
  274. package/dist/XeroInvoiceListConfig-UR3GONBJ.js.map +1 -0
  275. package/dist/XeroInvoiceListFlowDetail-LYHODWH6.js +58 -0
  276. package/dist/XeroInvoiceListFlowDetail-LYHODWH6.js.map +1 -0
  277. package/dist/XeroPaymentCreateConfig-RPMAIK6E.js +116 -0
  278. package/dist/XeroPaymentCreateConfig-RPMAIK6E.js.map +1 -0
  279. package/dist/XeroPaymentCreateFlowDetail-CF35MVIM.js +573 -0
  280. package/dist/XeroPaymentCreateFlowDetail-CF35MVIM.js.map +1 -0
  281. package/dist/action-manifest.json +2091 -393
  282. package/dist/chunk-2GAYKKTL.js +9 -0
  283. package/dist/chunk-2GAYKKTL.js.map +1 -0
  284. package/dist/chunk-3TUYY4HK.js +20 -0
  285. package/dist/chunk-3TUYY4HK.js.map +1 -0
  286. package/dist/chunk-4DGCCXD6.js +710 -0
  287. package/dist/chunk-4DGCCXD6.js.map +1 -0
  288. package/dist/chunk-4NAFQF6V.js +11 -0
  289. package/dist/chunk-4NAFQF6V.js.map +1 -0
  290. package/dist/chunk-4PONO4US.js +799 -0
  291. package/dist/chunk-4PONO4US.js.map +1 -0
  292. package/dist/chunk-4TMOIK5M.js +21 -0
  293. package/dist/chunk-4TMOIK5M.js.map +1 -0
  294. package/dist/chunk-5E6Z6JJN.js +4456 -0
  295. package/dist/chunk-5E6Z6JJN.js.map +1 -0
  296. package/dist/chunk-5IH3VC5I.js +102 -0
  297. package/dist/chunk-5IH3VC5I.js.map +1 -0
  298. package/dist/chunk-5NTKDOP6.js +89 -0
  299. package/dist/chunk-5NTKDOP6.js.map +1 -0
  300. package/dist/chunk-5O2SFRGU.js +18 -0
  301. package/dist/chunk-5O2SFRGU.js.map +1 -0
  302. package/dist/chunk-632JLECF.js +55 -0
  303. package/dist/chunk-632JLECF.js.map +1 -0
  304. package/dist/chunk-676HDB7K.js +95 -0
  305. package/dist/chunk-676HDB7K.js.map +1 -0
  306. package/dist/chunk-6ESTNTSH.js +223 -0
  307. package/dist/chunk-6ESTNTSH.js.map +1 -0
  308. package/dist/chunk-6GKJR52N.js +15 -0
  309. package/dist/chunk-6GKJR52N.js.map +1 -0
  310. package/dist/chunk-6L4ZIKYU.js +23 -0
  311. package/dist/chunk-6L4ZIKYU.js.map +1 -0
  312. package/dist/chunk-76YX5R4L.js +11 -0
  313. package/dist/chunk-76YX5R4L.js.map +1 -0
  314. package/dist/chunk-7J3GFMN3.js +32 -0
  315. package/dist/chunk-7J3GFMN3.js.map +1 -0
  316. package/dist/chunk-7LSARC2G.js +102 -0
  317. package/dist/chunk-7LSARC2G.js.map +1 -0
  318. package/dist/chunk-7W7UUUIE.js +609 -0
  319. package/dist/chunk-7W7UUUIE.js.map +1 -0
  320. package/dist/chunk-7ZLW7H37.js +21 -0
  321. package/dist/chunk-7ZLW7H37.js.map +1 -0
  322. package/dist/chunk-AAZHI22G.js +18 -0
  323. package/dist/chunk-AAZHI22G.js.map +1 -0
  324. package/dist/chunk-ACNE455I.js +76 -0
  325. package/dist/chunk-ACNE455I.js.map +1 -0
  326. package/dist/chunk-BKLSSLPZ.js +27 -0
  327. package/dist/chunk-BKLSSLPZ.js.map +1 -0
  328. package/dist/chunk-BZ7UPUTY.js +417 -0
  329. package/dist/chunk-BZ7UPUTY.js.map +1 -0
  330. package/dist/chunk-CGFAICUE.js +28 -0
  331. package/dist/chunk-CGFAICUE.js.map +1 -0
  332. package/dist/chunk-CMCEWQ3C.js +19 -0
  333. package/dist/chunk-CMCEWQ3C.js.map +1 -0
  334. package/dist/chunk-CP4UV436.js +41 -0
  335. package/dist/chunk-CP4UV436.js.map +1 -0
  336. package/dist/chunk-DIQRZP7Z.js +51 -0
  337. package/dist/chunk-DIQRZP7Z.js.map +1 -0
  338. package/dist/chunk-EBFFDDAS.js +13 -0
  339. package/dist/chunk-EBFFDDAS.js.map +1 -0
  340. package/dist/chunk-EGVS23DR.js +85 -0
  341. package/dist/chunk-EGVS23DR.js.map +1 -0
  342. package/dist/chunk-EKBQ7K4N.js +15 -0
  343. package/dist/chunk-EKBQ7K4N.js.map +1 -0
  344. package/dist/chunk-EKQCZRAN.js +24 -0
  345. package/dist/chunk-EKQCZRAN.js.map +1 -0
  346. package/dist/chunk-EYKZIZ5J.js +48 -0
  347. package/dist/chunk-EYKZIZ5J.js.map +1 -0
  348. package/dist/{chunk-NEOPTPDF.js → chunk-F4PTFXZH.js} +11554 -22046
  349. package/dist/chunk-F4PTFXZH.js.map +1 -0
  350. package/dist/chunk-F5GTFCYV.js +3333 -0
  351. package/dist/chunk-F5GTFCYV.js.map +1 -0
  352. package/dist/chunk-FFYZXA75.js +58 -0
  353. package/dist/chunk-FFYZXA75.js.map +1 -0
  354. package/dist/chunk-GFGDHPZ2.js +22 -0
  355. package/dist/chunk-GFGDHPZ2.js.map +1 -0
  356. package/dist/chunk-GR3CDFID.js +18 -0
  357. package/dist/chunk-GR3CDFID.js.map +1 -0
  358. package/dist/chunk-GR4SIU32.js +104 -0
  359. package/dist/chunk-GR4SIU32.js.map +1 -0
  360. package/dist/chunk-H5E46IIS.js +18 -0
  361. package/dist/chunk-H5E46IIS.js.map +1 -0
  362. package/dist/chunk-HFHVAMZL.js +22 -0
  363. package/dist/chunk-HFHVAMZL.js.map +1 -0
  364. package/dist/chunk-HT6L7A5M.js +12 -0
  365. package/dist/chunk-HT6L7A5M.js.map +1 -0
  366. package/dist/chunk-I2FPFISM.js +301 -0
  367. package/dist/chunk-I2FPFISM.js.map +1 -0
  368. package/dist/chunk-IADAQJDH.js +28 -0
  369. package/dist/chunk-IADAQJDH.js.map +1 -0
  370. package/dist/chunk-IBOBCMQQ.js +99 -0
  371. package/dist/chunk-IBOBCMQQ.js.map +1 -0
  372. package/dist/chunk-IFWKRCFF.js +56 -0
  373. package/dist/chunk-IFWKRCFF.js.map +1 -0
  374. package/dist/chunk-IH4T7V4C.js +40 -0
  375. package/dist/chunk-IH4T7V4C.js.map +1 -0
  376. package/dist/chunk-IIIZZ4E4.js +1679 -0
  377. package/dist/chunk-IIIZZ4E4.js.map +1 -0
  378. package/dist/chunk-ILSFU3WD.js +83 -0
  379. package/dist/chunk-ILSFU3WD.js.map +1 -0
  380. package/dist/chunk-IX3VBV3L.js +43 -0
  381. package/dist/chunk-IX3VBV3L.js.map +1 -0
  382. package/dist/chunk-JB6ASLUJ.js +315 -0
  383. package/dist/chunk-JB6ASLUJ.js.map +1 -0
  384. package/dist/chunk-JBBFSORW.js +846 -0
  385. package/dist/chunk-JBBFSORW.js.map +1 -0
  386. package/dist/chunk-JIDTNKKL.js +1183 -0
  387. package/dist/chunk-JIDTNKKL.js.map +1 -0
  388. package/dist/chunk-JSPE6NGZ.js +22 -0
  389. package/dist/chunk-JSPE6NGZ.js.map +1 -0
  390. package/dist/chunk-JVROGQ7Q.js +150 -0
  391. package/dist/chunk-JVROGQ7Q.js.map +1 -0
  392. package/dist/chunk-K4WUMWNJ.js +32 -0
  393. package/dist/chunk-K4WUMWNJ.js.map +1 -0
  394. package/dist/chunk-K74XQ4Q5.js +11 -0
  395. package/dist/chunk-K74XQ4Q5.js.map +1 -0
  396. package/dist/chunk-KLLMJ4U3.js +22 -0
  397. package/dist/chunk-KLLMJ4U3.js.map +1 -0
  398. package/dist/chunk-LTKVCJ2E.js +27 -0
  399. package/dist/chunk-LTKVCJ2E.js.map +1 -0
  400. package/dist/chunk-M36DJTFZ.js +34 -0
  401. package/dist/chunk-M36DJTFZ.js.map +1 -0
  402. package/dist/chunk-MHM52LCJ.js +154 -0
  403. package/dist/chunk-MHM52LCJ.js.map +1 -0
  404. package/dist/chunk-MQCDMHRZ.js +59 -0
  405. package/dist/chunk-MQCDMHRZ.js.map +1 -0
  406. package/dist/chunk-MZIBZ5FY.js +554 -0
  407. package/dist/chunk-MZIBZ5FY.js.map +1 -0
  408. package/dist/chunk-N3ORMGAI.js +348 -0
  409. package/dist/chunk-N3ORMGAI.js.map +1 -0
  410. package/dist/chunk-NCSGIRRQ.js +28 -0
  411. package/dist/chunk-NCSGIRRQ.js.map +1 -0
  412. package/dist/chunk-NIXT2SBH.js +1423 -0
  413. package/dist/chunk-NIXT2SBH.js.map +1 -0
  414. package/dist/chunk-NJAII6CO.js +148 -0
  415. package/dist/chunk-NJAII6CO.js.map +1 -0
  416. package/dist/chunk-NKE4TL43.js +92 -0
  417. package/dist/chunk-NKE4TL43.js.map +1 -0
  418. package/dist/chunk-NZ7AXA7B.js +1 -0
  419. package/dist/chunk-NZ7AXA7B.js.map +1 -0
  420. package/dist/chunk-OCAYEGI2.js +26 -0
  421. package/dist/chunk-OCAYEGI2.js.map +1 -0
  422. package/dist/chunk-OMLI45ER.js +90 -0
  423. package/dist/chunk-OMLI45ER.js.map +1 -0
  424. package/dist/chunk-P7OBLJAG.js +88 -0
  425. package/dist/chunk-P7OBLJAG.js.map +1 -0
  426. package/dist/chunk-PAY3CBWL.js +2321 -0
  427. package/dist/chunk-PAY3CBWL.js.map +1 -0
  428. package/dist/chunk-PFF6VY35.js +257 -0
  429. package/dist/chunk-PFF6VY35.js.map +1 -0
  430. package/dist/chunk-PYNDJDWZ.js +1758 -0
  431. package/dist/chunk-PYNDJDWZ.js.map +1 -0
  432. package/dist/chunk-QDQ6UMMN.js +53 -0
  433. package/dist/chunk-QDQ6UMMN.js.map +1 -0
  434. package/dist/chunk-QGT3G2XG.js +24 -0
  435. package/dist/chunk-QGT3G2XG.js.map +1 -0
  436. package/dist/chunk-QZYCJ2GZ.js +55 -0
  437. package/dist/chunk-QZYCJ2GZ.js.map +1 -0
  438. package/dist/chunk-REZ7RFSA.js +124 -0
  439. package/dist/chunk-REZ7RFSA.js.map +1 -0
  440. package/dist/chunk-RRYBAE6E.js +2449 -0
  441. package/dist/chunk-RRYBAE6E.js.map +1 -0
  442. package/dist/chunk-RWUZOB62.js +34 -0
  443. package/dist/chunk-RWUZOB62.js.map +1 -0
  444. package/dist/chunk-SB5UCPZH.js +116 -0
  445. package/dist/chunk-SB5UCPZH.js.map +1 -0
  446. package/dist/chunk-SEJJ7CRI.js +99 -0
  447. package/dist/chunk-SEJJ7CRI.js.map +1 -0
  448. package/dist/chunk-SHBFGRPV.js +45 -0
  449. package/dist/chunk-SHBFGRPV.js.map +1 -0
  450. package/dist/chunk-SOFJ4GC5.js +45 -0
  451. package/dist/chunk-SOFJ4GC5.js.map +1 -0
  452. package/dist/chunk-STH2HPZK.js +44 -0
  453. package/dist/chunk-STH2HPZK.js.map +1 -0
  454. package/dist/chunk-TK3JNKME.js +28 -0
  455. package/dist/chunk-TK3JNKME.js.map +1 -0
  456. package/dist/chunk-TMONHFE3.js +46 -0
  457. package/dist/chunk-TMONHFE3.js.map +1 -0
  458. package/dist/chunk-TR4KO3AG.js +44 -0
  459. package/dist/chunk-TR4KO3AG.js.map +1 -0
  460. package/dist/chunk-TS2LNBF2.js +68 -0
  461. package/dist/chunk-TS2LNBF2.js.map +1 -0
  462. package/dist/chunk-UZUMBFPP.js +26 -0
  463. package/dist/chunk-UZUMBFPP.js.map +1 -0
  464. package/dist/chunk-VRZ5LMOW.js +176 -0
  465. package/dist/chunk-VRZ5LMOW.js.map +1 -0
  466. package/dist/chunk-WLGGY6Z6.js +75 -0
  467. package/dist/chunk-WLGGY6Z6.js.map +1 -0
  468. package/dist/chunk-WO7V6ZNC.js +11 -0
  469. package/dist/chunk-WO7V6ZNC.js.map +1 -0
  470. package/dist/chunk-WXSENSRP.js +64 -0
  471. package/dist/chunk-WXSENSRP.js.map +1 -0
  472. package/dist/chunk-XEKBZ2SA.js +19 -0
  473. package/dist/chunk-XEKBZ2SA.js.map +1 -0
  474. package/dist/chunk-XPBKU3JX.js +61 -0
  475. package/dist/chunk-XPBKU3JX.js.map +1 -0
  476. package/dist/chunk-XRYXBXWH.js +24 -0
  477. package/dist/chunk-XRYXBXWH.js.map +1 -0
  478. package/dist/chunk-XVA7QRVH.js +22 -0
  479. package/dist/chunk-XVA7QRVH.js.map +1 -0
  480. package/dist/chunk-XYXDY72K.js +27508 -0
  481. package/dist/chunk-XYXDY72K.js.map +1 -0
  482. package/dist/chunk-YCTHHBSS.js +37 -0
  483. package/dist/chunk-YCTHHBSS.js.map +1 -0
  484. package/dist/chunk-YHPWD5NE.js +70 -0
  485. package/dist/chunk-YHPWD5NE.js.map +1 -0
  486. package/dist/chunk-YLNEKJQ5.js +126 -0
  487. package/dist/chunk-YLNEKJQ5.js.map +1 -0
  488. package/dist/chunk-YN4CEKCF.js +73 -0
  489. package/dist/chunk-YN4CEKCF.js.map +1 -0
  490. package/dist/chunk-YYNMESIF.js +17 -0
  491. package/dist/chunk-YYNMESIF.js.map +1 -0
  492. package/dist/chunk-Z6PRMCV6.js +1 -0
  493. package/dist/chunk-Z6PRMCV6.js.map +1 -0
  494. package/dist/chunk-ZDNW6VQG.js +11 -0
  495. package/dist/chunk-ZDNW6VQG.js.map +1 -0
  496. package/dist/chunk-ZP4D73DO.js +36 -0
  497. package/dist/chunk-ZP4D73DO.js.map +1 -0
  498. package/dist/chunk-ZUATADUV.js +26 -0
  499. package/dist/chunk-ZUATADUV.js.map +1 -0
  500. package/dist/{connections-1NtNQrsY.d.ts → connections-CEcurtWI.d.ts} +74 -9
  501. package/dist/core/index.cjs +14041 -6973
  502. package/dist/core/index.cjs.map +1 -1
  503. package/dist/core/index.d.ts +422 -138
  504. package/dist/core/index.js +425 -183
  505. package/dist/core/index.js.map +1 -1
  506. package/dist/flow-vnext/index.cjs +2842 -0
  507. package/dist/flow-vnext/index.cjs.map +1 -0
  508. package/dist/flow-vnext/index.d.ts +3 -0
  509. package/dist/flow-vnext/index.js +119 -0
  510. package/dist/flow-vnext/index.js.map +1 -0
  511. package/dist/{graphql-client-Bn0tN049.d.ts → graphql-client-B2tREsx6.d.ts} +3 -1
  512. package/dist/index-b9xxXGFs.d.ts +1230 -0
  513. package/dist/index.d.ts +5 -3
  514. package/dist/index.js +202 -37
  515. package/dist/index.js.map +1 -1
  516. package/dist/legacy-BpgIqaQ5.d.ts +14 -0
  517. package/dist/mantine/index.d.ts +7 -4
  518. package/dist/mantine/index.js +84 -30
  519. package/dist/mantine/index.js.map +1 -1
  520. package/dist/{runtime-BFwvCQDF.d.ts → types-Dqk5MTfW.d.ts} +6096 -5386
  521. package/package.json +12 -2
  522. package/dist/chunk-A4CWC4AG.js +0 -374
  523. package/dist/chunk-A4CWC4AG.js.map +0 -1
  524. package/dist/chunk-NEOPTPDF.js.map +0 -1
  525. package/dist/chunk-VRCRDKN5.js +0 -59694
  526. package/dist/chunk-VRCRDKN5.js.map +0 -1
@@ -0,0 +1,2842 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/flow-vnext/index.ts
31
+ var flow_vnext_exports = {};
32
+ __export(flow_vnext_exports, {
33
+ ActionContractResolutionError: () => ActionContractResolutionError,
34
+ ComposioContractMismatchError: () => ComposioContractMismatchError,
35
+ EffectClaimTransitionError: () => EffectClaimTransitionError,
36
+ EncryptedMatrixFlowDefinitionRevisionRepository: () => EncryptedMatrixFlowDefinitionRevisionRepository,
37
+ FLOW_CAPABILITIES: () => FLOW_CAPABILITIES,
38
+ FLOW_RUN_PROJECTIONS_MAP_KEY: () => FLOW_RUN_PROJECTIONS_MAP_KEY,
39
+ FlowDefinitionVerificationError: () => FlowDefinitionVerificationError,
40
+ FlowEventValidationError: () => FlowEventValidationError,
41
+ HistoricalManifestActionContractResolver: () => HistoricalManifestActionContractResolver,
42
+ LegacyFlowFrozenError: () => LegacyFlowFrozenError,
43
+ MATRIX_FLOW_DEFINITION_ANCHOR_TYPE: () => MATRIX_FLOW_DEFINITION_ANCHOR_TYPE,
44
+ MATRIX_FLOW_EVENT_TYPE: () => MATRIX_FLOW_EVENT_TYPE,
45
+ ManifestBoundComposioActionAdapter: () => ManifestBoundComposioActionAdapter,
46
+ MatrixRoomFlowEventStore: () => MatrixRoomFlowEventStore,
47
+ PeerExecutionError: () => PeerExecutionError,
48
+ UNIVERSAL_ACTION_COMPLETED_OUTCOME: () => UNIVERSAL_ACTION_COMPLETED_OUTCOME,
49
+ armEffectClaim: () => armEffectClaim,
50
+ assertLegacyFlowOperationAllowed: () => assertLegacyFlowOperationAllowed,
51
+ buildFlowResourceUri: () => buildFlowResourceUri,
52
+ canonicalizeJson: () => canonicalizeJson,
53
+ claimEffect: () => claimEffect,
54
+ computeActionContractDigest: () => computeActionContractDigest,
55
+ computeComposioAvailabilityDigest: () => computeComposioAvailabilityDigest,
56
+ computeExecutionPolicyDigest: () => computeExecutionPolicyDigest,
57
+ computeFlowDefinitionDigest: () => computeFlowDefinitionDigest,
58
+ createPeerExecutor: () => createPeerExecutor,
59
+ deepFreezeJson: () => deepFreezeJson,
60
+ deriveAttemptId: () => deriveAttemptId,
61
+ deriveEffectClaimKey: () => deriveEffectClaimKey,
62
+ deriveEventId: () => deriveEventId,
63
+ deriveReceiptId: () => deriveReceiptId,
64
+ deriveRunId: () => deriveRunId,
65
+ digestCanonicalJson: () => digestCanonicalJson,
66
+ drainTopicReceiptOutbox: () => drainTopicReceiptOutbox,
67
+ fingerprintFlowCommand: () => fingerprintFlowCommand,
68
+ flowRunProjectionStorageKey: () => flowRunProjectionStorageKey,
69
+ markEffectNeedsVerification: () => markEffectNeedsVerification,
70
+ matrixFlowEventTransactionId: () => matrixFlowEventTransactionId,
71
+ persistSignedTopicReceipt: () => persistSignedTopicReceipt,
72
+ prepareEffectSuccess: () => prepareEffectSuccess,
73
+ projectFlowRun: () => projectFlowRun,
74
+ readFlowRunProjection: () => readFlowRunProjection,
75
+ reduceFlowEvents: () => reduceFlowEvents,
76
+ renewEffectClaim: () => renewEffectClaim,
77
+ repairFlowRunProjection: () => repairFlowRunProjection,
78
+ resolveEffectClaim: () => resolveEffectClaim,
79
+ signComposioActionAvailability: () => signComposioActionAvailability,
80
+ signExecutionPolicy: () => signExecutionPolicy,
81
+ signFlowDefinitionRevision: () => signFlowDefinitionRevision,
82
+ signFlowEvent: () => signFlowEvent,
83
+ signMatrixDefinitionAnchor: () => signMatrixDefinitionAnchor,
84
+ verifyComposioActionAvailability: () => verifyComposioActionAvailability,
85
+ verifyExecutionPolicy: () => verifyExecutionPolicy,
86
+ verifyFlowDefinitionRevision: () => verifyFlowDefinitionRevision,
87
+ verifyFlowEvent: () => verifyFlowEvent,
88
+ verifyMatrixDefinitionAnchor: () => verifyMatrixDefinitionAnchor
89
+ });
90
+ module.exports = __toCommonJS(flow_vnext_exports);
91
+
92
+ // src/core/lib/flowEngine/vnext/canonical.ts
93
+ function deepFreezeJson(value) {
94
+ if (!value || typeof value !== "object") return value;
95
+ for (const nested of Object.values(value)) deepFreezeJson(nested);
96
+ return Object.freeze(value);
97
+ }
98
+ function isPlainObject(value) {
99
+ const prototype = Object.getPrototypeOf(value);
100
+ return prototype === Object.prototype || prototype === null;
101
+ }
102
+ function assertValidUnicode(value) {
103
+ for (let index = 0; index < value.length; index += 1) {
104
+ const codeUnit = value.charCodeAt(index);
105
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
106
+ const next = value.charCodeAt(index + 1);
107
+ if (!(next >= 56320 && next <= 57343)) {
108
+ throw new TypeError("Canonical JSON contains an unpaired Unicode surrogate");
109
+ }
110
+ index += 1;
111
+ } else if (codeUnit >= 56320 && codeUnit <= 57343) {
112
+ throw new TypeError("Canonical JSON contains an unpaired Unicode surrogate");
113
+ }
114
+ }
115
+ }
116
+ function canonicalizeJson(value) {
117
+ const ancestors = /* @__PURE__ */ new Set();
118
+ const serialize = (candidate) => {
119
+ if (candidate === null || typeof candidate === "boolean") return JSON.stringify(candidate);
120
+ if (typeof candidate === "string") {
121
+ assertValidUnicode(candidate);
122
+ return JSON.stringify(candidate);
123
+ }
124
+ if (typeof candidate === "number") {
125
+ if (!Number.isFinite(candidate)) throw new TypeError("Canonical JSON numbers must be finite");
126
+ return JSON.stringify(candidate);
127
+ }
128
+ if (typeof candidate !== "object") {
129
+ throw new TypeError(`Canonical JSON contains a non-JSON value: ${typeof candidate}`);
130
+ }
131
+ if (ancestors.has(candidate)) throw new TypeError("Canonical JSON contains a circular reference");
132
+ ancestors.add(candidate);
133
+ try {
134
+ if (Array.isArray(candidate)) return `[${candidate.map((entry) => serialize(entry)).join(",")}]`;
135
+ if (!isPlainObject(candidate)) throw new TypeError("Canonical JSON contains a non-plain object");
136
+ return `{${Object.keys(candidate).sort().map((key) => {
137
+ assertValidUnicode(key);
138
+ return `${JSON.stringify(key)}:${serialize(candidate[key])}`;
139
+ }).join(",")}}`;
140
+ } finally {
141
+ ancestors.delete(candidate);
142
+ }
143
+ };
144
+ return serialize(value);
145
+ }
146
+ async function digestCanonicalJson(value) {
147
+ if (!globalThis.crypto?.subtle) throw new Error("Web Crypto is required to digest a Flow contract");
148
+ const bytes = new TextEncoder().encode(canonicalizeJson(value));
149
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
150
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
151
+ return `sha256:${hex}`;
152
+ }
153
+
154
+ // src/core/lib/flowEngine/vnext/contracts.ts
155
+ var FlowDefinitionVerificationError = class extends Error {
156
+ constructor(code, message) {
157
+ super(message);
158
+ this.code = code;
159
+ this.name = "FlowDefinitionVerificationError";
160
+ }
161
+ };
162
+ var DEFINITION_SIGNATURE_DOMAIN = "qi.flow.definition.v1\0";
163
+ var EXECUTION_POLICY_SIGNATURE_DOMAIN = "qi.flow.execution-policy.v1\0";
164
+ function asCanonical(value) {
165
+ return value;
166
+ }
167
+ function signatureInput(digest) {
168
+ return new TextEncoder().encode(`${DEFINITION_SIGNATURE_DOMAIN}${digest}`);
169
+ }
170
+ function policySignatureInput(digest) {
171
+ return new TextEncoder().encode(`${EXECUTION_POLICY_SIGNATURE_DOMAIN}${digest}`);
172
+ }
173
+ function assertExecutionPolicyPayload(payload) {
174
+ if (payload.kind !== "qi.flow.execution-policy" || payload.schemaVersion !== "1.0") throw new Error("Unsupported Flow execution policy");
175
+ if (payload.mode !== "enabled" && payload.mode !== "pause_new_effects") throw new Error("Unsupported Flow execution policy mode");
176
+ if (!payload.definition.digest || !payload.issuedBy || !payload.issuedAt) throw new Error("Execution policy identity, issuer, and timestamp are required");
177
+ if (payload.expiresAt && Date.parse(payload.expiresAt) <= Date.parse(payload.issuedAt)) throw new Error("Execution policy expiry must be after issuance");
178
+ }
179
+ async function computeExecutionPolicyDigest(payload) {
180
+ assertExecutionPolicyPayload(payload);
181
+ return await digestCanonicalJson(asCanonical(payload));
182
+ }
183
+ async function signExecutionPolicy(payload, signer) {
184
+ const snapshot = JSON.parse(canonicalizeJson(asCanonical(payload)));
185
+ assertExecutionPolicyPayload(snapshot);
186
+ if (signer.issuerDid !== snapshot.issuedBy || !signer.verificationMethod.startsWith(`${snapshot.issuedBy}#`)) {
187
+ throw new Error("Execution policy signer does not match the issuer");
188
+ }
189
+ const digest = await computeExecutionPolicyDigest(snapshot);
190
+ const signature = await signer.sign(policySignatureInput(digest));
191
+ if (!signature) throw new Error("Execution policy signer returned an empty signature");
192
+ return {
193
+ ...snapshot,
194
+ integrity: {
195
+ canonicalization: "RFC8785",
196
+ digest: { algorithm: "SHA-256", value: digest },
197
+ signature: { algorithm: signer.algorithm, verificationMethod: signer.verificationMethod, value: signature }
198
+ }
199
+ };
200
+ }
201
+ async function verifyExecutionPolicy(candidate, policy, now = /* @__PURE__ */ new Date()) {
202
+ const snapshot = JSON.parse(canonicalizeJson(asCanonical(candidate)));
203
+ const { integrity, ...payload } = snapshot;
204
+ assertExecutionPolicyPayload(payload);
205
+ const digest = await computeExecutionPolicyDigest(payload);
206
+ if (digest !== integrity.digest.value) throw new Error("Execution policy digest does not match its content");
207
+ if (!policy.trustedIssuerDids.includes(payload.issuedBy)) throw new Error(`Execution policy issuer is not trusted: ${payload.issuedBy}`);
208
+ if (policy.revokedIssuerDids?.includes(payload.issuedBy)) throw new Error(`Execution policy issuer is revoked: ${payload.issuedBy}`);
209
+ if (!policy.allowedSignatureAlgorithms.includes(integrity.signature.algorithm))
210
+ throw new Error(`Execution policy signature algorithm is not allowed: ${integrity.signature.algorithm}`);
211
+ if (!integrity.signature.verificationMethod.startsWith(`${payload.issuedBy}#`)) throw new Error("Execution policy verification method does not belong to the issuer");
212
+ if (payload.expiresAt && Date.parse(payload.expiresAt) <= now.getTime()) throw new Error("Execution policy is expired");
213
+ const valid = await policy.verifySignature({
214
+ issuerDid: payload.issuedBy,
215
+ verificationMethod: integrity.signature.verificationMethod,
216
+ algorithm: integrity.signature.algorithm,
217
+ data: policySignatureInput(digest),
218
+ signature: integrity.signature.value
219
+ });
220
+ if (!valid) throw new Error("Execution policy signature verification failed");
221
+ return deepFreezeJson(snapshot);
222
+ }
223
+ function assertDefinitionPayload(payload) {
224
+ if (payload.kind !== "qi.flow.definition-revision" || payload.schemaVersion !== "1.0") {
225
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", "Unsupported Flow definition contract");
226
+ }
227
+ if (!payload.ref.flowId || !payload.ref.revision || !payload.publishedBy || payload.steps.length === 0) {
228
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", "Flow definition identity, publisher, and steps are required");
229
+ }
230
+ const stepIds = /* @__PURE__ */ new Set();
231
+ for (const step of payload.steps) {
232
+ if (!step.stepId || !step.blockId || !step.action.contractDigest || !step.action.manifestDigest) {
233
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", "Every Flow step must pin its identity and Action contract");
234
+ }
235
+ if (step.action.manifestDigest !== payload.actionManifestDigest) {
236
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} does not use the revision Action manifest`);
237
+ }
238
+ if (stepIds.has(step.stepId)) throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Duplicate Flow step id: ${step.stepId}`);
239
+ if (step.trigger.kind === "schedule") {
240
+ if (!step.trigger.scheduleRef || step.trigger.scheduleRevision !== void 0 && (!Number.isInteger(step.trigger.scheduleRevision) || step.trigger.scheduleRevision < 1)) {
241
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} has an invalid schedule binding`);
242
+ }
243
+ }
244
+ if (step.trigger.kind === "topic.request" && !step.trigger.requestKind.trim()) {
245
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} has an invalid Topic request kind`);
246
+ }
247
+ if (step.ttlMs !== void 0 && (!Number.isFinite(step.ttlMs) || step.ttlMs < 0)) {
248
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} has an invalid ttlMs`);
249
+ }
250
+ if (step.ttl?.absoluteDueDate && !Number.isFinite(Date.parse(step.ttl.absoluteDueDate))) {
251
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} has an invalid absolute TTL`);
252
+ }
253
+ for (const duration of [step.ttl?.fromEnablement, step.ttl?.fromCommitment]) {
254
+ const match = duration ? /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/u.exec(duration) : void 0;
255
+ if (duration && (!match || !match.slice(1).some((part) => Number(part ?? 0) > 0))) {
256
+ throw new FlowDefinitionVerificationError("INVALID_DEFINITION", `Flow step ${step.stepId} has an invalid relative TTL`);
257
+ }
258
+ }
259
+ stepIds.add(step.stepId);
260
+ }
261
+ }
262
+ async function computeFlowDefinitionDigest(payload) {
263
+ assertDefinitionPayload(payload);
264
+ return await digestCanonicalJson(asCanonical(payload));
265
+ }
266
+ async function signFlowDefinitionRevision(payload, signer) {
267
+ const snapshot = JSON.parse(canonicalizeJson(asCanonical(payload)));
268
+ assertDefinitionPayload(snapshot);
269
+ if (signer.issuerDid !== snapshot.publishedBy || !signer.verificationMethod.startsWith(`${snapshot.publishedBy}#`)) {
270
+ throw new FlowDefinitionVerificationError("SIGNER_MISMATCH", "Flow definition signer does not match the publisher");
271
+ }
272
+ const digest = await computeFlowDefinitionDigest(snapshot);
273
+ const signature = await signer.sign(signatureInput(digest));
274
+ if (!signature) throw new FlowDefinitionVerificationError("INVALID_SIGNATURE", "Flow definition signer returned an empty signature");
275
+ return {
276
+ ...snapshot,
277
+ integrity: {
278
+ canonicalization: "RFC8785",
279
+ digest: { algorithm: "SHA-256", value: digest },
280
+ signature: { algorithm: signer.algorithm, verificationMethod: signer.verificationMethod, value: signature }
281
+ }
282
+ };
283
+ }
284
+ async function verifyFlowDefinitionRevision(candidate, policy) {
285
+ const snapshot = JSON.parse(canonicalizeJson(asCanonical(candidate)));
286
+ const { integrity, ...payload } = snapshot;
287
+ assertDefinitionPayload(payload);
288
+ const digest = await computeFlowDefinitionDigest(payload);
289
+ if (digest !== integrity.digest.value) throw new FlowDefinitionVerificationError("DIGEST_MISMATCH", "Flow definition digest does not match its content");
290
+ if (!policy.trustedIssuerDids.includes(payload.publishedBy)) {
291
+ throw new FlowDefinitionVerificationError("UNTRUSTED_ISSUER", `Flow definition issuer is not trusted: ${payload.publishedBy}`);
292
+ }
293
+ if (policy.revokedIssuerDids?.includes(payload.publishedBy)) {
294
+ throw new FlowDefinitionVerificationError("REVOKED_ISSUER", `Flow definition issuer is revoked: ${payload.publishedBy}`);
295
+ }
296
+ if (!policy.allowedSignatureAlgorithms.includes(integrity.signature.algorithm)) {
297
+ throw new FlowDefinitionVerificationError("DISALLOWED_SIGNATURE_ALGORITHM", `Flow definition signature algorithm is not allowed: ${integrity.signature.algorithm}`);
298
+ }
299
+ if (!integrity.signature.verificationMethod.startsWith(`${payload.publishedBy}#`)) {
300
+ throw new FlowDefinitionVerificationError("SIGNER_MISMATCH", "Flow definition verification method does not belong to the publisher");
301
+ }
302
+ const verified = await policy.verifySignature({
303
+ issuerDid: payload.publishedBy,
304
+ verificationMethod: integrity.signature.verificationMethod,
305
+ algorithm: integrity.signature.algorithm,
306
+ data: signatureInput(digest),
307
+ signature: integrity.signature.value
308
+ });
309
+ if (!verified) throw new FlowDefinitionVerificationError("INVALID_SIGNATURE", "Flow definition signature verification failed");
310
+ return deepFreezeJson(snapshot);
311
+ }
312
+ var FLOW_CAPABILITIES = {
313
+ definitionRead: "flow/definition.read",
314
+ definitionWrite: "flow/definition.write",
315
+ definitionPublish: "flow/definition.publish",
316
+ definitionClone: "flow/definition.clone",
317
+ runStart: "flow/run.start",
318
+ runClose: "flow/run.close",
319
+ runCancel: "flow/run.cancel",
320
+ actionExecute: "flow/action.execute",
321
+ topicBindFlow: "topic/bind-flow",
322
+ topicRequestAction: "topic/request-action",
323
+ topicRecordAction: "topic/record-action"
324
+ };
325
+ function segment(value) {
326
+ return encodeURIComponent(value);
327
+ }
328
+ function buildFlowResourceUri(definition, target) {
329
+ const root = `ixo:flow:${segment(definition.flowId)}@${segment(definition.revision)}`;
330
+ if (!target) return root;
331
+ if (target.kind === "run") return `${root}/runs/${segment(target.runId)}`;
332
+ const run = target.runId ? `/runs/${segment(target.runId)}` : "";
333
+ return `${root}${run}/steps/${segment(target.stepId)}`;
334
+ }
335
+
336
+ // src/core/lib/flowEngine/vnext/ids.ts
337
+ async function deriveId(namespace, parts) {
338
+ const digest = await digestCanonicalJson({ namespace, parts });
339
+ return `${namespace}:${digest.slice("sha256:".length)}`;
340
+ }
341
+ function deriveRunId(definition, launchKind, launchNonce) {
342
+ return deriveId("run", [definition.digest, launchKind, launchNonce]);
343
+ }
344
+ function deriveAttemptId(params) {
345
+ return deriveId("attempt", [params.runId, params.stepId, params.idempotencyKey, params.inputDigest]);
346
+ }
347
+ function deriveEventId(unsignedEvent) {
348
+ return deriveId("event", unsignedEvent);
349
+ }
350
+ function deriveReceiptId(params) {
351
+ return deriveId("receipt", [params.topicRequestId, params.attemptId, params.phase, params.eventId]);
352
+ }
353
+ function deriveEffectClaimKey(params) {
354
+ return digestCanonicalJson([
355
+ params.definition.digest,
356
+ params.runId,
357
+ params.stepId,
358
+ params.attemptId,
359
+ params.actorDid,
360
+ params.inputDigest,
361
+ params.action.contractDigest,
362
+ params.topicBindingId ?? null
363
+ ]);
364
+ }
365
+
366
+ // src/core/lib/flowEngine/vnext/events.ts
367
+ var EVENT_SIGNATURE_DOMAIN = "qi.flow.event.v1\0";
368
+ var FlowEventValidationError = class extends Error {
369
+ constructor(message) {
370
+ super(message);
371
+ this.name = "FlowEventValidationError";
372
+ }
373
+ };
374
+ function signatureInput2(eventId) {
375
+ return new TextEncoder().encode(`${EVENT_SIGNATURE_DOMAIN}${eventId}`);
376
+ }
377
+ function flowEventSnapshot(value) {
378
+ let snapshot;
379
+ try {
380
+ snapshot = JSON.parse(canonicalizeJson(value));
381
+ } catch {
382
+ throw new FlowEventValidationError("Flow event content cannot be canonicalized");
383
+ }
384
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) throw new FlowEventValidationError("Flow event envelope is malformed");
385
+ return snapshot;
386
+ }
387
+ function isRecord(value) {
388
+ return value !== null && typeof value === "object" && !Array.isArray(value);
389
+ }
390
+ function isStringArray(value) {
391
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
392
+ }
393
+ function hasDefinitionRefShape(value) {
394
+ return isRecord(value) && typeof value.flowId === "string" && typeof value.revision === "string" && typeof value.digest === "string";
395
+ }
396
+ function hasAttemptShape(payload) {
397
+ return typeof payload.attemptId === "string" && typeof payload.stepId === "string";
398
+ }
399
+ function assertVerifiedEnvelopeShape(snapshot) {
400
+ if (snapshot.kind !== "qi.flow.event" || snapshot.schemaVersion !== "1.0" || typeof snapshot.eventId !== "string" || typeof snapshot.runId !== "string" || !hasDefinitionRefShape(snapshot.definition) || typeof snapshot.producer !== "string" || typeof snapshot.actor !== "string" || typeof snapshot.occurredAt !== "string" || !isStringArray(snapshot.parents) || snapshot.causationId !== void 0 && typeof snapshot.causationId !== "string" || typeof snapshot.correlationId !== "string" || typeof snapshot.idempotencyKey !== "string" || typeof snapshot.commandFingerprint !== "string" || !isStringArray(snapshot.proofReferences) || !isRecord(snapshot.signature) || typeof snapshot.signature.algorithm !== "string" || typeof snapshot.signature.verificationMethod !== "string" || typeof snapshot.signature.value !== "string" || !isRecord(snapshot.payload) || typeof snapshot.payload.kind !== "string") {
401
+ throw new FlowEventValidationError("Flow event envelope is malformed");
402
+ }
403
+ const payload = snapshot.payload;
404
+ switch (payload.kind) {
405
+ case "run.started": {
406
+ const genesis = payload.genesis;
407
+ if (!isRecord(genesis) || genesis.kind !== "qi.flow.run-genesis" || genesis.schemaVersion !== "1.0" || typeof genesis.runId !== "string" || !hasDefinitionRefShape(genesis.definition) || !["manual", "topic.request", "schedule", "event"].includes(String(genesis.launchKind)) || typeof genesis.launchNonce !== "string" || !isStringArray(genesis.requiredStepIds) || typeof genesis.startedBy !== "string" || typeof genesis.startedAt !== "string" || genesis.topicBindingId !== void 0 && typeof genesis.topicBindingId !== "string") {
408
+ throw new FlowEventValidationError("Flow run genesis is malformed");
409
+ }
410
+ break;
411
+ }
412
+ case "run.cancel_requested":
413
+ if (payload.reason !== void 0 && typeof payload.reason !== "string") throw new FlowEventValidationError("Flow cancellation reason is malformed");
414
+ break;
415
+ case "action.requested":
416
+ if (!hasAttemptShape(payload) || typeof payload.inputDigest !== "string") throw new FlowEventValidationError("Flow Action request is malformed");
417
+ break;
418
+ case "action.approval_proposed":
419
+ if (!hasAttemptShape(payload) || typeof payload.proposalDigest !== "string") throw new FlowEventValidationError("Flow Action approval proposal is malformed");
420
+ break;
421
+ case "action.started":
422
+ if (!hasAttemptShape(payload)) throw new FlowEventValidationError("Flow Action start is malformed");
423
+ break;
424
+ case "action.effect_armed":
425
+ if (!hasAttemptShape(payload) || typeof payload.claimKey !== "string" || !Number.isSafeInteger(payload.fencingEpoch) || Number(payload.fencingEpoch) < 1) {
426
+ throw new FlowEventValidationError("Flow Action fence is malformed");
427
+ }
428
+ break;
429
+ case "action.succeeded":
430
+ if (!hasAttemptShape(payload) || typeof payload.outputDigest !== "string" || payload.providerCorrelation !== void 0 && typeof payload.providerCorrelation !== "string" || payload.claimKey !== void 0 && typeof payload.claimKey !== "string" || payload.fencingEpoch !== void 0 && (!Number.isSafeInteger(payload.fencingEpoch) || Number(payload.fencingEpoch) < 1) || payload.outcomes !== void 0 && !Array.isArray(payload.outcomes)) {
431
+ throw new FlowEventValidationError("Flow Action success is malformed");
432
+ }
433
+ break;
434
+ case "action.outcome_emitted":
435
+ if (!hasAttemptShape(payload)) throw new FlowEventValidationError("Flow Action outcome is malformed");
436
+ break;
437
+ case "action.failed_before_effect":
438
+ if (!hasAttemptShape(payload) || !isRecord(payload.error)) throw new FlowEventValidationError("Flow Action failure is malformed");
439
+ break;
440
+ case "action.needs_verification":
441
+ if (!hasAttemptShape(payload) || typeof payload.reason !== "string" || payload.providerCorrelation !== void 0 && typeof payload.providerCorrelation !== "string") {
442
+ throw new FlowEventValidationError("Flow Action verification state is malformed");
443
+ }
444
+ break;
445
+ case "receipt.persisted":
446
+ if (typeof payload.attemptId !== "string" || typeof payload.receiptId !== "string" || typeof payload.receiptDigest !== "string") {
447
+ throw new FlowEventValidationError("Flow receipt evidence is malformed");
448
+ }
449
+ break;
450
+ case "run.finalized": {
451
+ const summary = payload.summary;
452
+ if (!["completed", "failed", "cancelled"].includes(String(payload.status)) || !isRecord(summary) || summary.kind !== "qi.flow.run-finalization-summary" || summary.schemaVersion !== "1.0" || summary.status !== payload.status || typeof summary.cancelRequested !== "boolean" || !isStringArray(summary.requiredStepIds) || !isStringArray(summary.frontierEventIds) || !Array.isArray(summary.attempts) || !summary.attempts.every(
453
+ (attempt) => isRecord(attempt) && typeof attempt.attemptId === "string" && typeof attempt.stepId === "string" && ["not_started", "armed", "succeeded", "failed_before_effect", "needs_verification"].includes(String(attempt.disposition)) && isStringArray(attempt.receiptIds)
454
+ ) || typeof payload.summaryDigest !== "string") {
455
+ throw new FlowEventValidationError("Flow run finalization is malformed");
456
+ }
457
+ break;
458
+ }
459
+ case "log":
460
+ if (!["debug", "info", "warn", "error"].includes(String(payload.level)) || typeof payload.message !== "string") {
461
+ throw new FlowEventValidationError("Flow log event is malformed");
462
+ }
463
+ break;
464
+ default:
465
+ throw new FlowEventValidationError(`Unsupported Flow event payload: ${String(payload.kind)}`);
466
+ }
467
+ }
468
+ async function signFlowEvent(unsigned, signer) {
469
+ const snapshot = flowEventSnapshot(unsigned);
470
+ const { eventId: _eventId, signature: _signature, ...unsignedSnapshot } = snapshot;
471
+ if (unsignedSnapshot.producer !== signer.producerDid || !signer.verificationMethod.startsWith(`${unsignedSnapshot.producer}#`)) {
472
+ throw new Error("Flow event signer does not match the producer");
473
+ }
474
+ const eventId = await deriveEventId(unsignedSnapshot);
475
+ const signature = await signer.sign(signatureInput2(eventId));
476
+ if (!signature) throw new Error("Flow event signer returned an empty signature");
477
+ return {
478
+ ...unsignedSnapshot,
479
+ eventId,
480
+ signature: { algorithm: signer.algorithm, verificationMethod: signer.verificationMethod, value: signature }
481
+ };
482
+ }
483
+ async function verifyFlowEvent(event, policy) {
484
+ const snapshot = flowEventSnapshot(event);
485
+ assertVerifiedEnvelopeShape(snapshot);
486
+ const { eventId, signature, ...unsigned } = snapshot;
487
+ const expectedId = await deriveEventId(unsigned);
488
+ if (expectedId !== eventId) throw new FlowEventValidationError("Flow event content does not match its event id");
489
+ const outcomes = snapshot.payload.kind === "action.succeeded" ? snapshot.payload.outcomes ?? [] : snapshot.payload.kind === "action.outcome_emitted" ? [snapshot.payload] : [];
490
+ const seenOutcomes = /* @__PURE__ */ new Set();
491
+ for (const outcome of outcomes) {
492
+ if (typeof outcome.name !== "string" || !outcome.name.trim()) throw new FlowEventValidationError("Flow event outcome name is required");
493
+ if (!outcome.payload || typeof outcome.payload !== "object" || Array.isArray(outcome.payload) || typeof outcome.payloadDigest !== "string") {
494
+ throw new FlowEventValidationError(`Flow event outcome payload is malformed: ${outcome.name}`);
495
+ }
496
+ const actualDigest = await digestCanonicalJson(outcome.payload);
497
+ if (actualDigest !== outcome.payloadDigest) throw new FlowEventValidationError(`Flow event outcome payload digest mismatch: ${outcome.name}`);
498
+ const identity = `${outcome.name}\0${outcome.payloadDigest}`;
499
+ if (seenOutcomes.has(identity)) throw new FlowEventValidationError(`Flow event contains a duplicate outcome: ${outcome.name}`);
500
+ seenOutcomes.add(identity);
501
+ }
502
+ if (snapshot.payload.kind === "run.finalized") {
503
+ if (!snapshot.payload.summary || typeof snapshot.payload.summary !== "object" || Array.isArray(snapshot.payload.summary)) {
504
+ throw new FlowEventValidationError("Flow run finalization summary is malformed");
505
+ }
506
+ const actualDigest = await digestCanonicalJson(snapshot.payload.summary);
507
+ if (actualDigest !== snapshot.payload.summaryDigest) throw new FlowEventValidationError("Flow run finalization summary digest mismatch");
508
+ }
509
+ if (!signature.verificationMethod.startsWith(`${snapshot.producer}#`)) throw new FlowEventValidationError("Flow event verification method does not belong to the producer");
510
+ if (!policy.allowedSignatureAlgorithms.includes(signature.algorithm)) {
511
+ throw new FlowEventValidationError(`Flow event signature algorithm is not allowed: ${signature.algorithm}`);
512
+ }
513
+ if (!await policy.isTrustedProducer(snapshot.producer, signature.verificationMethod)) {
514
+ throw new FlowEventValidationError(`Flow event producer is not trusted: ${snapshot.producer}`);
515
+ }
516
+ if (!await policy.verifySignature({
517
+ producerDid: snapshot.producer,
518
+ verificationMethod: signature.verificationMethod,
519
+ algorithm: signature.algorithm,
520
+ data: signatureInput2(eventId),
521
+ signature: signature.value
522
+ })) {
523
+ throw new FlowEventValidationError("Flow event signature verification failed");
524
+ }
525
+ return deepFreezeJson(snapshot);
526
+ }
527
+ function matrixFlowEventTransactionId(event) {
528
+ return `qi-flow-v1-${event.eventId}`;
529
+ }
530
+ function eventHasAncestor(event, ancestor, byId, seen = /* @__PURE__ */ new Set()) {
531
+ if (seen.has(event.eventId)) return false;
532
+ seen.add(event.eventId);
533
+ for (const parent of event.parents) {
534
+ if (parent === ancestor) return true;
535
+ const parentEvent = byId.get(parent);
536
+ if (parentEvent && eventHasAncestor(parentEvent, ancestor, byId, seen)) return true;
537
+ }
538
+ return false;
539
+ }
540
+ function causalOrder(events, byId) {
541
+ const indegree = new Map(events.map((event) => [event.eventId, 0]));
542
+ const children = /* @__PURE__ */ new Map();
543
+ for (const event of events) {
544
+ for (const parent of event.parents) {
545
+ if (!byId.has(parent)) continue;
546
+ indegree.set(event.eventId, (indegree.get(event.eventId) ?? 0) + 1);
547
+ children.set(parent, [...children.get(parent) ?? [], event.eventId]);
548
+ }
549
+ }
550
+ const ready = events.filter((event) => indegree.get(event.eventId) === 0).map((event) => event.eventId).sort();
551
+ const ordered = [];
552
+ while (ready.length > 0) {
553
+ const eventId = ready.shift();
554
+ const event = byId.get(eventId);
555
+ if (!event) continue;
556
+ ordered.push(event);
557
+ for (const childId of (children.get(eventId) ?? []).sort()) {
558
+ const next = (indegree.get(childId) ?? 0) - 1;
559
+ indegree.set(childId, next);
560
+ if (next === 0) {
561
+ ready.push(childId);
562
+ ready.sort();
563
+ }
564
+ }
565
+ }
566
+ const orderedIds = new Set(ordered.map((event) => event.eventId));
567
+ return { ordered, cyclic: new Set(events.filter((event) => !orderedIds.has(event.eventId)).map((event) => event.eventId)) };
568
+ }
569
+ function hasAcceptedAncestor(event, byId, accepted, predicate) {
570
+ const pending = [...event.parents];
571
+ const seen = /* @__PURE__ */ new Set();
572
+ while (pending.length > 0) {
573
+ const eventId = pending.pop();
574
+ if (seen.has(eventId)) continue;
575
+ seen.add(eventId);
576
+ const candidate = byId.get(eventId);
577
+ if (!candidate || !accepted.has(eventId)) continue;
578
+ if (predicate(candidate)) return true;
579
+ pending.push(...candidate.parents);
580
+ }
581
+ return false;
582
+ }
583
+ function attemptChainError(event, byId, accepted) {
584
+ const payload = event.payload;
585
+ if (!("attemptId" in payload) || payload.kind === "action.requested") return void 0;
586
+ if (payload.kind === "receipt.persisted") {
587
+ return hasAcceptedAncestor(event, byId, accepted, (candidate) => candidate.payload.kind === "action.succeeded" && candidate.payload.attemptId === payload.attemptId) ? void 0 : "missing_success_ancestor";
588
+ }
589
+ if (!("stepId" in payload)) return void 0;
590
+ const sameAttemptAndStep = (candidate) => {
591
+ const candidatePayload = candidate.payload;
592
+ return "attemptId" in candidatePayload && "stepId" in candidatePayload && candidatePayload.attemptId === payload.attemptId && candidatePayload.stepId === payload.stepId;
593
+ };
594
+ if (payload.kind === "action.outcome_emitted") {
595
+ return hasAcceptedAncestor(event, byId, accepted, (candidate) => {
596
+ if (!sameAttemptAndStep(candidate) || candidate.payload.kind !== "action.succeeded") return false;
597
+ return (candidate.payload.outcomes ?? []).some(
598
+ (outcome) => outcome.name === payload.name && outcome.payloadDigest === payload.payloadDigest && canonicalizeJson(outcome.payload) === canonicalizeJson(payload.payload)
599
+ );
600
+ }) ? void 0 : "missing_declaring_success_ancestor";
601
+ }
602
+ if (payload.kind === "action.started" || payload.kind === "action.effect_armed" || payload.kind === "action.approval_proposed") {
603
+ return hasAcceptedAncestor(event, byId, accepted, (candidate) => sameAttemptAndStep(candidate) && candidate.payload.kind === "action.requested") ? void 0 : "missing_request_ancestor";
604
+ }
605
+ if (payload.kind === "action.failed_before_effect") {
606
+ return hasAcceptedAncestor(event, byId, accepted, (candidate) => sameAttemptAndStep(candidate) && candidate.payload.kind === "action.started") ? void 0 : "missing_started_ancestor";
607
+ }
608
+ if (payload.kind === "action.succeeded") {
609
+ const hasStarted = hasAcceptedAncestor(event, byId, accepted, (candidate) => sameAttemptAndStep(candidate) && candidate.payload.kind === "action.started");
610
+ const hasArmed = hasAcceptedAncestor(event, byId, accepted, (candidate) => sameAttemptAndStep(candidate) && candidate.payload.kind === "action.effect_armed");
611
+ const hasClaimKey = payload.claimKey !== void 0;
612
+ const hasFencingEpoch = payload.fencingEpoch !== void 0;
613
+ if (hasClaimKey !== hasFencingEpoch) return "incomplete_fence_evidence";
614
+ if (hasClaimKey && hasFencingEpoch) {
615
+ return hasAcceptedAncestor(
616
+ event,
617
+ byId,
618
+ accepted,
619
+ (candidate) => sameAttemptAndStep(candidate) && candidate.payload.kind === "action.effect_armed" && candidate.payload.claimKey === payload.claimKey && candidate.payload.fencingEpoch === payload.fencingEpoch
620
+ ) ? void 0 : "missing_matching_fence_ancestor";
621
+ }
622
+ if (hasArmed && !hasStarted) return "missing_fence_evidence";
623
+ return hasStarted ? void 0 : "missing_execution_ancestor";
624
+ }
625
+ if (payload.kind === "action.needs_verification") {
626
+ return hasAcceptedAncestor(
627
+ event,
628
+ byId,
629
+ accepted,
630
+ (candidate) => sameAttemptAndStep(candidate) && (candidate.payload.kind === "action.started" || candidate.payload.kind === "action.effect_armed")
631
+ ) ? void 0 : "missing_execution_ancestor";
632
+ }
633
+ return void 0;
634
+ }
635
+ var DISPOSITION_RANK = {
636
+ not_started: 0,
637
+ armed: 1,
638
+ failed_before_effect: 2,
639
+ needs_verification: 3,
640
+ succeeded: 4
641
+ };
642
+ function compareCodeUnits(left, right) {
643
+ return left < right ? -1 : left > right ? 1 : 0;
644
+ }
645
+ function sortedUnique(values) {
646
+ return [...new Set(values)].sort(compareCodeUnits);
647
+ }
648
+ function sameStringSet(left, right) {
649
+ return canonicalizeJson(sortedUnique(left)) === canonicalizeJson(sortedUnique(right));
650
+ }
651
+ function acceptedFrontier(events, accepted) {
652
+ const acceptedEvents = events.filter((event) => accepted.has(event.eventId));
653
+ const referencedParents = new Set(acceptedEvents.flatMap((event) => event.parents.filter((parent) => accepted.has(parent))));
654
+ return acceptedEvents.map((event) => event.eventId).filter((eventId) => !referencedParents.has(eventId)).sort(compareCodeUnits);
655
+ }
656
+ function reduceFlowEvents(genesis, input) {
657
+ const unique = /* @__PURE__ */ new Map();
658
+ for (const event of input) if (!unique.has(event.eventId)) unique.set(event.eventId, event);
659
+ const events = [...unique.values()];
660
+ const canonicalDefinition = canonicalizeJson(genesis.definition);
661
+ const belongsToRun = (event) => event.runId === genesis.runId && canonicalizeJson(event.definition) === canonicalDefinition;
662
+ const runEvents = events.filter(belongsToRun);
663
+ const byId = new Map(events.map((event) => [event.eventId, event]));
664
+ const { ordered, cyclic } = causalOrder(events, byId);
665
+ const commandFingerprints = /* @__PURE__ */ new Map();
666
+ const attemptSteps = /* @__PURE__ */ new Map();
667
+ const runGenesisValues = new Set(
668
+ runEvents.filter((event) => event.payload.kind === "run.started").map((event) => event.payload.kind === "run.started" ? canonicalizeJson(event.payload.genesis) : "")
669
+ );
670
+ const canonicalGenesis = canonicalizeJson(genesis);
671
+ for (const event of runEvents) {
672
+ const fingerprints = commandFingerprints.get(event.idempotencyKey) ?? /* @__PURE__ */ new Set();
673
+ fingerprints.add(event.commandFingerprint);
674
+ commandFingerprints.set(event.idempotencyKey, fingerprints);
675
+ if ("attemptId" in event.payload && "stepId" in event.payload) {
676
+ const steps = attemptSteps.get(event.payload.attemptId) ?? /* @__PURE__ */ new Set();
677
+ steps.add(event.payload.stepId);
678
+ attemptSteps.set(event.payload.attemptId, steps);
679
+ }
680
+ }
681
+ const attempts = /* @__PURE__ */ new Map();
682
+ const accepted = [];
683
+ const acceptedSet = /* @__PURE__ */ new Set();
684
+ const invalid = [];
685
+ const invalidReasons = /* @__PURE__ */ new Map();
686
+ const cancelEvents = [];
687
+ const finalizationEvents = [];
688
+ const cycleEvents = events.filter((event) => cyclic.has(event.eventId)).sort((left, right) => compareCodeUnits(left.eventId, right.eventId));
689
+ for (const event of [...ordered, ...cycleEvents]) {
690
+ let reason;
691
+ if (!belongsToRun(event)) reason = "run_or_definition_mismatch";
692
+ if (!reason && event.payload.kind === "run.started" && runGenesisValues.size > 1) reason = "run_genesis_conflict";
693
+ if (!reason && event.payload.kind === "run.started" && canonicalizeJson(event.payload.genesis) !== canonicalGenesis) {
694
+ reason = "run_genesis_mismatch";
695
+ }
696
+ if (!reason && (commandFingerprints.get(event.idempotencyKey)?.size ?? 0) > 1) reason = "idempotency_fingerprint_conflict";
697
+ if (!reason && event.parents.some((parent) => !byId.has(parent))) reason = "missing_parent";
698
+ if (!reason && cyclic.has(event.eventId)) reason = "causal_cycle";
699
+ if (!reason && "attemptId" in event.payload && (attemptSteps.get(event.payload.attemptId)?.size ?? 0) > 1) reason = "attempt_step_conflict";
700
+ if (!reason && event.parents.some((parent) => invalidReasons.has(parent))) reason = "invalid_parent";
701
+ if (!reason) reason = attemptChainError(event, byId, acceptedSet);
702
+ if (!reason && event.payload.kind !== "log" && hasAcceptedAncestor(event, byId, acceptedSet, (candidate) => candidate.payload.kind === "run.finalized")) {
703
+ reason = "event_descends_from_finalization";
704
+ }
705
+ if (!reason && event.payload.kind === "action.requested") {
706
+ const causallyCancelled = cancelEvents.some((cancel) => eventHasAncestor(event, cancel.eventId, byId));
707
+ if (causallyCancelled) reason = "action_descends_from_cancellation";
708
+ }
709
+ if (reason) {
710
+ invalid.push({ eventId: event.eventId, reason });
711
+ invalidReasons.set(event.eventId, reason);
712
+ continue;
713
+ }
714
+ accepted.push(event.eventId);
715
+ acceptedSet.add(event.eventId);
716
+ const payload = event.payload;
717
+ if (payload.kind === "run.cancel_requested") cancelEvents.push(event);
718
+ if (payload.kind === "run.finalized") finalizationEvents.push(event);
719
+ if (!("attemptId" in payload)) continue;
720
+ const current = attempts.get(payload.attemptId) ?? {
721
+ attemptId: payload.attemptId,
722
+ stepId: "stepId" in payload ? payload.stepId : "",
723
+ disposition: "not_started",
724
+ receiptIds: [],
725
+ outcomes: []
726
+ };
727
+ let next = current;
728
+ if (payload.kind === "action.effect_armed" && DISPOSITION_RANK[current.disposition] < DISPOSITION_RANK.armed) {
729
+ next = { ...current, stepId: payload.stepId, disposition: "armed" };
730
+ }
731
+ if (payload.kind === "action.succeeded") {
732
+ next = { ...current, stepId: payload.stepId, disposition: "succeeded", outputDigest: payload.outputDigest, providerCorrelation: payload.providerCorrelation };
733
+ }
734
+ if (payload.kind === "action.failed_before_effect" && DISPOSITION_RANK[current.disposition] < DISPOSITION_RANK.failed_before_effect) {
735
+ next = { ...current, stepId: payload.stepId, disposition: "failed_before_effect" };
736
+ }
737
+ if (payload.kind === "action.needs_verification" && DISPOSITION_RANK[current.disposition] < DISPOSITION_RANK.needs_verification) {
738
+ next = { ...current, stepId: payload.stepId, disposition: "needs_verification", providerCorrelation: payload.providerCorrelation };
739
+ }
740
+ if (payload.kind === "receipt.persisted") {
741
+ next = { ...current, receiptIds: [.../* @__PURE__ */ new Set([...current.receiptIds, payload.receiptId])].sort() };
742
+ }
743
+ if (payload.kind === "action.outcome_emitted") {
744
+ const outcomes = [...current.outcomes, { name: payload.name, payload: payload.payload, payloadDigest: payload.payloadDigest }];
745
+ next = {
746
+ ...current,
747
+ outcomes: outcomes.filter((outcome, index) => outcomes.findIndex((candidate) => candidate.name === outcome.name && candidate.payloadDigest === outcome.payloadDigest) === index).sort((left, right) => compareCodeUnits(left.name, right.name) || compareCodeUnits(left.payloadDigest, right.payloadDigest))
748
+ };
749
+ }
750
+ attempts.set(payload.attemptId, next);
751
+ }
752
+ const values = [...attempts.values()];
753
+ const unresolved = values.some((attempt) => attempt.disposition === "armed" || attempt.disposition === "needs_verification");
754
+ const completedSteps = new Set(values.filter((attempt) => attempt.disposition === "succeeded").map((attempt) => attempt.stepId));
755
+ const completed = genesis.requiredStepIds.every((stepId) => completedSteps.has(stepId));
756
+ const failed = values.some((attempt) => attempt.disposition === "failed_before_effect");
757
+ const cancelRequested = cancelEvents.length > 0;
758
+ const active = values.some((attempt) => attempt.disposition === "not_started" || attempt.disposition === "armed");
759
+ const acceptedStateEvents = new Set(
760
+ accepted.filter((eventId) => {
761
+ const kind = byId.get(eventId)?.payload.kind;
762
+ return kind !== "run.finalized" && kind !== "log";
763
+ })
764
+ );
765
+ const frontierEventIds = acceptedFrontier(events, acceptedStateEvents);
766
+ const hasAcceptedStart = [...acceptedStateEvents].some((eventId) => byId.get(eventId)?.payload.kind === "run.started");
767
+ const missingTopicReceipt = genesis.topicBindingId !== void 0 && values.some((attempt) => attempt.disposition === "succeeded" && attempt.receiptIds.length === 0);
768
+ const missingDeclaredOutcome = accepted.some((eventId) => {
769
+ const success = byId.get(eventId);
770
+ if (success?.payload.kind !== "action.succeeded") return false;
771
+ const successPayload = success.payload;
772
+ return (successPayload.outcomes ?? []).some(
773
+ (declared) => !accepted.some((candidateId) => {
774
+ const candidate = byId.get(candidateId);
775
+ return candidate?.payload.kind === "action.outcome_emitted" && candidate.payload.attemptId === successPayload.attemptId && candidate.payload.stepId === successPayload.stepId && candidate.payload.name === declared.name && candidate.payload.payloadDigest === declared.payloadDigest && canonicalizeJson(candidate.payload.payload) === canonicalizeJson(declared.payload) && eventHasAncestor(candidate, success.eventId, byId);
776
+ })
777
+ );
778
+ });
779
+ let finalizableStatus;
780
+ if (hasAcceptedStart && !unresolved && !missingTopicReceipt && !missingDeclaredOutcome) {
781
+ if (completed) finalizableStatus = "completed";
782
+ else if (cancelRequested && !active) finalizableStatus = "cancelled";
783
+ else if (failed && !active) finalizableStatus = "failed";
784
+ }
785
+ const finalizationSummary = finalizableStatus ? {
786
+ kind: "qi.flow.run-finalization-summary",
787
+ schemaVersion: "1.0",
788
+ status: finalizableStatus,
789
+ cancelRequested,
790
+ requiredStepIds: sortedUnique(genesis.requiredStepIds),
791
+ frontierEventIds,
792
+ attempts: values.map((attempt) => ({
793
+ attemptId: attempt.attemptId,
794
+ stepId: attempt.stepId,
795
+ disposition: attempt.disposition,
796
+ receiptIds: sortedUnique(attempt.receiptIds)
797
+ })).sort((left, right) => compareCodeUnits(left.attemptId, right.attemptId))
798
+ } : void 0;
799
+ const validFinalizationIds = [];
800
+ for (const event of finalizationEvents) {
801
+ if (invalidReasons.has(event.eventId) || event.payload.kind !== "run.finalized") continue;
802
+ let reason;
803
+ if (!sameStringSet(event.parents, frontierEventIds)) reason = "incomplete_finalization_frontier";
804
+ else if (!finalizableStatus || !finalizationSummary) reason = "run_not_finalizable";
805
+ else if (event.payload.status !== finalizableStatus) reason = "finalization_status_mismatch";
806
+ else if (canonicalizeJson(event.payload.summary) !== canonicalizeJson(finalizationSummary)) {
807
+ reason = "finalization_summary_mismatch";
808
+ }
809
+ if (reason) {
810
+ invalid.push({ eventId: event.eventId, reason });
811
+ invalidReasons.set(event.eventId, reason);
812
+ } else {
813
+ validFinalizationIds.push(event.eventId);
814
+ }
815
+ }
816
+ let status = acceptedStateEvents.size === 0 ? "queued" : "running";
817
+ if (unresolved) status = "needs_verification";
818
+ else if (validFinalizationIds.length > 0 && finalizableStatus) status = finalizableStatus;
819
+ else if (cancelRequested) status = "cancelling";
820
+ const validAccepted = accepted.filter((eventId) => !invalidReasons.has(eventId));
821
+ return {
822
+ runId: genesis.runId,
823
+ definition: genesis.definition,
824
+ status,
825
+ attempts: Object.fromEntries([...attempts.entries()].sort(([left], [right]) => compareCodeUnits(left, right))),
826
+ cancelRequested,
827
+ frontierEventIds,
828
+ ...finalizableStatus && finalizationSummary ? { finalizationCandidate: { status: finalizableStatus, summary: finalizationSummary } } : {},
829
+ finalizedEventIds: validFinalizationIds.sort(compareCodeUnits),
830
+ acceptedEventIds: validAccepted.sort(compareCodeUnits),
831
+ invalidEvents: invalid.sort((left, right) => compareCodeUnits(left.eventId, right.eventId))
832
+ };
833
+ }
834
+ async function fingerprintFlowCommand(command) {
835
+ return await digestCanonicalJson(command);
836
+ }
837
+
838
+ // src/core/lib/flowEngine/vnext/effectClaims.ts
839
+ var EffectClaimTransitionError = class extends Error {
840
+ constructor(code, message) {
841
+ super(message);
842
+ this.code = code;
843
+ this.name = "EffectClaimTransitionError";
844
+ }
845
+ };
846
+ function claimEffect(existing, request, now) {
847
+ if (existing?.fingerprint !== void 0 && existing.fingerprint !== request.admission.commandFingerprint) {
848
+ return { outcome: "conflict", record: existing, reason: "Idempotency key already belongs to a different command fingerprint" };
849
+ }
850
+ if (existing && existing.providerIdempotencyKey !== request.providerIdempotencyKey) {
851
+ return { outcome: "conflict", record: existing, reason: "Effect claim already belongs to a different provider idempotency key" };
852
+ }
853
+ if (existing) {
854
+ const recovery = existing.status === "armed" || existing.status === "needs_verification" || existing.status === "success_prepared";
855
+ if (recovery) {
856
+ if (existing.leaseExpiresAt > now) return { outcome: "existing", record: existing };
857
+ return {
858
+ outcome: "claimed",
859
+ record: {
860
+ ...existing,
861
+ leaseOwner: request.leaseOwner,
862
+ // A prepared success has already consumed the effect fence. Recovery
863
+ // only drains its immutable result evidence into Matrix.
864
+ fencingEpoch: existing.status === "success_prepared" ? existing.fencingEpoch : existing.fencingEpoch + 1,
865
+ leaseExpiresAt: now + request.leaseTtlMs,
866
+ policyDigest: request.policyDigest,
867
+ updatedAt: now
868
+ }
869
+ };
870
+ }
871
+ if (existing.status !== "claimed") {
872
+ return { outcome: "existing", record: existing };
873
+ }
874
+ if (existing.leaseExpiresAt > now) return { outcome: "existing", record: existing };
875
+ if (request.admission.policy.mode !== "enabled") {
876
+ return {
877
+ outcome: "claimed",
878
+ record: {
879
+ ...existing,
880
+ leaseOwner: request.leaseOwner,
881
+ fencingEpoch: existing.fencingEpoch + 1,
882
+ leaseExpiresAt: now + request.leaseTtlMs,
883
+ policyDigest: request.policyDigest,
884
+ updatedAt: now
885
+ }
886
+ };
887
+ }
888
+ }
889
+ if (request.admission.policy.mode !== "enabled") return { outcome: "paused", record: existing ?? void 0, reason: "Execution policy pauses new effects" };
890
+ return {
891
+ outcome: "claimed",
892
+ record: {
893
+ kind: "qi.flow.effect-claim",
894
+ schemaVersion: "1.0",
895
+ claimKey: request.claimKey,
896
+ fingerprint: request.admission.commandFingerprint,
897
+ status: "claimed",
898
+ leaseOwner: request.leaseOwner,
899
+ fencingEpoch: (existing?.fencingEpoch ?? 0) + 1,
900
+ leaseExpiresAt: now + request.leaseTtlMs,
901
+ providerIdempotencyKey: request.providerIdempotencyKey,
902
+ policyDigest: request.policyDigest,
903
+ updatedAt: now
904
+ }
905
+ };
906
+ }
907
+ function assertFence(record, owner, epoch, now) {
908
+ if (record.leaseOwner !== owner || record.fencingEpoch !== epoch) {
909
+ throw new EffectClaimTransitionError("STALE_FENCE", "Effect claim owner or fencing epoch is stale");
910
+ }
911
+ if (record.leaseExpiresAt <= now) throw new EffectClaimTransitionError("STALE_FENCE", "Effect claim lease has expired");
912
+ }
913
+ function renewEffectClaim(record, owner, epoch, leaseTtlMs, now) {
914
+ assertFence(record, owner, epoch, now);
915
+ if (record.status !== "claimed") throw new EffectClaimTransitionError("INVALID_TRANSITION", "Only an unarmed claim can renew its lease");
916
+ return { ...record, leaseExpiresAt: now + leaseTtlMs, updatedAt: now };
917
+ }
918
+ function armEffectClaim(record, owner, epoch, now, providerCorrelation) {
919
+ assertFence(record, owner, epoch, now);
920
+ if (record.status === "armed" && record.providerCorrelation === providerCorrelation) return record;
921
+ if (record.status !== "claimed") throw new EffectClaimTransitionError("INVALID_TRANSITION", "Only a claimed effect can be armed");
922
+ return { ...record, status: "armed", ...providerCorrelation !== void 0 ? { providerCorrelation } : {}, updatedAt: now };
923
+ }
924
+ function prepareEffectSuccess(record, owner, epoch, outputDigest2, outcomesDigest, now, providerCorrelation) {
925
+ assertFence(record, owner, epoch, now);
926
+ if (record.status === "success_prepared") {
927
+ if (record.outputDigest !== outputDigest2 || record.outcomesDigest !== outcomesDigest) {
928
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Prepared effect success has different result evidence");
929
+ }
930
+ return record;
931
+ }
932
+ if (record.status !== "armed" && record.status !== "needs_verification") {
933
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Only an armed or verified effect can prepare success");
934
+ }
935
+ const nextCorrelation = providerCorrelation ?? record.providerCorrelation;
936
+ return {
937
+ ...record,
938
+ status: "success_prepared",
939
+ outputDigest: outputDigest2,
940
+ outcomesDigest,
941
+ ...nextCorrelation !== void 0 ? { providerCorrelation: nextCorrelation } : {},
942
+ updatedAt: now
943
+ };
944
+ }
945
+ function resolveEffectClaim(record, owner, epoch, outcome, now, providerCorrelation, successEventId) {
946
+ if (outcome === "failed_before_effect" && successEventId !== void 0) {
947
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Failed-before-effect resolution cannot include success evidence");
948
+ }
949
+ if (record.status === outcome) {
950
+ const expectedCorrelation = providerCorrelation ?? record.providerCorrelation;
951
+ const sameCorrelation = record.providerCorrelation === expectedCorrelation;
952
+ const sameSuccess = outcome !== "succeeded" || record.successEventId === successEventId;
953
+ if (record.leaseOwner === owner && record.fencingEpoch === epoch && sameCorrelation && sameSuccess) return record;
954
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Resolved effect evidence does not match the existing terminal record");
955
+ }
956
+ assertFence(record, owner, epoch, now);
957
+ if (outcome === "failed_before_effect" && record.status !== "claimed") {
958
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "An armed effect cannot be reported as failed before effect");
959
+ }
960
+ if (outcome === "succeeded" && (record.status !== "success_prepared" || !record.outputDigest || !record.outcomesDigest)) {
961
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Effect success must be prepared before it can be finalized");
962
+ }
963
+ if (outcome === "succeeded" && !successEventId) {
964
+ throw new EffectClaimTransitionError("INVALID_TRANSITION", "Effect success requires its durable Matrix event id");
965
+ }
966
+ const nextCorrelation = providerCorrelation ?? record.providerCorrelation;
967
+ return {
968
+ ...record,
969
+ status: outcome,
970
+ ...nextCorrelation !== void 0 ? { providerCorrelation: nextCorrelation } : {},
971
+ ...successEventId ? { successEventId } : {},
972
+ updatedAt: now
973
+ };
974
+ }
975
+ function markEffectNeedsVerification(record, owner, epoch, now, providerCorrelation) {
976
+ assertFence(record, owner, epoch, now);
977
+ if (record.status === "needs_verification" && record.providerCorrelation === (providerCorrelation ?? record.providerCorrelation)) return record;
978
+ if (record.status !== "armed") throw new EffectClaimTransitionError("INVALID_TRANSITION", "Only an armed effect can become ambiguous");
979
+ const nextCorrelation = providerCorrelation ?? record.providerCorrelation;
980
+ return { ...record, status: "needs_verification", ...nextCorrelation !== void 0 ? { providerCorrelation: nextCorrelation } : {}, updatedAt: now };
981
+ }
982
+
983
+ // src/core/lib/actionRegistry/manifestV2.ts
984
+ var import__ = __toESM(require("ajv/dist/2020.js"), 1);
985
+
986
+ // src/core/lib/actionRegistry/manifestV2.schema.ts
987
+ var ACTION_MANIFEST_V2_SCHEMA = {
988
+ $schema: "https://json-schema.org/draft/2020-12/schema",
989
+ $id: "https://ixo.world/schemas/qi/action-manifest-v2.schema.json",
990
+ type: "object",
991
+ additionalProperties: false,
992
+ required: ["manifestVersion", "manifestId", "generatedAt", "package", "issuer", "compatibility", "actions", "primitives", "integrity"],
993
+ properties: {
994
+ manifestVersion: { const: "2.0" },
995
+ manifestId: { type: "string", minLength: 1 },
996
+ generatedAt: {
997
+ type: "string",
998
+ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$"
999
+ },
1000
+ package: {
1001
+ type: "object",
1002
+ additionalProperties: false,
1003
+ required: ["name", "version", "sourceCommit"],
1004
+ properties: {
1005
+ name: { type: "string", minLength: 1 },
1006
+ version: { type: "string", minLength: 1 },
1007
+ sourceCommit: { type: "string", minLength: 1 },
1008
+ buildId: { type: "string", minLength: 1 },
1009
+ distributionUrl: { type: "string", pattern: "^[a-zA-Z][a-zA-Z0-9+.-]*:" }
1010
+ }
1011
+ },
1012
+ issuer: {
1013
+ type: "object",
1014
+ additionalProperties: false,
1015
+ required: ["did", "verificationMethod"],
1016
+ properties: {
1017
+ did: { type: "string", pattern: "^did:[a-z0-9]+:.+" },
1018
+ verificationMethod: { type: "string", pattern: "^did:[a-z0-9]+:.+#.+" }
1019
+ }
1020
+ },
1021
+ compatibility: {
1022
+ type: "object",
1023
+ additionalProperties: false,
1024
+ required: ["engine", "flowSchemaVersions", "features"],
1025
+ properties: {
1026
+ engine: {
1027
+ type: "object",
1028
+ additionalProperties: false,
1029
+ required: ["versionRange"],
1030
+ properties: {
1031
+ versionRange: { type: "string", minLength: 1 }
1032
+ }
1033
+ },
1034
+ flowSchemaVersions: {
1035
+ type: "array",
1036
+ minItems: 1,
1037
+ uniqueItems: true,
1038
+ items: { type: "string", minLength: 1 }
1039
+ },
1040
+ features: {
1041
+ type: "array",
1042
+ minItems: 1,
1043
+ uniqueItems: true,
1044
+ items: { type: "string", minLength: 1 }
1045
+ }
1046
+ }
1047
+ },
1048
+ actions: {
1049
+ type: "array",
1050
+ items: { $ref: "#/$defs/contract" }
1051
+ },
1052
+ primitives: {
1053
+ type: "array",
1054
+ items: { $ref: "#/$defs/contract" }
1055
+ },
1056
+ integrity: {
1057
+ type: "object",
1058
+ additionalProperties: false,
1059
+ required: ["canonicalization", "digest", "signature"],
1060
+ properties: {
1061
+ canonicalization: { const: "RFC8785" },
1062
+ digest: {
1063
+ type: "object",
1064
+ additionalProperties: false,
1065
+ required: ["algorithm", "value"],
1066
+ properties: {
1067
+ algorithm: { const: "SHA-256" },
1068
+ value: { type: "string", pattern: "^sha256:[0-9a-f]{64}$" }
1069
+ }
1070
+ },
1071
+ signature: {
1072
+ type: "object",
1073
+ additionalProperties: false,
1074
+ required: ["algorithm", "verificationMethod", "value"],
1075
+ properties: {
1076
+ algorithm: { type: "string", minLength: 1 },
1077
+ verificationMethod: { type: "string", pattern: "^did:[a-z0-9]+:.+#.+" },
1078
+ value: { type: "string", minLength: 1 }
1079
+ }
1080
+ }
1081
+ }
1082
+ }
1083
+ },
1084
+ $defs: {
1085
+ contract: {
1086
+ type: "object",
1087
+ required: ["type", "contractVersion"],
1088
+ properties: {
1089
+ type: { type: "string", minLength: 1 },
1090
+ contractVersion: { type: "string", minLength: 1 },
1091
+ aliases: {
1092
+ type: "array",
1093
+ uniqueItems: true,
1094
+ items: { type: "string", minLength: 1 }
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ };
1100
+
1101
+ // src/core/lib/actionRegistry/manifestV2.ts
1102
+ var ActionManifestV2VerificationError = class extends Error {
1103
+ constructor(code, message) {
1104
+ super(message);
1105
+ this.name = "ActionManifestV2VerificationError";
1106
+ this.code = code;
1107
+ }
1108
+ };
1109
+ var validateSignedManifest = new import__.default({ allErrors: true, strict: false }).compile(ACTION_MANIFEST_V2_SCHEMA);
1110
+ var SIGNATURE_DOMAIN = "qi.action-manifest.v2\0";
1111
+ function isPlainObject2(value) {
1112
+ const prototype = Object.getPrototypeOf(value);
1113
+ return prototype === Object.prototype || prototype === null;
1114
+ }
1115
+ function assertValidUnicode2(value) {
1116
+ for (let index = 0; index < value.length; index += 1) {
1117
+ const codeUnit = value.charCodeAt(index);
1118
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
1119
+ const next = value.charCodeAt(index + 1);
1120
+ if (!(next >= 56320 && next <= 57343)) {
1121
+ throw new TypeError("Manifest v2 contains an unpaired Unicode surrogate");
1122
+ }
1123
+ index += 1;
1124
+ } else if (codeUnit >= 56320 && codeUnit <= 57343) {
1125
+ throw new TypeError("Manifest v2 contains an unpaired Unicode surrogate");
1126
+ }
1127
+ }
1128
+ }
1129
+ function canonicalizeManifestV2Payload(payload) {
1130
+ const ancestors = /* @__PURE__ */ new Set();
1131
+ const serialize = (value) => {
1132
+ if (value === null || typeof value === "boolean") {
1133
+ return JSON.stringify(value);
1134
+ }
1135
+ if (typeof value === "string") {
1136
+ assertValidUnicode2(value);
1137
+ return JSON.stringify(value);
1138
+ }
1139
+ if (typeof value === "number") {
1140
+ if (!Number.isFinite(value)) {
1141
+ throw new TypeError("Manifest v2 contains a non-finite number");
1142
+ }
1143
+ return JSON.stringify(value);
1144
+ }
1145
+ if (typeof value !== "object") {
1146
+ throw new TypeError(`Manifest v2 contains a non-JSON value: ${typeof value}`);
1147
+ }
1148
+ if (ancestors.has(value)) {
1149
+ throw new TypeError("Manifest v2 contains a circular reference");
1150
+ }
1151
+ ancestors.add(value);
1152
+ try {
1153
+ if (Array.isArray(value)) {
1154
+ return `[${value.map((entry) => serialize(entry)).join(",")}]`;
1155
+ }
1156
+ if (!isPlainObject2(value)) {
1157
+ throw new TypeError("Manifest v2 contains a non-plain object");
1158
+ }
1159
+ return `{${Object.keys(value).sort().map((key) => {
1160
+ assertValidUnicode2(key);
1161
+ return `${JSON.stringify(key)}:${serialize(value[key])}`;
1162
+ }).join(",")}}`;
1163
+ } finally {
1164
+ ancestors.delete(value);
1165
+ }
1166
+ };
1167
+ return serialize(payload);
1168
+ }
1169
+ async function computeActionManifestV2Digest(payload) {
1170
+ if (!globalThis.crypto?.subtle) {
1171
+ throw new Error("Web Crypto is required to digest an Action Manifest v2 contract");
1172
+ }
1173
+ const canonicalPayload = canonicalizeManifestV2Payload(payload);
1174
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalPayload));
1175
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1176
+ return `sha256:${hex}`;
1177
+ }
1178
+ function signatureInput3(digest) {
1179
+ return new TextEncoder().encode(`${SIGNATURE_DOMAIN}${digest}`);
1180
+ }
1181
+ function schemaFailure() {
1182
+ const details = (validateSignedManifest.errors || []).map((error) => `${error.instancePath || "/"} ${error.message || "is invalid"}`).join("; ");
1183
+ return new ActionManifestV2VerificationError("INVALID_MANIFEST", details ? `Action Manifest v2 is invalid: ${details}` : "Action Manifest v2 is invalid");
1184
+ }
1185
+ function payloadFromSignedManifest(manifest) {
1186
+ const { integrity: _integrity, ...payload } = manifest;
1187
+ return payload;
1188
+ }
1189
+ function assertContractIdentities(payload) {
1190
+ const contracts = [...payload.actions, ...payload.primitives];
1191
+ const canonicalTypes = /* @__PURE__ */ new Set();
1192
+ for (const contract of contracts) {
1193
+ if (canonicalTypes.has(contract.type)) {
1194
+ throw new ActionManifestV2VerificationError("DUPLICATE_CONTRACT_TYPE", `Manifest contains duplicate canonical contract type: ${contract.type}`);
1195
+ }
1196
+ canonicalTypes.add(contract.type);
1197
+ }
1198
+ for (const [groupName, group] of [
1199
+ ["actions", payload.actions],
1200
+ ["primitives", payload.primitives]
1201
+ ]) {
1202
+ for (let index = 1; index < group.length; index += 1) {
1203
+ if (group[index - 1].type > group[index].type) {
1204
+ throw new ActionManifestV2VerificationError("UNSORTED_CONTRACTS", `Manifest ${groupName} must be sorted by canonical type`);
1205
+ }
1206
+ }
1207
+ }
1208
+ const claimedNames = new Map(Array.from(canonicalTypes, (type) => [type, type]));
1209
+ for (const contract of contracts) {
1210
+ const aliases = contract.aliases;
1211
+ if (!Array.isArray(aliases)) continue;
1212
+ for (const alias of aliases) {
1213
+ const existingOwner = claimedNames.get(alias);
1214
+ if (existingOwner) {
1215
+ throw new ActionManifestV2VerificationError("AMBIGUOUS_ALIAS", `Manifest alias ${alias} conflicts with contract ${existingOwner}`);
1216
+ }
1217
+ claimedNames.set(alias, contract.type);
1218
+ }
1219
+ }
1220
+ }
1221
+ function deepFreeze(value) {
1222
+ for (const child of Object.values(value)) {
1223
+ if (typeof child === "object" && child !== null && !Object.isFrozen(child)) {
1224
+ deepFreeze(child);
1225
+ }
1226
+ }
1227
+ return Object.freeze(value);
1228
+ }
1229
+ async function verifyActionManifestV2(candidate, trustPolicy) {
1230
+ if (typeof candidate !== "object" || candidate === null || !("manifestVersion" in candidate) || candidate.manifestVersion !== "2.0") {
1231
+ throw new ActionManifestV2VerificationError("UNSUPPORTED_MANIFEST_VERSION", "Only Action Manifest version 2.0 can cross this execution boundary");
1232
+ }
1233
+ if (!("integrity" in candidate) || typeof candidate.integrity !== "object") {
1234
+ throw new ActionManifestV2VerificationError("UNSIGNED_MANIFEST", "A signature and digest are required to load Action Manifest v2 for execution");
1235
+ }
1236
+ if (!validateSignedManifest(candidate)) {
1237
+ throw schemaFailure();
1238
+ }
1239
+ const manifest = candidate;
1240
+ const { issuer, integrity } = manifest;
1241
+ assertContractIdentities(manifest);
1242
+ if (!trustPolicy.trustedIssuerDids.includes(issuer.did)) {
1243
+ throw new ActionManifestV2VerificationError("UNTRUSTED_ISSUER", `Manifest issuer is not trusted: ${issuer.did}`);
1244
+ }
1245
+ if (trustPolicy.revokedIssuerDids?.includes(issuer.did)) {
1246
+ throw new ActionManifestV2VerificationError("REVOKED_ISSUER", `Manifest issuer is revoked: ${issuer.did}`);
1247
+ }
1248
+ if (integrity.signature.verificationMethod !== issuer.verificationMethod || !integrity.signature.verificationMethod.startsWith(`${issuer.did}#`)) {
1249
+ throw new ActionManifestV2VerificationError("VERIFICATION_METHOD_MISMATCH", "The signature verification method does not belong to the declared manifest issuer");
1250
+ }
1251
+ if (!trustPolicy.allowedSignatureAlgorithms.includes(integrity.signature.algorithm)) {
1252
+ throw new ActionManifestV2VerificationError("DISALLOWED_SIGNATURE_ALGORITHM", `Manifest signature algorithm is not allowed: ${integrity.signature.algorithm}`);
1253
+ }
1254
+ let digest;
1255
+ try {
1256
+ digest = await computeActionManifestV2Digest(payloadFromSignedManifest(manifest));
1257
+ } catch (error) {
1258
+ throw new ActionManifestV2VerificationError(
1259
+ "INVALID_MANIFEST",
1260
+ error instanceof Error ? `Action Manifest v2 cannot be canonicalized: ${error.message}` : "Action Manifest v2 cannot be canonicalized"
1261
+ );
1262
+ }
1263
+ if (digest !== integrity.digest.value) {
1264
+ throw new ActionManifestV2VerificationError("DIGEST_MISMATCH", "Manifest payload does not match its signed digest");
1265
+ }
1266
+ let validSignature = false;
1267
+ try {
1268
+ validSignature = await trustPolicy.verifySignature({
1269
+ issuerDid: issuer.did,
1270
+ verificationMethod: integrity.signature.verificationMethod,
1271
+ algorithm: integrity.signature.algorithm,
1272
+ data: signatureInput3(digest),
1273
+ signature: integrity.signature.value
1274
+ });
1275
+ } catch {
1276
+ validSignature = false;
1277
+ }
1278
+ if (!validSignature) {
1279
+ throw new ActionManifestV2VerificationError("INVALID_SIGNATURE", "Manifest signature verification failed");
1280
+ }
1281
+ const trustedSnapshot = JSON.parse(JSON.stringify(manifest));
1282
+ return deepFreeze(trustedSnapshot);
1283
+ }
1284
+
1285
+ // src/core/lib/flowEngine/vnext/actionContracts.ts
1286
+ var ActionContractResolutionError = class extends Error {
1287
+ constructor(code, message) {
1288
+ super(message);
1289
+ this.code = code;
1290
+ this.name = "ActionContractResolutionError";
1291
+ }
1292
+ };
1293
+ var SAFETY_CLASSES = /* @__PURE__ */ new Set(["pure", "provider_idempotent", "fenced", "approval_only"]);
1294
+ var DATA_CLASSIFICATIONS = /* @__PURE__ */ new Set(["public", "shared", "confidential", "restricted"]);
1295
+ var PROCEDURES = /* @__PURE__ */ new Set(["required", "supported", "unavailable"]);
1296
+ function object(value, field) {
1297
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1298
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${field} must be a JSON object`);
1299
+ }
1300
+ return value;
1301
+ }
1302
+ function strings(value, field) {
1303
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) {
1304
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${field} must be an array of non-empty strings`);
1305
+ }
1306
+ return [...value];
1307
+ }
1308
+ function requiredString(action, field) {
1309
+ const value = action[field];
1310
+ if (typeof value !== "string" || value.length === 0) {
1311
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type}.${field} must be a non-empty string`);
1312
+ }
1313
+ return value;
1314
+ }
1315
+ function parseActionContract(action, manifestDigest) {
1316
+ const can = requiredString(action, "can");
1317
+ const safety = requiredString(action, "safety");
1318
+ if (!SAFETY_CLASSES.has(safety)) {
1319
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type}.safety is not a supported safety class`);
1320
+ }
1321
+ const dataClassification = requiredString(action, "dataClassification");
1322
+ if (!DATA_CLASSIFICATIONS.has(dataClassification)) {
1323
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type}.dataClassification is not supported`);
1324
+ }
1325
+ const providerIdempotency = object(action.providerIdempotency, `${action.type}.providerIdempotency`);
1326
+ if (typeof providerIdempotency.supported !== "boolean") {
1327
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type}.providerIdempotency.supported must be boolean`);
1328
+ }
1329
+ const readback = requiredString(action, "readbackProcedure");
1330
+ const compensation = requiredString(action, "compensationProcedure");
1331
+ if (!PROCEDURES.has(readback) || !PROCEDURES.has(compensation)) {
1332
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type} readback and compensation procedures must be explicit`);
1333
+ }
1334
+ if ((safety === "provider_idempotent" || safety === "fenced") && readback === "unavailable") {
1335
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type} cannot perform external effects without a readback procedure`);
1336
+ }
1337
+ if (safety === "provider_idempotent" && providerIdempotency.supported !== true) {
1338
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `${action.type} declares provider idempotency without provider support`);
1339
+ }
1340
+ return {
1341
+ kind: "qi.action.contract",
1342
+ schemaVersion: "1.0",
1343
+ type: action.type,
1344
+ can,
1345
+ contractVersion: action.contractVersion,
1346
+ manifestDigest,
1347
+ inputSchema: object(action.inputSchema, `${action.type}.inputSchema`),
1348
+ outputSchema: object(action.outputSchema, `${action.type}.outputSchema`),
1349
+ safety,
1350
+ handlerVersion: requiredString(action, "handlerVersion"),
1351
+ dataClassification,
1352
+ requiredServices: strings(action.requiredServices, `${action.type}.requiredServices`),
1353
+ idempotency: {
1354
+ providerKey: providerIdempotency.supported,
1355
+ readback,
1356
+ compensation
1357
+ }
1358
+ };
1359
+ }
1360
+ async function computeActionContractDigest(contract) {
1361
+ return await digestCanonicalJson(contract);
1362
+ }
1363
+ var HistoricalManifestActionContractResolver = class {
1364
+ constructor(repository, trustPolicy) {
1365
+ this.repository = repository;
1366
+ this.trustPolicy = trustPolicy;
1367
+ this.verifiedManifests = /* @__PURE__ */ new Map();
1368
+ }
1369
+ async resolve(ref) {
1370
+ const manifest = await this.loadManifest(ref.manifestDigest);
1371
+ const action = manifest.actions.find((candidate) => candidate.type === ref.type);
1372
+ if (!action) throw new ActionContractResolutionError("ACTION_NOT_FOUND", `Action ${ref.type} is not present in ${ref.manifestDigest}`);
1373
+ if (action.contractVersion !== ref.contractVersion) {
1374
+ throw new ActionContractResolutionError("ACTION_VERSION_MISMATCH", `Action ${ref.type} contract version does not match its Flow revision`);
1375
+ }
1376
+ const unsigned = parseActionContract(action, ref.manifestDigest);
1377
+ const contractDigest = await computeActionContractDigest(unsigned);
1378
+ if (contractDigest !== ref.contractDigest) {
1379
+ throw new ActionContractResolutionError("ACTION_CONTRACT_DIGEST_MISMATCH", `Action ${ref.type} contract bytes do not match the pinned digest`);
1380
+ }
1381
+ if (unsigned.can !== ref.can) {
1382
+ throw new ActionContractResolutionError("INVALID_ACTION_CONTRACT", `Action ${ref.type} capability does not match the Flow revision`);
1383
+ }
1384
+ return Object.freeze({ ...unsigned, contractDigest });
1385
+ }
1386
+ loadManifest(digest) {
1387
+ const cached = this.verifiedManifests.get(digest);
1388
+ if (cached) return cached;
1389
+ const pending = this.verifyManifest(digest);
1390
+ this.verifiedManifests.set(digest, pending);
1391
+ pending.catch(() => this.verifiedManifests.delete(digest));
1392
+ return pending;
1393
+ }
1394
+ async verifyManifest(digest) {
1395
+ const signed = await this.repository.getByDigest(digest);
1396
+ if (!signed) throw new ActionContractResolutionError("MANIFEST_NOT_FOUND", `Historical Action manifest is unavailable: ${digest}`);
1397
+ const verified = await verifyActionManifestV2(signed, this.trustPolicy);
1398
+ if (verified.integrity.digest.value !== digest) {
1399
+ throw new ActionContractResolutionError("MANIFEST_DIGEST_MISMATCH", `Historical manifest repository returned the wrong digest for ${digest}`);
1400
+ }
1401
+ return verified;
1402
+ }
1403
+ };
1404
+
1405
+ // src/core/lib/flowEngine/vnext/peerExecutor.ts
1406
+ var import__2 = __toESM(require("ajv/dist/2020.js"), 1);
1407
+ var UNIVERSAL_ACTION_COMPLETED_OUTCOME = "step.completed";
1408
+ var PeerExecutionError = class extends Error {
1409
+ constructor(code, message) {
1410
+ super(message);
1411
+ this.code = code;
1412
+ this.name = "PeerExecutionError";
1413
+ }
1414
+ };
1415
+ function definitionRef(definition) {
1416
+ return { ...definition.ref, digest: definition.integrity.digest.value };
1417
+ }
1418
+ function proofReferences(authorization) {
1419
+ const invocations = "flow" in authorization ? [authorization.flow, authorization.action, authorization.topic, authorization.provider, authorization.effectClaim?.invocation] : [authorization];
1420
+ return [...new Set(invocations.flatMap((invocation) => invocation ? [invocation.cid, ...invocation.proofCids] : []))].sort();
1421
+ }
1422
+ function assertInvocation(invocation, expected) {
1423
+ if (invocation.audience !== expected.audience || invocation.can !== expected.can || invocation.with !== expected.with || invocation.definitionDigest !== expected.definitionDigest || invocation.actionContractDigest !== expected.actionContractDigest || invocation.idempotencyKey !== expected.idempotencyKey) {
1424
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", `Verified invocation does not authorize ${expected.can} on ${expected.with}`);
1425
+ }
1426
+ }
1427
+ function outputDigest(output) {
1428
+ return digestCanonicalJson(output);
1429
+ }
1430
+ function compareCodeUnits2(left, right) {
1431
+ return left < right ? -1 : left > right ? 1 : 0;
1432
+ }
1433
+ async function actionOutcomes(output, provided = []) {
1434
+ const inputs = [
1435
+ { name: UNIVERSAL_ACTION_COMPLETED_OUTCOME, payload: { outputDigest: output } },
1436
+ ...provided.filter((outcome) => outcome.name.trim() !== UNIVERSAL_ACTION_COMPLETED_OUTCOME)
1437
+ ];
1438
+ const outcomes = await Promise.all(
1439
+ inputs.map(async ({ name, payload }) => {
1440
+ const normalizedName = name.trim();
1441
+ if (!normalizedName) throw new PeerExecutionError("EVENT_CONFLICT", "Action outcome name cannot be empty");
1442
+ const snapshot = JSON.parse(canonicalizeJson(payload));
1443
+ return { name: normalizedName, payload: snapshot, payloadDigest: await digestCanonicalJson(snapshot) };
1444
+ })
1445
+ );
1446
+ return outcomes.filter((outcome, index) => outcomes.findIndex((candidate) => candidate.name === outcome.name && candidate.payloadDigest === outcome.payloadDigest) === index).sort((left, right) => compareCodeUnits2(left.name, right.name) || compareCodeUnits2(left.payloadDigest, right.payloadDigest));
1447
+ }
1448
+ function actionOutcomesDigest(outcomes) {
1449
+ return digestCanonicalJson(outcomes);
1450
+ }
1451
+ function canonicalSnapshot(value) {
1452
+ return deepFreezeJson(JSON.parse(canonicalizeJson(value)));
1453
+ }
1454
+ function snapshotStartCommand(command) {
1455
+ return canonicalSnapshot({
1456
+ definition: command.definition,
1457
+ launchKind: command.launchKind,
1458
+ launchNonce: command.launchNonce,
1459
+ actor: command.actor,
1460
+ issuedAt: command.issuedAt,
1461
+ idempotencyKey: command.idempotencyKey,
1462
+ authorization: command.authorization,
1463
+ ...command.topicBindingId !== void 0 ? { topicBindingId: command.topicBindingId } : {}
1464
+ });
1465
+ }
1466
+ function snapshotAttemptCommand(command) {
1467
+ return canonicalSnapshot({
1468
+ definition: command.definition,
1469
+ genesis: command.genesis,
1470
+ stepId: command.stepId,
1471
+ actor: command.actor,
1472
+ issuedAt: command.issuedAt,
1473
+ idempotencyKey: command.idempotencyKey,
1474
+ inputs: command.inputs,
1475
+ authorization: command.authorization,
1476
+ policy: command.policy,
1477
+ ...command.topicBinding ? { topicBinding: command.topicBinding } : {},
1478
+ ...command.topicRequest ? { topicRequest: command.topicRequest } : {}
1479
+ });
1480
+ }
1481
+ function snapshotCancelCommand(command) {
1482
+ return canonicalSnapshot({
1483
+ definition: command.definition,
1484
+ genesis: command.genesis,
1485
+ actor: command.actor,
1486
+ issuedAt: command.issuedAt,
1487
+ idempotencyKey: command.idempotencyKey,
1488
+ authorization: command.authorization,
1489
+ ...command.reason !== void 0 ? { reason: command.reason } : {}
1490
+ });
1491
+ }
1492
+ function snapshotFinalizeCommand(command) {
1493
+ return canonicalSnapshot({
1494
+ definition: command.definition,
1495
+ genesis: command.genesis,
1496
+ actor: command.actor,
1497
+ issuedAt: command.issuedAt,
1498
+ idempotencyKey: command.idempotencyKey,
1499
+ authorization: command.authorization
1500
+ });
1501
+ }
1502
+ function durationMs(value) {
1503
+ const match = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/u.exec(value);
1504
+ if (!match) return void 0;
1505
+ const [, days, hours, minutes] = match;
1506
+ const total = Number(days ?? 0) * 864e5 + Number(hours ?? 0) * 36e5 + Number(minutes ?? 0) * 6e4;
1507
+ return total > 0 ? total : void 0;
1508
+ }
1509
+ function assertStepWithinTtl(step, genesis, now) {
1510
+ const startedAt = Date.parse(genesis.startedAt);
1511
+ const deadlines = [];
1512
+ if (step.ttlMs !== void 0) {
1513
+ if (!Number.isFinite(startedAt)) throw new PeerExecutionError("STEP_EXPIRED", "Run start time is unavailable for the signed step TTL");
1514
+ deadlines.push(startedAt + step.ttlMs);
1515
+ }
1516
+ if (step.ttl?.absoluteDueDate) deadlines.push(Date.parse(step.ttl.absoluteDueDate));
1517
+ for (const relative of [step.ttl?.fromEnablement, step.ttl?.fromCommitment]) {
1518
+ if (!relative) continue;
1519
+ const relativeMs = durationMs(relative);
1520
+ if (!Number.isFinite(startedAt) || relativeMs === void 0) {
1521
+ throw new PeerExecutionError("STEP_EXPIRED", "The signed relative step TTL cannot be proven unexpired");
1522
+ }
1523
+ deadlines.push(startedAt + relativeMs);
1524
+ }
1525
+ if (deadlines.some((deadline) => !Number.isFinite(deadline) || now >= deadline)) {
1526
+ throw new PeerExecutionError("STEP_EXPIRED", `Flow step ${step.stepId} is outside its signed execution window`);
1527
+ }
1528
+ }
1529
+ function assertCommandTime(issuedAtValue, executionNow) {
1530
+ const issuedAt = Date.parse(issuedAtValue);
1531
+ if (!Number.isFinite(issuedAt) || issuedAt > executionNow) {
1532
+ throw new PeerExecutionError("COMMAND_TIME_INVALID", "Command time must be valid and no later than executor time");
1533
+ }
1534
+ }
1535
+ async function assertRunGenesis(definitionRevision, genesis) {
1536
+ const definition = definitionRef(definitionRevision);
1537
+ const expectedRunId = await deriveRunId(definition, genesis.launchKind, genesis.launchNonce);
1538
+ const expectedStepIds = definitionRevision.steps.map((candidate) => candidate.stepId);
1539
+ if (genesis.runId !== expectedRunId || canonicalizeJson(genesis.definition) !== canonicalizeJson(definition) || canonicalizeJson(genesis.requiredStepIds) !== canonicalizeJson(expectedStepIds) || !Number.isFinite(Date.parse(genesis.startedAt))) {
1540
+ throw new PeerExecutionError("DEFINITION_MISMATCH", "Run genesis does not match the immutable Flow definition");
1541
+ }
1542
+ return definition;
1543
+ }
1544
+ function createPeerExecutor(options) {
1545
+ const schemaCompiler = new import__2.default({ allErrors: true, strict: false });
1546
+ const validators = /* @__PURE__ */ new Map();
1547
+ function contractValidators(contract) {
1548
+ let resolved = validators.get(contract.contractDigest);
1549
+ if (!resolved) {
1550
+ try {
1551
+ const input = schemaCompiler.compile(contract.inputSchema);
1552
+ const output = schemaCompiler.compile(contract.outputSchema);
1553
+ if (input.$async || output.$async) {
1554
+ throw new Error("Asynchronous JSON Schema validation is not supported by the peer executor");
1555
+ }
1556
+ resolved = { input, output };
1557
+ } catch (error) {
1558
+ throw new PeerExecutionError("ACTION_CONTRACT_INVALID", `Pinned Action schema is invalid: ${error instanceof Error ? error.message : String(error)}`);
1559
+ }
1560
+ validators.set(contract.contractDigest, resolved);
1561
+ }
1562
+ return resolved;
1563
+ }
1564
+ function assertValidInputs(contract, inputs) {
1565
+ const validate = contractValidators(contract).input;
1566
+ if (!validate(inputs)) {
1567
+ throw new PeerExecutionError("INPUT_SCHEMA_INVALID", `Action inputs do not match the pinned schema: ${schemaCompiler.errorsText(validate.errors)}`);
1568
+ }
1569
+ }
1570
+ async function validatedOutputDigest(contract, candidate) {
1571
+ const output = canonicalSnapshot(candidate);
1572
+ const validate = contractValidators(contract).output;
1573
+ if (!validate(output)) {
1574
+ throw new PeerExecutionError("OUTPUT_SCHEMA_INVALID", `Action output does not match the pinned schema: ${schemaCompiler.errorsText(validate.errors)}`);
1575
+ }
1576
+ return outputDigest(output);
1577
+ }
1578
+ function assertExecutionWindow(command, step) {
1579
+ const executionNow = options.now?.() ?? Date.now();
1580
+ if (command.policy.expiresAt && (!Number.isFinite(Date.parse(command.policy.expiresAt)) || executionNow >= Date.parse(command.policy.expiresAt))) {
1581
+ throw new PeerExecutionError("POLICY_EXPIRED", "Signed execution policy has expired");
1582
+ }
1583
+ assertStepWithinTtl(step, command.genesis, executionNow);
1584
+ }
1585
+ const append = async (envelope) => {
1586
+ const event = await signFlowEvent(envelope, options.signer);
1587
+ try {
1588
+ const result = await options.events.append(event, matrixFlowEventTransactionId(event));
1589
+ if (result.outcome === "conflict") throw new PeerExecutionError("EVENT_CONFLICT", `Matrix transaction conflicts for ${event.eventId}`);
1590
+ } catch (error) {
1591
+ if (error instanceof PeerExecutionError) throw error;
1592
+ throw new PeerExecutionError("EVENT_UNAVAILABLE", `Matrix could not durably append ${event.payload.kind}: ${error instanceof Error ? error.message : String(error)}`);
1593
+ }
1594
+ return event;
1595
+ };
1596
+ const eventBase = (params) => ({
1597
+ kind: "qi.flow.event",
1598
+ schemaVersion: "1.0",
1599
+ runId: params.runId,
1600
+ definition: params.definition,
1601
+ producer: options.executorDid,
1602
+ actor: params.actor,
1603
+ occurredAt: params.issuedAt,
1604
+ parents: params.parents,
1605
+ correlationId: params.idempotencyKey,
1606
+ idempotencyKey: params.idempotencyKey,
1607
+ commandFingerprint: params.commandFingerprint,
1608
+ proofReferences: params.proofs
1609
+ });
1610
+ const readAnchoredRun = async (definition, genesis) => {
1611
+ let runEvents;
1612
+ try {
1613
+ runEvents = await options.events.read(genesis.runId);
1614
+ } catch (error) {
1615
+ throw new PeerExecutionError("EVENT_UNAVAILABLE", `Matrix could not inspect run state: ${error instanceof Error ? error.message : String(error)}`);
1616
+ }
1617
+ const reducedRun = reduceFlowEvents(genesis, runEvents);
1618
+ const acceptedEventIds = new Set(reducedRun.acceptedEventIds);
1619
+ const canonicalGenesis = canonicalizeJson(genesis);
1620
+ if (!runEvents.some(
1621
+ (event) => acceptedEventIds.has(event.eventId) && event.payload.kind === "run.started" && canonicalizeJson(event.payload.genesis) === canonicalGenesis
1622
+ )) {
1623
+ throw new PeerExecutionError("DEFINITION_MISMATCH", "Run genesis is not anchored by a verified run-start event");
1624
+ }
1625
+ if (canonicalizeJson(reducedRun.definition) !== canonicalizeJson(definition)) {
1626
+ throw new PeerExecutionError("DEFINITION_MISMATCH", "Reduced run definition does not match the immutable Flow definition");
1627
+ }
1628
+ return { runEvents, reducedRun, acceptedEventIds };
1629
+ };
1630
+ async function startRun(command) {
1631
+ command = snapshotStartCommand(command);
1632
+ const definition = definitionRef(command.definition);
1633
+ const runId = await deriveRunId(definition, command.launchKind, command.launchNonce);
1634
+ const executionNow = options.now?.() ?? Date.now();
1635
+ assertCommandTime(command.issuedAt, executionNow);
1636
+ if (command.launchKind === "topic.request" && !command.topicBindingId?.trim()) {
1637
+ throw new PeerExecutionError("TOPIC_BINDING_REQUIRED", "Topic run start requires a non-empty binding");
1638
+ }
1639
+ const genesis = {
1640
+ kind: "qi.flow.run-genesis",
1641
+ schemaVersion: "1.0",
1642
+ runId,
1643
+ definition,
1644
+ launchKind: command.launchKind,
1645
+ launchNonce: command.launchNonce,
1646
+ requiredStepIds: command.definition.steps.map((step) => step.stepId),
1647
+ startedBy: command.actor,
1648
+ startedAt: command.issuedAt,
1649
+ ...command.topicBindingId ? { topicBindingId: command.topicBindingId } : {}
1650
+ };
1651
+ let runEvents;
1652
+ try {
1653
+ runEvents = await options.events.read(runId);
1654
+ } catch (error) {
1655
+ throw new PeerExecutionError("EVENT_UNAVAILABLE", `Matrix could not inspect existing run starts: ${error instanceof Error ? error.message : String(error)}`);
1656
+ }
1657
+ const canonicalDefinition = canonicalizeJson(definition);
1658
+ const canonicalGenesis = canonicalizeJson(genesis);
1659
+ const existingStarts = runEvents.filter(
1660
+ (event) => event.runId === runId && canonicalizeJson(event.definition) === canonicalDefinition && event.payload.kind === "run.started"
1661
+ );
1662
+ if (existingStarts.some((event) => event.payload.kind === "run.started" && canonicalizeJson(event.payload.genesis) !== canonicalGenesis)) {
1663
+ throw new PeerExecutionError("EVENT_CONFLICT", `Run ${runId} already has different signed genesis evidence`);
1664
+ }
1665
+ if (existingStarts.length > 0) {
1666
+ const reducedRun = reduceFlowEvents(genesis, runEvents);
1667
+ const acceptedEventIds = new Set(reducedRun.acceptedEventIds);
1668
+ const acceptedStart = existingStarts.find((event) => acceptedEventIds.has(event.eventId));
1669
+ if (acceptedStart?.payload.kind === "run.started") return acceptedStart.payload.genesis;
1670
+ throw new PeerExecutionError("EVENT_CONFLICT", `Run ${runId} has invalid signed genesis evidence`);
1671
+ }
1672
+ const invocation = await options.authorizer.authorizeRunStart({
1673
+ authorization: command.authorization,
1674
+ executorDid: options.executorDid,
1675
+ definition,
1676
+ runId,
1677
+ actor: command.actor,
1678
+ issuedAt: command.issuedAt,
1679
+ idempotencyKey: command.idempotencyKey
1680
+ });
1681
+ assertInvocation(invocation, {
1682
+ audience: options.executorDid,
1683
+ can: FLOW_CAPABILITIES.runStart,
1684
+ with: buildFlowResourceUri(definition, { kind: "run", runId }),
1685
+ definitionDigest: definition.digest,
1686
+ idempotencyKey: command.idempotencyKey
1687
+ });
1688
+ const fingerprint = await fingerprintFlowCommand(genesis);
1689
+ await append({
1690
+ ...eventBase({
1691
+ runId,
1692
+ definition,
1693
+ actor: command.actor,
1694
+ issuedAt: command.issuedAt,
1695
+ idempotencyKey: command.idempotencyKey,
1696
+ commandFingerprint: fingerprint,
1697
+ parents: [],
1698
+ proofs: proofReferences(invocation)
1699
+ }),
1700
+ payload: { kind: "run.started", genesis }
1701
+ });
1702
+ return genesis;
1703
+ }
1704
+ async function cancelRun(command) {
1705
+ command = snapshotCancelCommand(command);
1706
+ const definition = await assertRunGenesis(command.definition, command.genesis);
1707
+ assertCommandTime(command.issuedAt, options.now?.() ?? Date.now());
1708
+ const { runEvents, reducedRun, acceptedEventIds } = await readAnchoredRun(definition, command.genesis);
1709
+ if (reducedRun.finalizedEventIds.length > 0) throw new PeerExecutionError("RUN_FINALIZED", `Run ${command.genesis.runId} is already finalized`);
1710
+ const commandFingerprint = await fingerprintFlowCommand({
1711
+ definitionDigest: definition.digest,
1712
+ runId: command.genesis.runId,
1713
+ kind: "run.cancel_requested",
1714
+ reason: command.reason ?? null
1715
+ });
1716
+ const sameKey = runEvents.filter((event) => event.idempotencyKey === command.idempotencyKey);
1717
+ const existing = sameKey.find(
1718
+ (event) => acceptedEventIds.has(event.eventId) && event.commandFingerprint === commandFingerprint && event.payload.kind === "run.cancel_requested" && event.payload.reason === command.reason
1719
+ );
1720
+ if (existing) return existing;
1721
+ if (sameKey.length > 0) throw new PeerExecutionError("EVENT_CONFLICT", "The cancellation command key is already bound to different evidence");
1722
+ const invocation = await options.authorizer.authorizeRunControl({
1723
+ authorization: command.authorization,
1724
+ executorDid: options.executorDid,
1725
+ definition,
1726
+ runId: command.genesis.runId,
1727
+ actor: command.actor,
1728
+ issuedAt: command.issuedAt,
1729
+ idempotencyKey: command.idempotencyKey,
1730
+ can: FLOW_CAPABILITIES.runCancel
1731
+ });
1732
+ assertInvocation(invocation, {
1733
+ audience: options.executorDid,
1734
+ can: FLOW_CAPABILITIES.runCancel,
1735
+ with: buildFlowResourceUri(definition, { kind: "run", runId: command.genesis.runId }),
1736
+ definitionDigest: definition.digest,
1737
+ idempotencyKey: command.idempotencyKey
1738
+ });
1739
+ return append({
1740
+ ...eventBase({
1741
+ runId: command.genesis.runId,
1742
+ definition,
1743
+ actor: command.actor,
1744
+ issuedAt: command.issuedAt,
1745
+ idempotencyKey: command.idempotencyKey,
1746
+ commandFingerprint,
1747
+ parents: reducedRun.frontierEventIds,
1748
+ proofs: proofReferences(invocation)
1749
+ }),
1750
+ payload: { kind: "run.cancel_requested", ...command.reason !== void 0 ? { reason: command.reason } : {} }
1751
+ });
1752
+ }
1753
+ async function finalizeRun(command) {
1754
+ command = snapshotFinalizeCommand(command);
1755
+ const definition = await assertRunGenesis(command.definition, command.genesis);
1756
+ assertCommandTime(command.issuedAt, options.now?.() ?? Date.now());
1757
+ const { runEvents, reducedRun, acceptedEventIds } = await readAnchoredRun(definition, command.genesis);
1758
+ const existingFinalization = runEvents.find(
1759
+ (event) => acceptedEventIds.has(event.eventId) && reducedRun.finalizedEventIds.includes(event.eventId) && event.payload.kind === "run.finalized"
1760
+ );
1761
+ if (existingFinalization) return existingFinalization;
1762
+ const candidate = reducedRun.finalizationCandidate;
1763
+ if (!candidate) throw new PeerExecutionError("RUN_NOT_FINALIZABLE", `Run ${command.genesis.runId} has no causally complete terminal state`);
1764
+ const summaryDigest = await digestCanonicalJson(candidate.summary);
1765
+ const commandFingerprint = await fingerprintFlowCommand({
1766
+ definitionDigest: definition.digest,
1767
+ runId: command.genesis.runId,
1768
+ kind: "run.finalized",
1769
+ status: candidate.status,
1770
+ summaryDigest
1771
+ });
1772
+ const sameKey = runEvents.filter((event) => event.idempotencyKey === command.idempotencyKey);
1773
+ if (sameKey.length > 0) throw new PeerExecutionError("EVENT_CONFLICT", "The finalization command key is already bound to stale or different evidence");
1774
+ const invocation = await options.authorizer.authorizeRunControl({
1775
+ authorization: command.authorization,
1776
+ executorDid: options.executorDid,
1777
+ definition,
1778
+ runId: command.genesis.runId,
1779
+ actor: command.actor,
1780
+ issuedAt: command.issuedAt,
1781
+ idempotencyKey: command.idempotencyKey,
1782
+ can: FLOW_CAPABILITIES.runClose
1783
+ });
1784
+ assertInvocation(invocation, {
1785
+ audience: options.executorDid,
1786
+ can: FLOW_CAPABILITIES.runClose,
1787
+ with: buildFlowResourceUri(definition, { kind: "run", runId: command.genesis.runId }),
1788
+ definitionDigest: definition.digest,
1789
+ idempotencyKey: command.idempotencyKey
1790
+ });
1791
+ return append({
1792
+ ...eventBase({
1793
+ runId: command.genesis.runId,
1794
+ definition,
1795
+ actor: command.actor,
1796
+ issuedAt: command.issuedAt,
1797
+ idempotencyKey: command.idempotencyKey,
1798
+ commandFingerprint,
1799
+ parents: candidate.summary.frontierEventIds,
1800
+ proofs: proofReferences(invocation)
1801
+ }),
1802
+ payload: { kind: "run.finalized", status: candidate.status, summary: candidate.summary, summaryDigest }
1803
+ });
1804
+ }
1805
+ async function executeAttempt(command) {
1806
+ command = snapshotAttemptCommand(command);
1807
+ const inputs = command.inputs;
1808
+ const definition = await assertRunGenesis(command.definition, command.genesis);
1809
+ const executionNow = options.now?.() ?? Date.now();
1810
+ assertCommandTime(command.issuedAt, executionNow);
1811
+ if (command.policy.definition.digest !== definition.digest) throw new PeerExecutionError("POLICY_MISMATCH", "Execution policy is for a different Flow definition");
1812
+ const { runEvents, reducedRun, acceptedEventIds } = await readAnchoredRun(definition, command.genesis);
1813
+ if (reducedRun.finalizedEventIds.length > 0) throw new PeerExecutionError("RUN_FINALIZED", `Run ${command.genesis.runId} is already finalized`);
1814
+ const step = command.definition.steps.find((candidate) => candidate.stepId === command.stepId);
1815
+ if (!step) throw new PeerExecutionError("STEP_NOT_FOUND", `Flow step is not in the immutable definition: ${command.stepId}`);
1816
+ if (step.trigger.kind !== "manual" && step.trigger.kind !== "topic.request" || step.conditions.length > 0) {
1817
+ throw new PeerExecutionError("ELIGIBILITY_EVIDENCE_REQUIRED", `Flow step ${step.stepId} requires signed eligibility evidence`);
1818
+ }
1819
+ const hasSignedTopicContext = step.trigger.kind === "topic.request" || command.genesis.launchKind === "topic.request" || command.genesis.topicBindingId !== void 0;
1820
+ if (hasSignedTopicContext && (!command.genesis.topicBindingId || !command.topicBinding || command.topicBinding.bindingId !== command.genesis.topicBindingId) || !hasSignedTopicContext && command.topicBinding) {
1821
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Topic execution requires the exact binding recorded by the signed step and run genesis");
1822
+ }
1823
+ if (step.trigger.kind === "topic.request" && (!command.topicRequest || command.topicRequest.requestKind !== step.trigger.requestKind || !command.topicRequest.requestId.trim() || !/^sha256:[0-9a-f]{64}$/u.test(command.topicRequest.requestDigest)) || !hasSignedTopicContext && command.topicRequest) {
1824
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Topic execution requires signed request evidence for the immutable request kind");
1825
+ }
1826
+ const contract = await options.contracts.resolve(step.action);
1827
+ assertValidInputs(contract, inputs);
1828
+ const inputDigest = await digestCanonicalJson(command.inputs);
1829
+ const attemptId = await deriveAttemptId({ runId: command.genesis.runId, stepId: command.stepId, idempotencyKey: command.idempotencyKey, inputDigest });
1830
+ const resource = buildFlowResourceUri(definition, { kind: "step", stepId: command.stepId, runId: command.genesis.runId });
1831
+ const authorization = await options.authorizer.authorizeAttempt({
1832
+ authorization: command.authorization,
1833
+ executorDid: options.executorDid,
1834
+ definition,
1835
+ runId: command.genesis.runId,
1836
+ stepId: command.stepId,
1837
+ action: contract,
1838
+ actor: command.actor,
1839
+ idempotencyKey: command.idempotencyKey,
1840
+ effectClaimAudience: options.effectClaimAudience,
1841
+ topicBinding: command.topicBinding,
1842
+ topicRequest: command.topicRequest
1843
+ });
1844
+ const invocationExpectation = {
1845
+ audience: options.executorDid,
1846
+ with: resource,
1847
+ definitionDigest: definition.digest,
1848
+ actionContractDigest: contract.contractDigest,
1849
+ idempotencyKey: command.idempotencyKey
1850
+ };
1851
+ assertInvocation(authorization.flow, { ...invocationExpectation, can: FLOW_CAPABILITIES.actionExecute });
1852
+ assertInvocation(authorization.action, { ...invocationExpectation, can: contract.can });
1853
+ if (hasSignedTopicContext) {
1854
+ if (!authorization.topic) throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Topic-bound execution requires a verified Topic invocation");
1855
+ assertInvocation(authorization.topic, {
1856
+ ...invocationExpectation,
1857
+ can: FLOW_CAPABILITIES.topicRequestAction,
1858
+ with: command.topicBinding.topicResource
1859
+ });
1860
+ if (command.topicRequest && (!authorization.topic.topicRequest || canonicalizeJson(authorization.topic.topicRequest) !== canonicalizeJson(command.topicRequest))) {
1861
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Verified Topic invocation does not bind the requested Topic request evidence");
1862
+ }
1863
+ }
1864
+ const commandFingerprint = await fingerprintFlowCommand({
1865
+ definitionDigest: definition.digest,
1866
+ runId: command.genesis.runId,
1867
+ stepId: command.stepId,
1868
+ attemptId,
1869
+ actor: command.actor,
1870
+ inputDigest,
1871
+ actionContractDigest: contract.contractDigest,
1872
+ topicBindingId: command.topicBinding?.bindingId ?? null,
1873
+ topicRequest: command.topicRequest ?? null
1874
+ });
1875
+ const base = {
1876
+ runId: command.genesis.runId,
1877
+ definition,
1878
+ actor: command.actor,
1879
+ issuedAt: command.issuedAt,
1880
+ idempotencyKey: command.idempotencyKey,
1881
+ commandFingerprint,
1882
+ proofs: proofReferences(authorization)
1883
+ };
1884
+ let claimAdmission;
1885
+ if (contract.safety === "fenced") {
1886
+ if (!options.effectClaimAudience || !authorization.effectClaim) {
1887
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Fenced execution requires a peer-issued invocation addressed to the effect claim ledger");
1888
+ }
1889
+ assertInvocation(authorization.effectClaim.invocation, {
1890
+ ...invocationExpectation,
1891
+ audience: options.effectClaimAudience,
1892
+ can: FLOW_CAPABILITIES.actionExecute
1893
+ });
1894
+ if (authorization.effectClaim.invocation.issuer !== options.executorDid) {
1895
+ throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Effect claim invocation must be issued by the peer that owns the lease");
1896
+ }
1897
+ claimAdmission = {
1898
+ authorization: authorization.effectClaim.authorization,
1899
+ invocation: authorization.effectClaim.invocation,
1900
+ policy: command.policy,
1901
+ commandFingerprint
1902
+ };
1903
+ }
1904
+ const existingRequest = runEvents.find(
1905
+ (event) => acceptedEventIds.has(event.eventId) && event.payload.kind === "action.requested" && event.payload.attemptId === attemptId && event.payload.stepId === command.stepId
1906
+ );
1907
+ if (existingRequest && (existingRequest.commandFingerprint !== commandFingerprint || existingRequest.payload.kind === "action.requested" && existingRequest.payload.inputDigest !== inputDigest)) {
1908
+ throw new PeerExecutionError("EVENT_CONFLICT", "The reserved attempt has different command evidence");
1909
+ }
1910
+ if (reducedRun.cancelRequested && !existingRequest) {
1911
+ throw new PeerExecutionError("RUN_CANCELLING", "Run cancellation was observed before this attempt was reserved");
1912
+ }
1913
+ const existingAttempt = reducedRun.attempts[attemptId];
1914
+ const existingSuccesses = runEvents.filter(
1915
+ (event) => acceptedEventIds.has(event.eventId) && event.payload.kind === "action.succeeded" && event.payload.attemptId === attemptId && event.payload.stepId === command.stepId
1916
+ );
1917
+ const acceptedEvents = runEvents.filter((event) => acceptedEventIds.has(event.eventId));
1918
+ if (existingRequest && contract.safety !== "fenced" && existingAttempt?.stepId === command.stepId) {
1919
+ if (existingAttempt.disposition === "succeeded") {
1920
+ if (!existingAttempt.outputDigest) throw new PeerExecutionError("EVENT_CONFLICT", "Accepted Action success is missing its output digest");
1921
+ if (existingSuccesses.length === 0) throw new PeerExecutionError("EVENT_CONFLICT", "Reduced Action success has no accepted event");
1922
+ for (const success of existingSuccesses) await persistActionOutcomeEvents(success, acceptedEvents);
1923
+ return {
1924
+ outcome: "succeeded",
1925
+ attemptId,
1926
+ outputDigest: existingAttempt.outputDigest,
1927
+ providerCorrelation: existingAttempt.providerCorrelation
1928
+ };
1929
+ }
1930
+ if (existingAttempt.disposition === "failed_before_effect") return { outcome: "failed_before_effect", attemptId };
1931
+ }
1932
+ const effectMayHaveStarted = runEvents.some(
1933
+ (event) => acceptedEventIds.has(event.eventId) && (event.payload.kind === "action.started" || event.payload.kind === "action.effect_armed") && event.payload.attemptId === attemptId && event.payload.stepId === command.stepId
1934
+ );
1935
+ if (!existingRequest && contract.safety !== "fenced") assertExecutionWindow(command, step);
1936
+ if (command.policy.mode === "pause_new_effects" && contract.safety === "provider_idempotent" && !effectMayHaveStarted) {
1937
+ throw new PeerExecutionError("POLICY_PAUSED", "Signed execution policy pauses new external effects");
1938
+ }
1939
+ const requested = existingRequest ?? await append({
1940
+ ...eventBase({ ...base, parents: reducedRun.frontierEventIds }),
1941
+ payload: { kind: "action.requested", attemptId, stepId: command.stepId, inputDigest }
1942
+ });
1943
+ if (contract.safety === "approval_only") {
1944
+ assertExecutionWindow(command, step);
1945
+ const proposalDigest = await digestCanonicalJson({ attemptId, inputs: command.inputs, action: contract.contractDigest });
1946
+ await append({
1947
+ ...eventBase({ ...base, parents: [requested.eventId] }),
1948
+ payload: { kind: "action.approval_proposed", attemptId, stepId: command.stepId, proposalDigest }
1949
+ });
1950
+ return { outcome: "approval_required", attemptId, proposalDigest };
1951
+ }
1952
+ const providerIdempotencyKey = `provider:${attemptId}`;
1953
+ let claim;
1954
+ let attemptParent = requested;
1955
+ if (contract.safety === "fenced") {
1956
+ if (!claimAdmission) throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Effect claim authorization is unavailable");
1957
+ const claimKey = await deriveEffectClaimKey({
1958
+ definition,
1959
+ runId: command.genesis.runId,
1960
+ stepId: command.stepId,
1961
+ attemptId,
1962
+ actorDid: command.actor,
1963
+ inputDigest,
1964
+ action: step.action,
1965
+ topicBindingId: command.topicBinding?.bindingId
1966
+ });
1967
+ const claimed = await options.effectClaims.claim({
1968
+ claimKey,
1969
+ leaseOwner: options.executorDid,
1970
+ leaseTtlMs: 3e4,
1971
+ providerIdempotencyKey,
1972
+ policyDigest: command.policy.integrity.digest.value,
1973
+ admission: claimAdmission
1974
+ });
1975
+ if (claimed.outcome === "paused") throw new PeerExecutionError("POLICY_PAUSED", claimed.reason);
1976
+ if (claimed.outcome === "conflict") throw new PeerExecutionError("CLAIM_CONFLICT", claimed.reason);
1977
+ if (!claimed.record) throw new PeerExecutionError("CLAIM_CONFLICT", "Effect claim ledger returned no claim record");
1978
+ const claimedRecord = claimed.record;
1979
+ claim = claimedRecord;
1980
+ const claimSuccess = claimedRecord.successEventId ? existingSuccesses.find((event) => event.eventId === claimedRecord.successEventId) : existingSuccesses.find(
1981
+ (event) => event.payload.kind === "action.succeeded" && event.payload.claimKey === claimedRecord.claimKey && event.payload.fencingEpoch === claimedRecord.fencingEpoch
1982
+ );
1983
+ if (claimedRecord.status === "succeeded") {
1984
+ return reconcileFenced(command, contract, authorization, attemptId, providerIdempotencyKey, claimedRecord, claimAdmission, base, requested, claimSuccess, acceptedEvents);
1985
+ }
1986
+ if (claimed.outcome === "existing" && claimedRecord.leaseOwner !== options.executorDid) {
1987
+ return { outcome: "deferred", attemptId, reason: `Effect claim is owned by ${claimedRecord.leaseOwner}` };
1988
+ }
1989
+ if (claimedRecord.status === "armed" || claimedRecord.status === "needs_verification" || claimedRecord.status === "success_prepared") {
1990
+ return reconcileFenced(command, contract, authorization, attemptId, providerIdempotencyKey, claimedRecord, claimAdmission, base, requested, claimSuccess, acceptedEvents);
1991
+ }
1992
+ claim = await options.effectClaims.arm(claimedRecord.claimKey, options.executorDid, claimedRecord.fencingEpoch, claimAdmission);
1993
+ try {
1994
+ attemptParent = await append({
1995
+ ...eventBase({ ...base, parents: [requested.eventId] }),
1996
+ payload: { kind: "action.effect_armed", attemptId, stepId: command.stepId, claimKey, fencingEpoch: claim.fencingEpoch }
1997
+ });
1998
+ } catch (error) {
1999
+ await options.effectClaims.markNeedsVerification(claim.claimKey, options.executorDid, claim.fencingEpoch, claimAdmission, claim.providerCorrelation);
2000
+ throw error;
2001
+ }
2002
+ } else {
2003
+ attemptParent = await append({
2004
+ ...eventBase({ ...base, parents: [requested.eventId] }),
2005
+ payload: { kind: "action.started", attemptId, stepId: command.stepId }
2006
+ });
2007
+ }
2008
+ if (!effectMayHaveStarted) {
2009
+ try {
2010
+ assertExecutionWindow(command, step);
2011
+ } catch (error) {
2012
+ if (!claim) throw error;
2013
+ if (!claimAdmission) throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Effect claim authorization is unavailable");
2014
+ const reason = error instanceof Error ? error.message : String(error);
2015
+ await options.effectClaims.markNeedsVerification(claim.claimKey, options.executorDid, claim.fencingEpoch, claimAdmission, claim.providerCorrelation);
2016
+ await append({
2017
+ ...eventBase({ ...base, parents: [attemptParent.eventId] }),
2018
+ payload: {
2019
+ kind: "action.needs_verification",
2020
+ attemptId,
2021
+ stepId: command.stepId,
2022
+ ...claim.providerCorrelation ? { providerCorrelation: claim.providerCorrelation } : {},
2023
+ reason
2024
+ }
2025
+ });
2026
+ return { outcome: "needs_verification", attemptId, providerCorrelation: claim.providerCorrelation };
2027
+ }
2028
+ }
2029
+ const provider = await options.actions.invoke({
2030
+ contract,
2031
+ inputs: command.inputs,
2032
+ providerIdempotencyKey,
2033
+ invocation: authorization,
2034
+ assertEffectAllowed: () => assertExecutionWindow(command, step)
2035
+ });
2036
+ if (provider.outcome === "succeeded") {
2037
+ const digest = await validatedOutputDigest(contract, provider.output);
2038
+ return persistSuccess(command, attemptId, digest, provider.outcomes, provider.providerCorrelation, claim, claimAdmission, base, attemptParent);
2039
+ }
2040
+ if (provider.outcome === "failed_before_effect" && !claim) {
2041
+ await append({
2042
+ ...eventBase({ ...base, parents: [attemptParent.eventId] }),
2043
+ payload: { kind: "action.failed_before_effect", attemptId, stepId: command.stepId, error: provider.error }
2044
+ });
2045
+ return { outcome: "failed_before_effect", attemptId };
2046
+ }
2047
+ const ambiguous = provider.outcome === "ambiguous" ? provider : { outcome: "ambiguous", reason: "Provider reported failure after the effect was armed; readback is required" };
2048
+ return reconcileAmbiguity(command, contract, authorization, attemptId, providerIdempotencyKey, claim, claimAdmission, base, attemptParent, ambiguous);
2049
+ }
2050
+ async function reconcileFenced(command, contract, authorization, attemptId, providerIdempotencyKey, claim, admission, base, requested, existingSuccess, existingEvents = []) {
2051
+ if (existingSuccess?.payload.kind === "action.succeeded") {
2052
+ const success = existingSuccess.payload;
2053
+ const outcomesMatch = claim.outcomesDigest === void 0 ? success.outcomes === void 0 : await actionOutcomesDigest(success.outcomes ?? []) === claim.outcomesDigest;
2054
+ if (success.claimKey !== claim.claimKey || success.fencingEpoch !== claim.fencingEpoch || success.outputDigest !== claim.outputDigest || !outcomesMatch) {
2055
+ throw new PeerExecutionError("EVENT_CONFLICT", "Accepted fenced success does not match the durable prepared evidence");
2056
+ }
2057
+ if (claim.status === "success_prepared") {
2058
+ await options.effectClaims.resolve(claim.claimKey, options.executorDid, claim.fencingEpoch, "succeeded", admission, success.providerCorrelation, existingSuccess.eventId);
2059
+ } else if (claim.status !== "succeeded" || claim.successEventId !== existingSuccess.eventId) {
2060
+ throw new PeerExecutionError("EVENT_CONFLICT", "Accepted fenced success has no prepared or finalized effect claim");
2061
+ }
2062
+ await persistActionOutcomeEvents(existingSuccess, existingEvents);
2063
+ return {
2064
+ outcome: "succeeded",
2065
+ attemptId,
2066
+ outputDigest: success.outputDigest,
2067
+ ...success.providerCorrelation !== void 0 ? { providerCorrelation: success.providerCorrelation } : {}
2068
+ };
2069
+ }
2070
+ if (claim.status === "succeeded") {
2071
+ throw new PeerExecutionError("EVENT_CONFLICT", "Finalized effect claim references a Matrix success event that is unavailable");
2072
+ }
2073
+ const armed = await append({
2074
+ ...eventBase({ ...base, parents: [requested.eventId] }),
2075
+ payload: {
2076
+ kind: "action.effect_armed",
2077
+ attemptId,
2078
+ stepId: command.stepId,
2079
+ claimKey: claim.claimKey,
2080
+ fencingEpoch: claim.fencingEpoch
2081
+ }
2082
+ });
2083
+ if (claim.status === "success_prepared" && claim.outputDigest && claim.outcomesDigest) {
2084
+ const readback = await options.actions.readback({
2085
+ contract,
2086
+ inputs: command.inputs,
2087
+ providerIdempotencyKey,
2088
+ providerCorrelation: claim.providerCorrelation,
2089
+ invocation: authorization
2090
+ });
2091
+ if (readback.outcome === "succeeded") {
2092
+ const digest = await validatedOutputDigest(contract, readback.output);
2093
+ const outcomes = await actionOutcomes(digest, readback.outcomes);
2094
+ if (digest === claim.outputDigest && await actionOutcomesDigest(outcomes) === claim.outcomesDigest) {
2095
+ return persistSuccess(command, attemptId, digest, readback.outcomes, readback.providerCorrelation, claim, admission, base, armed);
2096
+ }
2097
+ }
2098
+ const providerCorrelation = readback.outcome === "succeeded" || readback.outcome === "unknown" ? readback.providerCorrelation ?? claim.providerCorrelation : claim.providerCorrelation;
2099
+ await append({
2100
+ ...eventBase({ ...base, parents: [armed.eventId] }),
2101
+ payload: {
2102
+ kind: "action.needs_verification",
2103
+ attemptId,
2104
+ stepId: command.stepId,
2105
+ ...providerCorrelation !== void 0 ? { providerCorrelation } : {},
2106
+ reason: "Prepared provider result could not be reproduced with its complete outcome evidence"
2107
+ }
2108
+ });
2109
+ return { outcome: "needs_verification", attemptId, ...providerCorrelation !== void 0 ? { providerCorrelation } : {} };
2110
+ }
2111
+ return reconcileAmbiguity(command, contract, authorization, attemptId, providerIdempotencyKey, claim, admission, base, armed, {
2112
+ outcome: "ambiguous",
2113
+ providerCorrelation: claim.providerCorrelation,
2114
+ reason: "Recovered an armed effect claim"
2115
+ });
2116
+ }
2117
+ async function persistSuccess(command, attemptId, digest, providedOutcomes, providerCorrelation, claim, admission, base, attemptParent) {
2118
+ const outcomes = await actionOutcomes(digest, providedOutcomes);
2119
+ const outcomesDigest = await actionOutcomesDigest(outcomes);
2120
+ let durableClaim = claim;
2121
+ if (claim && !admission) throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Effect claim authorization is unavailable");
2122
+ if (claim && claim.status !== "success_prepared" && claim.status !== "succeeded") {
2123
+ durableClaim = await options.effectClaims.prepareSuccess(claim.claimKey, options.executorDid, claim.fencingEpoch, digest, outcomesDigest, admission, providerCorrelation);
2124
+ }
2125
+ if (durableClaim && (durableClaim.outputDigest !== digest || durableClaim.outcomesDigest !== outcomesDigest)) {
2126
+ throw new PeerExecutionError("EVENT_CONFLICT", "Prepared effect claim does not match the complete Action result evidence");
2127
+ }
2128
+ const success = await append({
2129
+ ...eventBase({ ...base, parents: [attemptParent.eventId] }),
2130
+ payload: {
2131
+ kind: "action.succeeded",
2132
+ attemptId,
2133
+ stepId: command.stepId,
2134
+ outputDigest: digest,
2135
+ outcomes,
2136
+ ...providerCorrelation !== void 0 ? { providerCorrelation } : {},
2137
+ ...durableClaim ? { claimKey: durableClaim.claimKey, fencingEpoch: durableClaim.fencingEpoch } : {}
2138
+ }
2139
+ });
2140
+ if (durableClaim?.status === "success_prepared") {
2141
+ await options.effectClaims.resolve(durableClaim.claimKey, options.executorDid, durableClaim.fencingEpoch, "succeeded", admission, providerCorrelation, success.eventId);
2142
+ }
2143
+ await persistActionOutcomeEvents(success);
2144
+ return { outcome: "succeeded", attemptId, outputDigest: digest, providerCorrelation };
2145
+ }
2146
+ async function persistActionOutcomeEvents(success, existingEvents = []) {
2147
+ if (success.payload.kind !== "action.succeeded") throw new PeerExecutionError("EVENT_CONFLICT", "Action outcomes require accepted success evidence");
2148
+ const successPayload = success.payload;
2149
+ for (const outcome of successPayload.outcomes ?? []) {
2150
+ const exists = existingEvents.some(
2151
+ (event) => event.payload.kind === "action.outcome_emitted" && event.payload.attemptId === successPayload.attemptId && event.payload.stepId === successPayload.stepId && event.payload.name === outcome.name && event.payload.payloadDigest === outcome.payloadDigest && event.parents.includes(success.eventId)
2152
+ );
2153
+ if (exists) continue;
2154
+ await append({
2155
+ ...eventBase({
2156
+ runId: success.runId,
2157
+ definition: success.definition,
2158
+ actor: success.actor,
2159
+ issuedAt: success.occurredAt,
2160
+ idempotencyKey: success.idempotencyKey,
2161
+ commandFingerprint: success.commandFingerprint,
2162
+ parents: [success.eventId],
2163
+ proofs: success.proofReferences
2164
+ }),
2165
+ causationId: success.eventId,
2166
+ payload: {
2167
+ kind: "action.outcome_emitted",
2168
+ attemptId: successPayload.attemptId,
2169
+ stepId: successPayload.stepId,
2170
+ ...outcome
2171
+ }
2172
+ });
2173
+ }
2174
+ }
2175
+ async function reconcileAmbiguity(command, contract, authorization, attemptId, providerIdempotencyKey, claim, admission, base, attemptParent, ambiguous) {
2176
+ const readback = await options.actions.readback({
2177
+ contract,
2178
+ inputs: command.inputs,
2179
+ providerIdempotencyKey,
2180
+ providerCorrelation: ambiguous.providerCorrelation,
2181
+ invocation: authorization
2182
+ });
2183
+ if (readback.outcome === "succeeded") {
2184
+ const digest = await validatedOutputDigest(contract, readback.output);
2185
+ return persistSuccess(command, attemptId, digest, readback.outcomes, readback.providerCorrelation, claim, admission, base, attemptParent);
2186
+ }
2187
+ if (readback.outcome === "not_found" && !claim) {
2188
+ await append({
2189
+ ...eventBase({ ...base, parents: [attemptParent.eventId] }),
2190
+ payload: { kind: "action.failed_before_effect", attemptId, stepId: command.stepId, error: { code: "PROVIDER_CONFIRMED_NOT_FOUND" } }
2191
+ });
2192
+ return { outcome: "failed_before_effect", attemptId };
2193
+ }
2194
+ const correlation = readback.outcome === "unknown" ? readback.providerCorrelation ?? ambiguous.providerCorrelation : ambiguous.providerCorrelation;
2195
+ if (claim && claim.status === "armed") {
2196
+ if (!admission) throw new PeerExecutionError("AUTHORIZATION_MISMATCH", "Effect claim authorization is unavailable");
2197
+ await options.effectClaims.markNeedsVerification(claim.claimKey, options.executorDid, claim.fencingEpoch, admission, correlation);
2198
+ }
2199
+ await append({
2200
+ ...eventBase({ ...base, parents: [attemptParent.eventId] }),
2201
+ payload: {
2202
+ kind: "action.needs_verification",
2203
+ attemptId,
2204
+ stepId: command.stepId,
2205
+ ...correlation !== void 0 ? { providerCorrelation: correlation } : {},
2206
+ reason: ambiguous.reason
2207
+ }
2208
+ });
2209
+ return { outcome: "needs_verification", attemptId, ...correlation !== void 0 ? { providerCorrelation: correlation } : {} };
2210
+ }
2211
+ return { startRun, cancelRun, finalizeRun, executeAttempt };
2212
+ }
2213
+
2214
+ // src/core/lib/flowEngine/vnext/legacy.ts
2215
+ var LegacyFlowFrozenError = class extends Error {
2216
+ constructor(operation) {
2217
+ super(`Legacy Flow operation ${operation} is frozen; explicitly republish authored meaning as a new vNext revision`);
2218
+ this.operation = operation;
2219
+ this.name = "LegacyFlowFrozenError";
2220
+ }
2221
+ };
2222
+ function assertLegacyFlowOperationAllowed(gate, operation) {
2223
+ if (gate?.legacyMode === "read_only") throw new LegacyFlowFrozenError(operation);
2224
+ }
2225
+
2226
+ // src/core/lib/flowEngine/vnext/topicReceipts.ts
2227
+ async function persistSignedTopicReceipt(params) {
2228
+ const outbox = params.outbox;
2229
+ const snapshot = JSON.parse(
2230
+ canonicalizeJson({
2231
+ topicRequestId: params.topicRequestId,
2232
+ attemptId: params.attemptId,
2233
+ phase: params.phase,
2234
+ eventId: params.eventId,
2235
+ signedReceipt: params.signedReceipt,
2236
+ persistedAt: params.persistedAt
2237
+ })
2238
+ );
2239
+ const canonicalReceipt = canonicalizeJson(snapshot.signedReceipt);
2240
+ const receiptDigest = await digestCanonicalJson(snapshot.signedReceipt);
2241
+ const receiptId = await deriveReceiptId({
2242
+ topicRequestId: snapshot.topicRequestId,
2243
+ attemptId: snapshot.attemptId,
2244
+ phase: snapshot.phase,
2245
+ eventId: snapshot.eventId
2246
+ });
2247
+ const record = {
2248
+ kind: "qi.flow.topic-receipt-outbox-record",
2249
+ schemaVersion: "1.0",
2250
+ receiptId,
2251
+ receiptDigest,
2252
+ topicRequestId: snapshot.topicRequestId,
2253
+ attemptId: snapshot.attemptId,
2254
+ phase: snapshot.phase,
2255
+ eventId: snapshot.eventId,
2256
+ canonicalReceipt,
2257
+ persistedAt: snapshot.persistedAt
2258
+ };
2259
+ const outcome = await outbox.persist(record);
2260
+ if (outcome === "conflict") throw new Error(`Topic receipt identity ${receiptId} is already bound to different signed bytes`);
2261
+ return record;
2262
+ }
2263
+ async function drainTopicReceiptOutbox(outbox, delivery, now = () => /* @__PURE__ */ new Date(), limit = 100) {
2264
+ const outcomes = [];
2265
+ for (const record of await outbox.pending(limit)) {
2266
+ try {
2267
+ const delivered = await delivery.deliver({
2268
+ receiptId: record.receiptId,
2269
+ receiptDigest: record.receiptDigest,
2270
+ canonicalReceipt: record.canonicalReceipt
2271
+ });
2272
+ await outbox.markDelivered(record.receiptId, record.receiptDigest, { ...delivered, deliveredAt: now().toISOString() });
2273
+ outcomes.push({ receiptId: record.receiptId, outcome: "delivered" });
2274
+ } catch (error) {
2275
+ outcomes.push({ receiptId: record.receiptId, outcome: "failed", error: error instanceof Error ? error.message : String(error) });
2276
+ }
2277
+ }
2278
+ return outcomes;
2279
+ }
2280
+
2281
+ // src/core/lib/flowEngine/vnext/matrixStores.ts
2282
+ var MATRIX_FLOW_EVENT_TYPE = "ixo.qi.flow.event.v1";
2283
+ var MATRIX_FLOW_DEFINITION_ANCHOR_TYPE = "ixo.qi.flow.definition-anchor.v1";
2284
+ var MatrixRoomFlowEventStore = class {
2285
+ constructor(roomId, transport, trust) {
2286
+ this.roomId = roomId;
2287
+ this.transport = transport;
2288
+ this.trust = trust;
2289
+ }
2290
+ async append(event, transactionId) {
2291
+ const verified = await verifyFlowEvent(event, this.trust);
2292
+ const expectedTransactionId = matrixFlowEventTransactionId(verified);
2293
+ if (transactionId !== expectedTransactionId) throw new Error(`Matrix Flow event append requires deterministic transaction ID ${expectedTransactionId}`);
2294
+ const result = await this.transport.append({ roomId: this.roomId, eventType: MATRIX_FLOW_EVENT_TYPE, transactionId, content: { event: verified } });
2295
+ if (result.outcome !== "conflict" && result.eventId !== verified.eventId) {
2296
+ throw new Error(`Matrix Flow event append acknowledged unexpected event ID ${result.eventId}`);
2297
+ }
2298
+ return result;
2299
+ }
2300
+ async inspect(runId, options = {}) {
2301
+ const acceptedEvents = [];
2302
+ const rejectedEvents = [];
2303
+ const seenCursors = /* @__PURE__ */ new Set();
2304
+ let cursor;
2305
+ do {
2306
+ const remaining = options.limit === void 0 ? void 0 : options.limit - acceptedEvents.length;
2307
+ if (remaining !== void 0 && remaining <= 0) break;
2308
+ const page = await this.transport.read({ roomId: this.roomId, runId, afterEventId: options.after, cursor, limit: remaining });
2309
+ for (const carrier of page.carriers) {
2310
+ if (options.limit !== void 0 && acceptedEvents.length >= options.limit) break;
2311
+ let eventSnapshot;
2312
+ try {
2313
+ eventSnapshot = deepFreezeJson(JSON.parse(canonicalizeJson(carrier.event)));
2314
+ } catch {
2315
+ eventSnapshot = deepFreezeJson(structuredClone(carrier.event));
2316
+ rejectedEvents.push({ carrierEventId: carrier.carrierEventId, event: eventSnapshot, reason: "Flow event content cannot be canonicalized" });
2317
+ continue;
2318
+ }
2319
+ try {
2320
+ acceptedEvents.push(await verifyFlowEvent(eventSnapshot, this.trust));
2321
+ } catch (error) {
2322
+ if (!(error instanceof FlowEventValidationError)) throw error;
2323
+ rejectedEvents.push({ carrierEventId: carrier.carrierEventId, event: eventSnapshot, reason: error.message });
2324
+ }
2325
+ }
2326
+ if (page.nextCursor === void 0) break;
2327
+ if (seenCursors.has(page.nextCursor)) throw new Error("Matrix Flow event transport returned a repeated cursor");
2328
+ seenCursors.add(page.nextCursor);
2329
+ cursor = page.nextCursor;
2330
+ } while (true);
2331
+ return { acceptedEvents, rejectedEvents };
2332
+ }
2333
+ async read(runId, options = {}) {
2334
+ return (await this.inspect(runId, options)).acceptedEvents;
2335
+ }
2336
+ };
2337
+ var ANCHOR_DOMAIN = "qi.flow.definition-anchor.v1\0";
2338
+ function anchorSignatureInput(digest) {
2339
+ return new TextEncoder().encode(`${ANCHOR_DOMAIN}${digest}`);
2340
+ }
2341
+ async function signMatrixDefinitionAnchor(payload, signer) {
2342
+ const snapshot = JSON.parse(canonicalizeJson(payload));
2343
+ if (snapshot.anchoredBy !== signer.issuerDid || !signer.verificationMethod.startsWith(`${snapshot.anchoredBy}#`)) {
2344
+ throw new Error("Matrix definition anchor signer does not match the issuer");
2345
+ }
2346
+ const digest = await digestCanonicalJson(snapshot);
2347
+ const signature = await signer.sign(anchorSignatureInput(digest));
2348
+ if (!signature) throw new Error("Matrix definition anchor signer returned an empty signature");
2349
+ return {
2350
+ ...snapshot,
2351
+ integrity: {
2352
+ canonicalization: "RFC8785",
2353
+ digest: { algorithm: "SHA-256", value: digest },
2354
+ signature: { algorithm: signer.algorithm, verificationMethod: signer.verificationMethod, value: signature }
2355
+ }
2356
+ };
2357
+ }
2358
+ async function verifyMatrixDefinitionAnchor(anchor, trust) {
2359
+ const snapshot = JSON.parse(canonicalizeJson(anchor));
2360
+ const { integrity, ...payload } = snapshot;
2361
+ const digest = await digestCanonicalJson(payload);
2362
+ if (digest !== integrity.digest.value) throw new Error("Matrix definition anchor digest mismatch");
2363
+ if (!trust.trustedIssuerDids.includes(payload.anchoredBy)) throw new Error(`Matrix definition anchor issuer is not trusted: ${payload.anchoredBy}`);
2364
+ if (!trust.allowedSignatureAlgorithms.includes(integrity.signature.algorithm)) throw new Error("Matrix definition anchor signature algorithm is not allowed");
2365
+ if (!integrity.signature.verificationMethod.startsWith(`${payload.anchoredBy}#`)) throw new Error("Matrix definition anchor verification method does not belong to the issuer");
2366
+ if (!await trust.verifySignature({
2367
+ issuerDid: payload.anchoredBy,
2368
+ verificationMethod: integrity.signature.verificationMethod,
2369
+ algorithm: integrity.signature.algorithm,
2370
+ data: anchorSignatureInput(digest),
2371
+ signature: integrity.signature.value
2372
+ })) {
2373
+ throw new Error("Matrix definition anchor signature is invalid");
2374
+ }
2375
+ return deepFreezeJson(snapshot);
2376
+ }
2377
+ var EncryptedMatrixFlowDefinitionRevisionRepository = class {
2378
+ constructor(roomId, transport, cipher, anchorSigner, anchorTrust, definitionTrust, now = () => /* @__PURE__ */ new Date()) {
2379
+ this.roomId = roomId;
2380
+ this.transport = transport;
2381
+ this.cipher = cipher;
2382
+ this.anchorSigner = anchorSigner;
2383
+ this.anchorTrust = anchorTrust;
2384
+ this.definitionTrust = definitionTrust;
2385
+ this.now = now;
2386
+ }
2387
+ async publish(revision, expectedParent) {
2388
+ const expectedParentSnapshot = expectedParent ? deepFreezeJson(JSON.parse(canonicalizeJson(expectedParent))) : void 0;
2389
+ const verified = await verifyFlowDefinitionRevision(revision, this.definitionTrust);
2390
+ if (canonicalizeJson(verified.parent ?? null) !== canonicalizeJson(expectedParentSnapshot ?? null)) {
2391
+ return "parent_conflict";
2392
+ }
2393
+ const definition = { ...verified.ref, digest: verified.integrity.digest.value };
2394
+ const plaintext = new TextEncoder().encode(canonicalizeJson(verified));
2395
+ const ciphertext = Uint8Array.from(await this.cipher.encrypt(plaintext));
2396
+ const ciphertextDigest = await digestCanonicalJson(Array.from(ciphertext));
2397
+ const mediaUri = await this.transport.putMedia({
2398
+ ciphertext,
2399
+ ciphertextDigest,
2400
+ contentType: "application/vnd.ixo.qi-flow-revision+json"
2401
+ });
2402
+ const anchor = await signMatrixDefinitionAnchor(
2403
+ {
2404
+ kind: "qi.flow.definition-anchor",
2405
+ schemaVersion: "1.0",
2406
+ definition,
2407
+ mediaUri,
2408
+ ciphertextDigest,
2409
+ encryption: { algorithm: this.cipher.algorithm, keyReference: this.cipher.keyReference },
2410
+ anchoredAt: this.now().toISOString(),
2411
+ anchoredBy: this.anchorSigner.issuerDid
2412
+ },
2413
+ this.anchorSigner
2414
+ );
2415
+ return this.transport.publishAnchor({
2416
+ roomId: this.roomId,
2417
+ eventType: MATRIX_FLOW_DEFINITION_ANCHOR_TYPE,
2418
+ transactionId: `qi-flow-definition-v1-${definition.digest.slice("sha256:".length)}`,
2419
+ anchor,
2420
+ expectedParent: expectedParentSnapshot
2421
+ });
2422
+ }
2423
+ async get(ref) {
2424
+ const candidate = await this.transport.getAnchor(this.roomId, ref.flowId, ref.revision);
2425
+ if (!candidate) return null;
2426
+ const anchor = await verifyMatrixDefinitionAnchor(candidate, this.anchorTrust);
2427
+ if (anchor.definition.digest !== ref.digest || anchor.definition.flowId !== ref.flowId || anchor.definition.revision !== ref.revision) {
2428
+ throw new Error("Matrix definition anchor does not match the requested revision");
2429
+ }
2430
+ if (anchor.encryption.algorithm !== this.cipher.algorithm || anchor.encryption.keyReference !== this.cipher.keyReference) {
2431
+ throw new Error("Matrix definition anchor encryption binding is unavailable");
2432
+ }
2433
+ const ciphertext = await this.transport.getMedia(anchor.mediaUri);
2434
+ const ciphertextDigest = await digestCanonicalJson(Array.from(ciphertext));
2435
+ if (ciphertextDigest !== anchor.ciphertextDigest) throw new Error("Encrypted Matrix revision media digest mismatch");
2436
+ const plaintext = await this.cipher.decrypt(ciphertext);
2437
+ const revision = JSON.parse(new TextDecoder().decode(plaintext));
2438
+ const verified = await verifyFlowDefinitionRevision(revision, this.definitionTrust);
2439
+ if (verified.ref.flowId !== anchor.definition.flowId || verified.ref.revision !== anchor.definition.revision || verified.integrity.digest.value !== anchor.definition.digest) {
2440
+ throw new Error("Decrypted Matrix revision does not match its signed anchor");
2441
+ }
2442
+ return verified;
2443
+ }
2444
+ };
2445
+
2446
+ // src/core/lib/flowEngine/vnext/composio.ts
2447
+ var ComposioContractMismatchError = class extends Error {
2448
+ constructor(reason) {
2449
+ super(`Composio Action is unavailable: ${reason}`);
2450
+ this.reason = reason;
2451
+ this.name = "ComposioContractMismatchError";
2452
+ }
2453
+ };
2454
+ var COMPOSIO_AVAILABILITY_SIGNATURE_DOMAIN = "qi.composio.action-availability.v1\0";
2455
+ function availabilitySignatureInput(digest) {
2456
+ return new TextEncoder().encode(`${COMPOSIO_AVAILABILITY_SIGNATURE_DOMAIN}${digest}`);
2457
+ }
2458
+ function assertAvailabilityPayload(payload) {
2459
+ if (payload.kind !== "qi.composio.action-availability" || payload.schemaVersion !== "1.0") throw new ComposioContractMismatchError("unsupported availability contract");
2460
+ if (!payload.issuedBy || !payload.actionContractDigest || !payload.handlerIdentity || !payload.toolSlug || !payload.accountBinding.bindingId || !payload.accountBinding.connectedAccountReference || !payload.ucanAudience) {
2461
+ throw new ComposioContractMismatchError("availability identity and execution binding are required");
2462
+ }
2463
+ if (payload.readback !== "unavailable" && !payload.readbackToolSlug?.trim()) {
2464
+ throw new ComposioContractMismatchError("required or supported readback must declare an explicit readback tool");
2465
+ }
2466
+ const checkedAt = Date.parse(payload.checkedAt);
2467
+ const expiresAt = Date.parse(payload.expiresAt);
2468
+ if (!Number.isFinite(checkedAt) || !Number.isFinite(expiresAt) || expiresAt <= checkedAt) {
2469
+ throw new ComposioContractMismatchError("availability timestamps are invalid");
2470
+ }
2471
+ }
2472
+ async function computeComposioAvailabilityDigest(payload) {
2473
+ assertAvailabilityPayload(payload);
2474
+ return await digestCanonicalJson(payload);
2475
+ }
2476
+ async function signComposioActionAvailability(payload, signer) {
2477
+ const snapshot = JSON.parse(canonicalizeJson(payload));
2478
+ assertAvailabilityPayload(snapshot);
2479
+ if (signer.issuerDid !== snapshot.issuedBy || !signer.verificationMethod.startsWith(`${snapshot.issuedBy}#`)) {
2480
+ throw new ComposioContractMismatchError("availability signer does not match the issuer");
2481
+ }
2482
+ const digest = await computeComposioAvailabilityDigest(snapshot);
2483
+ const signature = await signer.sign(availabilitySignatureInput(digest));
2484
+ if (!signature) throw new ComposioContractMismatchError("availability signer returned an empty signature");
2485
+ return {
2486
+ ...snapshot,
2487
+ integrity: {
2488
+ canonicalization: "RFC8785",
2489
+ digest: { algorithm: "SHA-256", value: digest },
2490
+ signature: { algorithm: signer.algorithm, verificationMethod: signer.verificationMethod, value: signature }
2491
+ }
2492
+ };
2493
+ }
2494
+ async function verifyComposioActionAvailability(candidate, policy, now = /* @__PURE__ */ new Date()) {
2495
+ const snapshot = JSON.parse(canonicalizeJson(candidate));
2496
+ const { integrity, ...payload } = snapshot;
2497
+ assertAvailabilityPayload(payload);
2498
+ const digest = await computeComposioAvailabilityDigest(payload);
2499
+ if (digest !== integrity.digest.value) throw new ComposioContractMismatchError("availability digest does not match its content");
2500
+ if (!policy.trustedIssuerDids.includes(payload.issuedBy)) throw new ComposioContractMismatchError("availability issuer is not trusted");
2501
+ if (policy.revokedIssuerDids?.includes(payload.issuedBy)) throw new ComposioContractMismatchError("availability issuer is revoked");
2502
+ if (!policy.allowedSignatureAlgorithms.includes(integrity.signature.algorithm)) throw new ComposioContractMismatchError("availability signature algorithm is not allowed");
2503
+ if (!integrity.signature.verificationMethod.startsWith(`${payload.issuedBy}#`)) {
2504
+ throw new ComposioContractMismatchError("availability verification method does not belong to the issuer");
2505
+ }
2506
+ if (Date.parse(payload.expiresAt) <= now.getTime()) throw new ComposioContractMismatchError("availability contract is expired");
2507
+ const valid = await policy.verifySignature({
2508
+ issuerDid: payload.issuedBy,
2509
+ verificationMethod: integrity.signature.verificationMethod,
2510
+ algorithm: integrity.signature.algorithm,
2511
+ data: availabilitySignatureInput(digest),
2512
+ signature: integrity.signature.value
2513
+ });
2514
+ if (!valid) throw new ComposioContractMismatchError("availability signature verification failed");
2515
+ return deepFreezeJson(snapshot);
2516
+ }
2517
+ async function assertAvailability(contract, availability, authorization, now) {
2518
+ if (Date.parse(availability.expiresAt) <= now.getTime()) throw new ComposioContractMismatchError("availability contract is expired");
2519
+ if (availability.status !== "available") throw new ComposioContractMismatchError(availability.unavailableReasons.join("; ") || "availability endpoint is unhealthy");
2520
+ if (availability.actionContractDigest !== contract.contractDigest) throw new ComposioContractMismatchError("Action contract digest mismatch");
2521
+ if (availability.handlerVersion !== contract.handlerVersion) throw new ComposioContractMismatchError("handler version mismatch");
2522
+ if (await digestCanonicalJson(contract.inputSchema) !== availability.inputSchemaDigest) throw new ComposioContractMismatchError("input schema digest mismatch");
2523
+ if (await digestCanonicalJson(contract.outputSchema) !== availability.outputSchemaDigest) throw new ComposioContractMismatchError("output schema digest mismatch");
2524
+ if (availability.providerIdempotency !== contract.idempotency.providerKey) throw new ComposioContractMismatchError("provider idempotency contract mismatch");
2525
+ if (availability.readback !== contract.idempotency.readback || availability.compensation !== contract.idempotency.compensation) {
2526
+ throw new ComposioContractMismatchError("recovery procedure mismatch");
2527
+ }
2528
+ if (availability.readback !== "unavailable" && !availability.readbackToolSlug?.trim()) {
2529
+ throw new ComposioContractMismatchError("required or supported readback must declare an explicit readback tool");
2530
+ }
2531
+ const provider = authorization.provider;
2532
+ if (!provider) throw new ComposioContractMismatchError("verified provider invocation is missing");
2533
+ if (provider.audience !== availability.ucanAudience || provider.can !== "composio/execute" || provider.with !== `ixo:composio:binding:${availability.accountBinding.bindingId}` || provider.actionContractDigest !== contract.contractDigest || provider.definitionDigest !== authorization.flow.definitionDigest || provider.idempotencyKey !== authorization.flow.idempotencyKey) {
2534
+ throw new ComposioContractMismatchError("provider UCAN does not authorize this Flow command and Action");
2535
+ }
2536
+ }
2537
+ var ManifestBoundComposioActionAdapter = class {
2538
+ constructor(availability, gateway, now = () => /* @__PURE__ */ new Date()) {
2539
+ this.availability = availability;
2540
+ this.gateway = gateway;
2541
+ this.now = now;
2542
+ }
2543
+ async invoke(request) {
2544
+ const available = await this.availability.resolve(request.contract.contractDigest);
2545
+ await assertAvailability(request.contract, available, request.invocation, this.now());
2546
+ request.assertEffectAllowed();
2547
+ return this.gateway.execute({
2548
+ toolSlug: available.toolSlug,
2549
+ bindingId: available.accountBinding.bindingId,
2550
+ connectedAccountReference: available.accountBinding.connectedAccountReference,
2551
+ arguments: request.inputs,
2552
+ providerIdempotencyKey: request.providerIdempotencyKey,
2553
+ providerInvocationReference: request.invocation.provider.cid
2554
+ });
2555
+ }
2556
+ async readback(request) {
2557
+ const available = await this.availability.resolve(request.contract.contractDigest);
2558
+ await assertAvailability(request.contract, available, request.invocation, this.now());
2559
+ if (!available.readbackToolSlug) return { outcome: "unknown", providerCorrelation: request.providerCorrelation, reason: "Manifest declares no explicit readback tool" };
2560
+ return this.gateway.readback({
2561
+ toolSlug: available.readbackToolSlug,
2562
+ bindingId: available.accountBinding.bindingId,
2563
+ connectedAccountReference: available.accountBinding.connectedAccountReference,
2564
+ arguments: request.inputs,
2565
+ providerIdempotencyKey: request.providerIdempotencyKey,
2566
+ providerCorrelation: request.providerCorrelation,
2567
+ providerInvocationReference: request.invocation.provider.cid
2568
+ });
2569
+ }
2570
+ };
2571
+
2572
+ // src/core/lib/yjsTypes.ts
2573
+ function isYMapLike(value) {
2574
+ if (!value || typeof value !== "object") return false;
2575
+ const candidate = value;
2576
+ return typeof candidate.get === "function" && typeof candidate.set === "function" && typeof candidate.has === "function" && typeof candidate.forEach === "function";
2577
+ }
2578
+
2579
+ // src/core/lib/flowEngine/vnext/runProjections.ts
2580
+ var FLOW_RUN_PROJECTIONS_MAP_KEY = "qi.flow.runProjections";
2581
+ var FLOW_RUN_PROJECTION_KEY_SEPARATOR = "::";
2582
+ var RUN_STATUSES = /* @__PURE__ */ new Set(["queued", "running", "cancelling", "needs_verification", "completed", "failed", "cancelled"]);
2583
+ var EFFECT_DISPOSITIONS = /* @__PURE__ */ new Set(["not_started", "armed", "succeeded", "failed_before_effect", "needs_verification"]);
2584
+ function isRecord2(value) {
2585
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2586
+ }
2587
+ function isStringArray2(value) {
2588
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
2589
+ }
2590
+ function isDigest(value) {
2591
+ return typeof value === "string" && /^sha256:[0-9a-f]{64}$/u.test(value);
2592
+ }
2593
+ function hasValidProjectionShape(value) {
2594
+ if (!isRecord2(value)) return false;
2595
+ if (value.kind !== "qi.flow.run-projection" || value.schemaVersion !== "1.0" || typeof value.runId !== "string" || !isDigest(value.sourceEventSetDigest)) return false;
2596
+ if (!isRecord2(value.definition) || typeof value.definition.flowId !== "string" || typeof value.definition.revision !== "string" || !isDigest(value.definition.digest))
2597
+ return false;
2598
+ const sourceEventIds = value.sourceEventIds;
2599
+ if (!isStringArray2(sourceEventIds) || canonicalizeJson(sourceEventIds) !== canonicalizeJson([...new Set(sourceEventIds)].sort())) return false;
2600
+ const headEventIds = value.headEventIds;
2601
+ if (!isStringArray2(headEventIds) || canonicalizeJson(headEventIds) !== canonicalizeJson([...new Set(headEventIds)].sort()) || !headEventIds.every((eventId) => sourceEventIds.includes(eventId)))
2602
+ return false;
2603
+ if (typeof value.status !== "string" || !RUN_STATUSES.has(value.status) || typeof value.cancelRequested !== "boolean") return false;
2604
+ const timeline = value.timeline;
2605
+ if (!isRecord2(value.attempts) || !Array.isArray(timeline) || !Array.isArray(value.invalidEvents)) return false;
2606
+ for (const [attemptId, attempt] of Object.entries(value.attempts)) {
2607
+ if (!isRecord2(attempt) || attempt.attemptId !== attemptId || typeof attempt.stepId !== "string" || typeof attempt.disposition !== "string") return false;
2608
+ if (!EFFECT_DISPOSITIONS.has(attempt.disposition) || !isStringArray2(attempt.receiptIds) || !Array.isArray(attempt.outcomes)) return false;
2609
+ if (attempt.outputDigest !== void 0 && !isDigest(attempt.outputDigest)) return false;
2610
+ if (attempt.providerCorrelation !== void 0 && typeof attempt.providerCorrelation !== "string") return false;
2611
+ if (!attempt.outcomes.every((outcome) => isRecord2(outcome) && typeof outcome.name === "string" && isRecord2(outcome.payload) && isDigest(outcome.payloadDigest))) return false;
2612
+ }
2613
+ if (!timeline.every(
2614
+ (entry) => isRecord2(entry) && typeof entry.eventId === "string" && sourceEventIds.includes(entry.eventId) && typeof entry.kind === "string" && typeof entry.occurredAt === "string" && typeof entry.actor === "string" && typeof entry.producer === "string" && isStringArray2(entry.parents) && (entry.attemptId === void 0 || typeof entry.attemptId === "string") && (entry.stepId === void 0 || typeof entry.stepId === "string")
2615
+ ))
2616
+ return false;
2617
+ if (!headEventIds.every((eventId) => timeline.some((entry) => isRecord2(entry) && entry.eventId === eventId))) return false;
2618
+ return value.invalidEvents.every((entry) => isRecord2(entry) && typeof entry.eventId === "string" && sourceEventIds.includes(entry.eventId) && typeof entry.reason === "string");
2619
+ }
2620
+ function orderAcceptedEvents(events, acceptedEventIds) {
2621
+ const accepted = new Set(acceptedEventIds);
2622
+ const byId = /* @__PURE__ */ new Map();
2623
+ for (const event of events) if (accepted.has(event.eventId) && !byId.has(event.eventId)) byId.set(event.eventId, event);
2624
+ const indegree = new Map([...byId.keys()].map((eventId) => [eventId, 0]));
2625
+ const children = /* @__PURE__ */ new Map();
2626
+ for (const event of byId.values()) {
2627
+ for (const parent of event.parents) {
2628
+ if (!byId.has(parent)) continue;
2629
+ indegree.set(event.eventId, (indegree.get(event.eventId) ?? 0) + 1);
2630
+ children.set(parent, [...children.get(parent) ?? [], event.eventId]);
2631
+ }
2632
+ }
2633
+ const ready = [...byId.keys()].filter((eventId) => indegree.get(eventId) === 0).sort();
2634
+ const ordered = [];
2635
+ while (ready.length > 0) {
2636
+ const eventId = ready.shift();
2637
+ const event = byId.get(eventId);
2638
+ if (!event) continue;
2639
+ ordered.push(event);
2640
+ for (const childId of (children.get(eventId) ?? []).sort()) {
2641
+ const next = (indegree.get(childId) ?? 0) - 1;
2642
+ indegree.set(childId, next);
2643
+ if (next === 0) {
2644
+ ready.push(childId);
2645
+ ready.sort();
2646
+ }
2647
+ }
2648
+ }
2649
+ return ordered;
2650
+ }
2651
+ function projectAttempt(attempt) {
2652
+ return {
2653
+ attemptId: attempt.attemptId,
2654
+ stepId: attempt.stepId,
2655
+ disposition: attempt.disposition,
2656
+ receiptIds: [...attempt.receiptIds],
2657
+ outcomes: attempt.outcomes.map((outcome) => ({ ...outcome, payload: { ...outcome.payload } })),
2658
+ ...attempt.outputDigest !== void 0 ? { outputDigest: attempt.outputDigest } : {},
2659
+ ...attempt.providerCorrelation !== void 0 ? { providerCorrelation: attempt.providerCorrelation } : {}
2660
+ };
2661
+ }
2662
+ function projectTimelineEntry(event) {
2663
+ const payload = event.payload;
2664
+ return {
2665
+ eventId: event.eventId,
2666
+ kind: payload.kind,
2667
+ occurredAt: event.occurredAt,
2668
+ actor: event.actor,
2669
+ producer: event.producer,
2670
+ parents: [...event.parents],
2671
+ ..."attemptId" in payload ? { attemptId: payload.attemptId } : {},
2672
+ ..."stepId" in payload ? { stepId: payload.stepId } : {}
2673
+ };
2674
+ }
2675
+ async function projectFlowRun(genesis, events) {
2676
+ const genesisSnapshot = deepFreezeJson(JSON.parse(canonicalizeJson(genesis)));
2677
+ const eventSnapshot = deepFreezeJson(JSON.parse(canonicalizeJson(events)));
2678
+ const reduced = reduceFlowEvents(genesisSnapshot, eventSnapshot);
2679
+ const sourceEventIds = [...new Set(eventSnapshot.map((event) => event.eventId))].sort();
2680
+ const sourceEventSetDigest = await digestCanonicalJson(sourceEventIds);
2681
+ const ordered = orderAcceptedEvents(eventSnapshot, reduced.acceptedEventIds);
2682
+ const accepted = new Set(reduced.acceptedEventIds);
2683
+ const referencedParents = new Set(ordered.flatMap((event) => event.parents.filter((parent) => accepted.has(parent))));
2684
+ const headEventIds = ordered.map((event) => event.eventId).filter((eventId) => !referencedParents.has(eventId)).sort();
2685
+ const projection = {
2686
+ kind: "qi.flow.run-projection",
2687
+ schemaVersion: "1.0",
2688
+ runId: reduced.runId,
2689
+ definition: reduced.definition,
2690
+ sourceEventIds,
2691
+ sourceEventSetDigest,
2692
+ headEventIds,
2693
+ status: reduced.status,
2694
+ cancelRequested: reduced.cancelRequested,
2695
+ attempts: Object.fromEntries(Object.entries(reduced.attempts).map(([id, attempt]) => [id, projectAttempt(attempt)])),
2696
+ timeline: ordered.map(projectTimelineEntry),
2697
+ invalidEvents: reduced.invalidEvents.map((event) => ({ ...event }))
2698
+ };
2699
+ return deepFreezeJson(JSON.parse(canonicalizeJson(projection)));
2700
+ }
2701
+ async function snapshotProjection(value) {
2702
+ if (!value || typeof value !== "object") return null;
2703
+ let snapshot;
2704
+ try {
2705
+ snapshot = JSON.parse(canonicalizeJson(value));
2706
+ } catch {
2707
+ return null;
2708
+ }
2709
+ if (!hasValidProjectionShape(snapshot)) return null;
2710
+ if (await digestCanonicalJson(snapshot.sourceEventIds) !== snapshot.sourceEventSetDigest) return null;
2711
+ return deepFreezeJson(snapshot);
2712
+ }
2713
+ function canonicalStoredProjection(value) {
2714
+ try {
2715
+ return canonicalizeJson(value);
2716
+ } catch {
2717
+ return null;
2718
+ }
2719
+ }
2720
+ function flowRunProjectionStorageKey(runId, sourceEventSetDigest) {
2721
+ return `${encodeURIComponent(runId)}${FLOW_RUN_PROJECTION_KEY_SEPARATOR}${sourceEventSetDigest}`;
2722
+ }
2723
+ function projectionStoragePrefix(runId) {
2724
+ return `${encodeURIComponent(runId)}${FLOW_RUN_PROJECTION_KEY_SEPARATOR}`;
2725
+ }
2726
+ async function storedRunProjections(map, runId) {
2727
+ const projections = [];
2728
+ const pending = [];
2729
+ const prefix = projectionStoragePrefix(runId);
2730
+ map.forEach((value, key) => {
2731
+ if (!key.startsWith(prefix)) return;
2732
+ pending.push(
2733
+ snapshotProjection(value).then((projection) => {
2734
+ if (projection?.runId === runId && key === flowRunProjectionStorageKey(runId, projection.sourceEventSetDigest)) projections.push(projection);
2735
+ })
2736
+ );
2737
+ });
2738
+ await Promise.all(pending);
2739
+ return projections;
2740
+ }
2741
+ async function readFlowRunProjection(doc, genesis, events) {
2742
+ const map = doc.share.get(FLOW_RUN_PROJECTIONS_MAP_KEY);
2743
+ if (!isYMapLike(map)) return null;
2744
+ const expected = await projectFlowRun(genesis, events);
2745
+ const projection = await snapshotProjection(map.get(flowRunProjectionStorageKey(expected.runId, expected.sourceEventSetDigest)));
2746
+ if (!projection || projection.runId !== expected.runId) return null;
2747
+ return canonicalizeJson(projection) === canonicalizeJson(expected) ? projection : null;
2748
+ }
2749
+ async function repairFlowRunProjection(doc, genesis, events, verifiedEvidence = events) {
2750
+ const projection = await projectFlowRun(genesis, events);
2751
+ const canonicalProjection = canonicalizeJson(projection);
2752
+ const map = doc.getMap(FLOW_RUN_PROJECTIONS_MAP_KEY);
2753
+ const storageKey = flowRunProjectionStorageKey(projection.runId, projection.sourceEventSetDigest);
2754
+ while (true) {
2755
+ const observedValue = map.get(storageKey);
2756
+ const observedCanonical = canonicalStoredProjection(observedValue);
2757
+ const current = await snapshotProjection(observedValue);
2758
+ if (canonicalStoredProjection(map.get(storageKey)) !== observedCanonical) continue;
2759
+ const incomingIds = new Set(projection.sourceEventIds);
2760
+ const verifiedIds = new Set(verifiedEvidence.map((event) => event.eventId));
2761
+ const blocking = (await storedRunProjections(map, projection.runId)).filter((candidate) => candidate.sourceEventIds.every((eventId) => verifiedIds.has(eventId))).filter((candidate) => !candidate.sourceEventIds.every((eventId) => incomingIds.has(eventId))).sort((left, right) => left.sourceEventSetDigest.localeCompare(right.sourceEventSetDigest))[0];
2762
+ if (canonicalStoredProjection(map.get(storageKey)) !== observedCanonical) continue;
2763
+ if (blocking) {
2764
+ return { outcome: "stale", currentSourceEventSetDigest: blocking.sourceEventSetDigest };
2765
+ }
2766
+ if (current && canonicalizeJson(current) === canonicalProjection) return { outcome: "unchanged" };
2767
+ let changedWhileWriting = false;
2768
+ doc.transact(() => {
2769
+ if (canonicalStoredProjection(map.get(storageKey)) !== observedCanonical) {
2770
+ changedWhileWriting = true;
2771
+ return;
2772
+ }
2773
+ map.set(storageKey, JSON.parse(canonicalProjection));
2774
+ map.delete(projection.runId);
2775
+ }, "vnext-run-projection-repair");
2776
+ if (changedWhileWriting) continue;
2777
+ return {
2778
+ outcome: "repaired",
2779
+ ...current ? { previousSourceEventSetDigest: current.sourceEventSetDigest } : {}
2780
+ };
2781
+ }
2782
+ }
2783
+ // Annotate the CommonJS export names for ESM import in node:
2784
+ 0 && (module.exports = {
2785
+ ActionContractResolutionError,
2786
+ ComposioContractMismatchError,
2787
+ EffectClaimTransitionError,
2788
+ EncryptedMatrixFlowDefinitionRevisionRepository,
2789
+ FLOW_CAPABILITIES,
2790
+ FLOW_RUN_PROJECTIONS_MAP_KEY,
2791
+ FlowDefinitionVerificationError,
2792
+ FlowEventValidationError,
2793
+ HistoricalManifestActionContractResolver,
2794
+ LegacyFlowFrozenError,
2795
+ MATRIX_FLOW_DEFINITION_ANCHOR_TYPE,
2796
+ MATRIX_FLOW_EVENT_TYPE,
2797
+ ManifestBoundComposioActionAdapter,
2798
+ MatrixRoomFlowEventStore,
2799
+ PeerExecutionError,
2800
+ UNIVERSAL_ACTION_COMPLETED_OUTCOME,
2801
+ armEffectClaim,
2802
+ assertLegacyFlowOperationAllowed,
2803
+ buildFlowResourceUri,
2804
+ canonicalizeJson,
2805
+ claimEffect,
2806
+ computeActionContractDigest,
2807
+ computeComposioAvailabilityDigest,
2808
+ computeExecutionPolicyDigest,
2809
+ computeFlowDefinitionDigest,
2810
+ createPeerExecutor,
2811
+ deepFreezeJson,
2812
+ deriveAttemptId,
2813
+ deriveEffectClaimKey,
2814
+ deriveEventId,
2815
+ deriveReceiptId,
2816
+ deriveRunId,
2817
+ digestCanonicalJson,
2818
+ drainTopicReceiptOutbox,
2819
+ fingerprintFlowCommand,
2820
+ flowRunProjectionStorageKey,
2821
+ markEffectNeedsVerification,
2822
+ matrixFlowEventTransactionId,
2823
+ persistSignedTopicReceipt,
2824
+ prepareEffectSuccess,
2825
+ projectFlowRun,
2826
+ readFlowRunProjection,
2827
+ reduceFlowEvents,
2828
+ renewEffectClaim,
2829
+ repairFlowRunProjection,
2830
+ resolveEffectClaim,
2831
+ signComposioActionAvailability,
2832
+ signExecutionPolicy,
2833
+ signFlowDefinitionRevision,
2834
+ signFlowEvent,
2835
+ signMatrixDefinitionAnchor,
2836
+ verifyComposioActionAvailability,
2837
+ verifyExecutionPolicy,
2838
+ verifyFlowDefinitionRevision,
2839
+ verifyFlowEvent,
2840
+ verifyMatrixDefinitionAnchor
2841
+ });
2842
+ //# sourceMappingURL=index.cjs.map