@ixo/editor 6.33.0 → 6.34.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-TJCJBJZZ.js +365 -0
  4. package/dist/BidFlowDetail-TJCJBJZZ.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-UVEQMEI5.js +641 -0
  20. package/dist/ClaimFlowDetail-UVEQMEI5.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-WFCSVIIG.js +647 -0
  24. package/dist/CollectionLifecycleFlowDetail-WFCSVIIG.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-ZLCJBWHG.js +1276 -0
  28. package/dist/CollectionUsersFlowDetail-ZLCJBWHG.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-2S2N4YTW.js +564 -0
  74. package/dist/EvaluateBidFlowDetail-2S2N4YTW.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-QYR7PJRD.js +2237 -0
  78. package/dist/EvaluateClaimFlowDetail-QYR7PJRD.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-WGKO43IH.js +83 -0
  166. package/dist/IdentityCreateFlowDetail-WGKO43IH.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-6M32S6XS.js +57 -0
  170. package/dist/IidCreateFlowDetail-6M32S6XS.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-EWOMXSD3.js +421 -0
  174. package/dist/KycVerifyFlowDetail-EWOMXSD3.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-73BHAN76.js +255 -0
  198. package/dist/OracleConfigureOracleFlowDetail-73BHAN76.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-BFV2EHLT.js +220 -0
  228. package/dist/OracleStoreSecretsAndConfigFlowDetail-BFV2EHLT.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-DNNOPHVA.js +197 -0
  232. package/dist/OracleStoreSecretsFlowDetail-DNNOPHVA.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-4VZZPAWH.js +235 -0
  236. package/dist/ProposalCreateFlowDetail-4VZZPAWH.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-2WPEATI7.js +315 -0
  285. package/dist/chunk-2WPEATI7.js.map +1 -0
  286. package/dist/chunk-3O42FYT3.js +3333 -0
  287. package/dist/chunk-3O42FYT3.js.map +1 -0
  288. package/dist/chunk-3TUYY4HK.js +20 -0
  289. package/dist/chunk-3TUYY4HK.js.map +1 -0
  290. package/dist/chunk-3XSLBJYI.js +554 -0
  291. package/dist/chunk-3XSLBJYI.js.map +1 -0
  292. package/dist/chunk-4DGCCXD6.js +710 -0
  293. package/dist/chunk-4DGCCXD6.js.map +1 -0
  294. package/dist/chunk-4NAFQF6V.js +11 -0
  295. package/dist/chunk-4NAFQF6V.js.map +1 -0
  296. package/dist/chunk-4PONO4US.js +799 -0
  297. package/dist/chunk-4PONO4US.js.map +1 -0
  298. package/dist/chunk-4TMOIK5M.js +21 -0
  299. package/dist/chunk-4TMOIK5M.js.map +1 -0
  300. package/dist/chunk-5IH3VC5I.js +102 -0
  301. package/dist/chunk-5IH3VC5I.js.map +1 -0
  302. package/dist/chunk-5NTKDOP6.js +89 -0
  303. package/dist/chunk-5NTKDOP6.js.map +1 -0
  304. package/dist/chunk-5O2SFRGU.js +18 -0
  305. package/dist/chunk-5O2SFRGU.js.map +1 -0
  306. package/dist/chunk-632JLECF.js +55 -0
  307. package/dist/chunk-632JLECF.js.map +1 -0
  308. package/dist/chunk-676HDB7K.js +95 -0
  309. package/dist/chunk-676HDB7K.js.map +1 -0
  310. package/dist/chunk-6ESTNTSH.js +223 -0
  311. package/dist/chunk-6ESTNTSH.js.map +1 -0
  312. package/dist/chunk-6GKJR52N.js +15 -0
  313. package/dist/chunk-6GKJR52N.js.map +1 -0
  314. package/dist/chunk-6L4ZIKYU.js +23 -0
  315. package/dist/chunk-6L4ZIKYU.js.map +1 -0
  316. package/dist/chunk-76YX5R4L.js +11 -0
  317. package/dist/chunk-76YX5R4L.js.map +1 -0
  318. package/dist/chunk-7J3GFMN3.js +32 -0
  319. package/dist/chunk-7J3GFMN3.js.map +1 -0
  320. package/dist/chunk-7LSARC2G.js +102 -0
  321. package/dist/chunk-7LSARC2G.js.map +1 -0
  322. package/dist/chunk-7W7UUUIE.js +609 -0
  323. package/dist/chunk-7W7UUUIE.js.map +1 -0
  324. package/dist/chunk-7ZLW7H37.js +21 -0
  325. package/dist/chunk-7ZLW7H37.js.map +1 -0
  326. package/dist/chunk-AAZHI22G.js +18 -0
  327. package/dist/chunk-AAZHI22G.js.map +1 -0
  328. package/dist/chunk-ACNE455I.js +76 -0
  329. package/dist/chunk-ACNE455I.js.map +1 -0
  330. package/dist/chunk-BKLSSLPZ.js +27 -0
  331. package/dist/chunk-BKLSSLPZ.js.map +1 -0
  332. package/dist/chunk-BZ7UPUTY.js +417 -0
  333. package/dist/chunk-BZ7UPUTY.js.map +1 -0
  334. package/dist/chunk-CGFAICUE.js +28 -0
  335. package/dist/chunk-CGFAICUE.js.map +1 -0
  336. package/dist/chunk-CMCEWQ3C.js +19 -0
  337. package/dist/chunk-CMCEWQ3C.js.map +1 -0
  338. package/dist/chunk-CP4UV436.js +41 -0
  339. package/dist/chunk-CP4UV436.js.map +1 -0
  340. package/dist/chunk-D2CQPNQG.js +27508 -0
  341. package/dist/chunk-D2CQPNQG.js.map +1 -0
  342. package/dist/chunk-DIQRZP7Z.js +51 -0
  343. package/dist/chunk-DIQRZP7Z.js.map +1 -0
  344. package/dist/chunk-EBFFDDAS.js +13 -0
  345. package/dist/chunk-EBFFDDAS.js.map +1 -0
  346. package/dist/chunk-EGVS23DR.js +85 -0
  347. package/dist/chunk-EGVS23DR.js.map +1 -0
  348. package/dist/chunk-EKBQ7K4N.js +15 -0
  349. package/dist/chunk-EKBQ7K4N.js.map +1 -0
  350. package/dist/chunk-EKQCZRAN.js +24 -0
  351. package/dist/chunk-EKQCZRAN.js.map +1 -0
  352. package/dist/chunk-EYKZIZ5J.js +48 -0
  353. package/dist/chunk-EYKZIZ5J.js.map +1 -0
  354. package/dist/{chunk-NEOPTPDF.js → chunk-F4PTFXZH.js} +11554 -22046
  355. package/dist/chunk-F4PTFXZH.js.map +1 -0
  356. package/dist/chunk-FFYZXA75.js +58 -0
  357. package/dist/chunk-FFYZXA75.js.map +1 -0
  358. package/dist/chunk-GFGDHPZ2.js +22 -0
  359. package/dist/chunk-GFGDHPZ2.js.map +1 -0
  360. package/dist/chunk-GR3CDFID.js +18 -0
  361. package/dist/chunk-GR3CDFID.js.map +1 -0
  362. package/dist/chunk-GR4SIU32.js +104 -0
  363. package/dist/chunk-GR4SIU32.js.map +1 -0
  364. package/dist/chunk-H5E46IIS.js +18 -0
  365. package/dist/chunk-H5E46IIS.js.map +1 -0
  366. package/dist/chunk-HFHVAMZL.js +22 -0
  367. package/dist/chunk-HFHVAMZL.js.map +1 -0
  368. package/dist/chunk-HRRI4BLF.js +4456 -0
  369. package/dist/chunk-HRRI4BLF.js.map +1 -0
  370. package/dist/chunk-HT6L7A5M.js +12 -0
  371. package/dist/chunk-HT6L7A5M.js.map +1 -0
  372. package/dist/chunk-I2FPFISM.js +301 -0
  373. package/dist/chunk-I2FPFISM.js.map +1 -0
  374. package/dist/chunk-IADAQJDH.js +28 -0
  375. package/dist/chunk-IADAQJDH.js.map +1 -0
  376. package/dist/chunk-IBOBCMQQ.js +99 -0
  377. package/dist/chunk-IBOBCMQQ.js.map +1 -0
  378. package/dist/chunk-IFWKRCFF.js +56 -0
  379. package/dist/chunk-IFWKRCFF.js.map +1 -0
  380. package/dist/chunk-IH4T7V4C.js +40 -0
  381. package/dist/chunk-IH4T7V4C.js.map +1 -0
  382. package/dist/chunk-IIIZZ4E4.js +1679 -0
  383. package/dist/chunk-IIIZZ4E4.js.map +1 -0
  384. package/dist/chunk-ILSFU3WD.js +83 -0
  385. package/dist/chunk-ILSFU3WD.js.map +1 -0
  386. package/dist/chunk-IX3VBV3L.js +43 -0
  387. package/dist/chunk-IX3VBV3L.js.map +1 -0
  388. package/dist/chunk-JBBFSORW.js +846 -0
  389. package/dist/chunk-JBBFSORW.js.map +1 -0
  390. package/dist/chunk-JIDTNKKL.js +1183 -0
  391. package/dist/chunk-JIDTNKKL.js.map +1 -0
  392. package/dist/chunk-JSPE6NGZ.js +22 -0
  393. package/dist/chunk-JSPE6NGZ.js.map +1 -0
  394. package/dist/chunk-JVROGQ7Q.js +150 -0
  395. package/dist/chunk-JVROGQ7Q.js.map +1 -0
  396. package/dist/chunk-K4WUMWNJ.js +32 -0
  397. package/dist/chunk-K4WUMWNJ.js.map +1 -0
  398. package/dist/chunk-K74XQ4Q5.js +11 -0
  399. package/dist/chunk-K74XQ4Q5.js.map +1 -0
  400. package/dist/chunk-KLLMJ4U3.js +22 -0
  401. package/dist/chunk-KLLMJ4U3.js.map +1 -0
  402. package/dist/chunk-LTKVCJ2E.js +27 -0
  403. package/dist/chunk-LTKVCJ2E.js.map +1 -0
  404. package/dist/chunk-M36DJTFZ.js +34 -0
  405. package/dist/chunk-M36DJTFZ.js.map +1 -0
  406. package/dist/chunk-MHM52LCJ.js +154 -0
  407. package/dist/chunk-MHM52LCJ.js.map +1 -0
  408. package/dist/chunk-MQCDMHRZ.js +59 -0
  409. package/dist/chunk-MQCDMHRZ.js.map +1 -0
  410. package/dist/chunk-N3ORMGAI.js +348 -0
  411. package/dist/chunk-N3ORMGAI.js.map +1 -0
  412. package/dist/chunk-NCSGIRRQ.js +28 -0
  413. package/dist/chunk-NCSGIRRQ.js.map +1 -0
  414. package/dist/chunk-NIXT2SBH.js +1423 -0
  415. package/dist/chunk-NIXT2SBH.js.map +1 -0
  416. package/dist/chunk-NJAII6CO.js +148 -0
  417. package/dist/chunk-NJAII6CO.js.map +1 -0
  418. package/dist/chunk-NKE4TL43.js +92 -0
  419. package/dist/chunk-NKE4TL43.js.map +1 -0
  420. package/dist/chunk-NZ7AXA7B.js +1 -0
  421. package/dist/chunk-NZ7AXA7B.js.map +1 -0
  422. package/dist/chunk-OCAYEGI2.js +26 -0
  423. package/dist/chunk-OCAYEGI2.js.map +1 -0
  424. package/dist/chunk-OMLI45ER.js +90 -0
  425. package/dist/chunk-OMLI45ER.js.map +1 -0
  426. package/dist/chunk-P7OBLJAG.js +88 -0
  427. package/dist/chunk-P7OBLJAG.js.map +1 -0
  428. package/dist/chunk-PAY3CBWL.js +2321 -0
  429. package/dist/chunk-PAY3CBWL.js.map +1 -0
  430. package/dist/chunk-PFF6VY35.js +257 -0
  431. package/dist/chunk-PFF6VY35.js.map +1 -0
  432. package/dist/chunk-PYNDJDWZ.js +1758 -0
  433. package/dist/chunk-PYNDJDWZ.js.map +1 -0
  434. package/dist/chunk-QDQ6UMMN.js +53 -0
  435. package/dist/chunk-QDQ6UMMN.js.map +1 -0
  436. package/dist/chunk-QGT3G2XG.js +24 -0
  437. package/dist/chunk-QGT3G2XG.js.map +1 -0
  438. package/dist/chunk-QZYCJ2GZ.js +55 -0
  439. package/dist/chunk-QZYCJ2GZ.js.map +1 -0
  440. package/dist/chunk-REZ7RFSA.js +124 -0
  441. package/dist/chunk-REZ7RFSA.js.map +1 -0
  442. package/dist/chunk-RRYBAE6E.js +2449 -0
  443. package/dist/chunk-RRYBAE6E.js.map +1 -0
  444. package/dist/chunk-RWUZOB62.js +34 -0
  445. package/dist/chunk-RWUZOB62.js.map +1 -0
  446. package/dist/chunk-SB5UCPZH.js +116 -0
  447. package/dist/chunk-SB5UCPZH.js.map +1 -0
  448. package/dist/chunk-SEJJ7CRI.js +99 -0
  449. package/dist/chunk-SEJJ7CRI.js.map +1 -0
  450. package/dist/chunk-SHBFGRPV.js +45 -0
  451. package/dist/chunk-SHBFGRPV.js.map +1 -0
  452. package/dist/chunk-SOFJ4GC5.js +45 -0
  453. package/dist/chunk-SOFJ4GC5.js.map +1 -0
  454. package/dist/chunk-STH2HPZK.js +44 -0
  455. package/dist/chunk-STH2HPZK.js.map +1 -0
  456. package/dist/chunk-TK3JNKME.js +28 -0
  457. package/dist/chunk-TK3JNKME.js.map +1 -0
  458. package/dist/chunk-TMONHFE3.js +46 -0
  459. package/dist/chunk-TMONHFE3.js.map +1 -0
  460. package/dist/chunk-TR4KO3AG.js +44 -0
  461. package/dist/chunk-TR4KO3AG.js.map +1 -0
  462. package/dist/chunk-TS2LNBF2.js +68 -0
  463. package/dist/chunk-TS2LNBF2.js.map +1 -0
  464. package/dist/chunk-UZUMBFPP.js +26 -0
  465. package/dist/chunk-UZUMBFPP.js.map +1 -0
  466. package/dist/chunk-VRZ5LMOW.js +176 -0
  467. package/dist/chunk-VRZ5LMOW.js.map +1 -0
  468. package/dist/chunk-WLGGY6Z6.js +75 -0
  469. package/dist/chunk-WLGGY6Z6.js.map +1 -0
  470. package/dist/chunk-WO7V6ZNC.js +11 -0
  471. package/dist/chunk-WO7V6ZNC.js.map +1 -0
  472. package/dist/chunk-WXSENSRP.js +64 -0
  473. package/dist/chunk-WXSENSRP.js.map +1 -0
  474. package/dist/chunk-XEKBZ2SA.js +19 -0
  475. package/dist/chunk-XEKBZ2SA.js.map +1 -0
  476. package/dist/chunk-XPBKU3JX.js +61 -0
  477. package/dist/chunk-XPBKU3JX.js.map +1 -0
  478. package/dist/chunk-XRYXBXWH.js +24 -0
  479. package/dist/chunk-XRYXBXWH.js.map +1 -0
  480. package/dist/chunk-XVA7QRVH.js +22 -0
  481. package/dist/chunk-XVA7QRVH.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,3333 @@
1
+ import {
2
+ appendAgentLedgerEvent,
3
+ capabilityForCommand,
4
+ computeAgentCommandId,
5
+ createIntentHash,
6
+ createYDocRuntimeManager,
7
+ deriveBlockPhase,
8
+ evaluateBlockExecutionEligibilityForRun,
9
+ executeActionBlock,
10
+ getAssigneeDid,
11
+ getBlockActionType,
12
+ getBlockId,
13
+ getBlockProps,
14
+ getBlockTitle,
15
+ getBlockType,
16
+ getDueAt,
17
+ getFlowAgentMaps,
18
+ isRuntimeRef,
19
+ parseConditionConfigStrict,
20
+ parseJsonProp,
21
+ queueAgentCommand,
22
+ readAgentCommands,
23
+ readPendingInvocations,
24
+ readQueuedAgentCommands,
25
+ updateAgentCommand
26
+ } from "./chunk-HRRI4BLF.js";
27
+ import {
28
+ boundRunActionOutput,
29
+ generateActionManifest,
30
+ readPendingRunTimelineEvents,
31
+ retryPendingRunTimelineEvents
32
+ } from "./chunk-F4PTFXZH.js";
33
+ import {
34
+ createDesignPodPortalJourneyPlan,
35
+ seedDesignPodMethodDefinition
36
+ } from "./chunk-JIDTNKKL.js";
37
+ import {
38
+ capabilityPatternCoversCan,
39
+ collectPhantomLegacyRun,
40
+ getAction,
41
+ getActionByCan,
42
+ getEventsForBlock,
43
+ hasLegacyRuntimeHistory,
44
+ readActionState,
45
+ resetActionState,
46
+ resolveActiveRunId,
47
+ resolveRunIdForExecution,
48
+ resolveRunIdForRead,
49
+ setMultiRunStorage,
50
+ sha256Digest,
51
+ writeActionState
52
+ } from "./chunk-IIIZZ4E4.js";
53
+ import {
54
+ isYMapLike,
55
+ isYXmlElementLike
56
+ } from "./chunk-NCSGIRRQ.js";
57
+
58
+ // src/core/lib/sharedFlowDocument.ts
59
+ import { MatrixCRDTEventTranslator, MatrixProvider, MatrixReader } from "@ixo/matrix-crdt";
60
+ import { Direction, Filter } from "matrix-js-sdk";
61
+ import * as Y from "yjs";
62
+
63
+ // src/core/lib/flowDocumentCache.ts
64
+ var DATABASE = "ixo-flow-checkpoints-v1";
65
+ var MAX_AGE = 7 * 24 * 60 * 60 * 1e3;
66
+ async function identity(client, roomId) {
67
+ const token = client.getAccessToken?.();
68
+ if (!token || !globalThis.crypto?.subtle || typeof indexedDB === "undefined") return;
69
+ const scope = JSON.stringify([client.getHomeserverUrl(), client.getUserId(), roomId]);
70
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${scope}\0${token}`));
71
+ const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
72
+ return { scope, key };
73
+ }
74
+ async function database() {
75
+ return new Promise((resolve, reject) => {
76
+ const request = indexedDB.open(DATABASE, 1);
77
+ request.onupgradeneeded = () => request.result.createObjectStore("documents");
78
+ request.onsuccess = () => resolve(request.result);
79
+ request.onerror = () => reject(request.error);
80
+ request.onblocked = () => reject(new Error("Flow cache is blocked"));
81
+ });
82
+ }
83
+ async function readFlowCheckpoint(client, roomId) {
84
+ try {
85
+ const auth = await identity(client, roomId);
86
+ if (!auth) return;
87
+ const db = await database();
88
+ const record = await new Promise((resolve, reject) => {
89
+ const transaction = db.transaction("documents", "readonly");
90
+ const request = transaction.objectStore("documents").get(auth.scope);
91
+ request.onsuccess = () => resolve(request.result);
92
+ request.onerror = () => reject(request.error);
93
+ transaction.oncomplete = () => db.close();
94
+ transaction.onabort = () => db.close();
95
+ });
96
+ if (!record || Date.now() - record.savedAt > MAX_AGE) return;
97
+ const clear = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(auth.scope) }, auth.key, record.data);
98
+ const value = JSON.parse(new TextDecoder().decode(clear));
99
+ if (!Array.isArray(value.update) || !value.token) return;
100
+ return { update: new Uint8Array(value.update), token: value.token, savedAt: record.savedAt };
101
+ } catch {
102
+ return;
103
+ }
104
+ }
105
+ async function writeFlowCheckpoint(client, roomId, checkpoint) {
106
+ try {
107
+ if (checkpoint.update.byteLength > 8 * 1024 * 1024) return;
108
+ const auth = await identity(client, roomId);
109
+ if (!auth) return;
110
+ const iv = crypto.getRandomValues(new Uint8Array(12));
111
+ const data = await crypto.subtle.encrypt(
112
+ { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(auth.scope) },
113
+ auth.key,
114
+ new TextEncoder().encode(JSON.stringify({ update: Array.from(checkpoint.update), token: checkpoint.token }))
115
+ );
116
+ const db = await database();
117
+ await new Promise((resolve, reject) => {
118
+ const transaction = db.transaction("documents", "readwrite");
119
+ const store = transaction.objectStore("documents");
120
+ store.put({ iv, data, savedAt: checkpoint.savedAt }, auth.scope);
121
+ const request = store.openCursor();
122
+ const records = [];
123
+ request.onsuccess = () => {
124
+ const cursor = request.result;
125
+ if (!cursor) {
126
+ records.sort((a, b) => b.savedAt - a.savedAt);
127
+ for (const record of records.slice(32)) store.delete(record.key);
128
+ return;
129
+ }
130
+ if (Date.now() - cursor.value.savedAt > MAX_AGE) cursor.delete();
131
+ else records.push({ key: cursor.key, savedAt: cursor.value.savedAt });
132
+ cursor.continue();
133
+ };
134
+ transaction.oncomplete = () => {
135
+ db.close();
136
+ resolve();
137
+ };
138
+ transaction.onerror = () => {
139
+ db.close();
140
+ reject(transaction.error);
141
+ };
142
+ transaction.onabort = () => {
143
+ db.close();
144
+ reject(transaction.error);
145
+ };
146
+ });
147
+ } catch {
148
+ return;
149
+ }
150
+ }
151
+
152
+ // src/core/lib/sharedFlowDocument.ts
153
+ var sessions = /* @__PURE__ */ new WeakMap();
154
+ var RETAIN_MS = 5 * 60 * 1e3;
155
+ var activeLoads = 0;
156
+ var loadQueue = [];
157
+ function withLoadSlot(read, visible) {
158
+ return new Promise((resolve, reject) => {
159
+ const start = () => {
160
+ activeLoads++;
161
+ void read().then(resolve, reject).finally(() => {
162
+ activeLoads--;
163
+ loadQueue.sort((a, b) => Number(b.visible) - Number(a.visible));
164
+ loadQueue.shift()?.start();
165
+ });
166
+ };
167
+ if (activeLoads < 4) start();
168
+ else loadQueue.push({ visible, start });
169
+ });
170
+ }
171
+ function syntheticSnapshot(update) {
172
+ let binary = "";
173
+ for (const byte of update) binary += String.fromCharCode(byte);
174
+ return { type: "matrix-crdt.doc_snapshot", event_id: "$local-checkpoint", sender: "@local:cache", origin_server_ts: 0, content: { update: btoa(binary) } };
175
+ }
176
+ function clientWithHistory(client, history) {
177
+ let first = true;
178
+ return new Proxy(client, {
179
+ get(target, property) {
180
+ if (property === "createMessagesRequest") {
181
+ return async (...args) => {
182
+ if (first && !args[1] && args[3] === Direction.Backward) {
183
+ first = false;
184
+ const response = await history();
185
+ if (response) return response;
186
+ }
187
+ return target.createMessagesRequest(args[0], args[1], 200, args[3], args[4]);
188
+ };
189
+ }
190
+ const value = Reflect.get(target, property);
191
+ return typeof value === "function" ? value.bind(target) : value;
192
+ }
193
+ });
194
+ }
195
+ async function readFlowDocumentHistory(client, roomId, checkpoint) {
196
+ const room = client.getRoom(roomId);
197
+ if (checkpoint && Date.now() - checkpoint.savedAt > 30 * 60 * 1e3 && room && !room.currentState.getStateEvents("m.room.encryption", "")) checkpoint = void 0;
198
+ if (checkpoint) {
199
+ try {
200
+ Y.decodeUpdate(checkpoint.update);
201
+ } catch {
202
+ checkpoint = void 0;
203
+ }
204
+ }
205
+ const translator = new MatrixCRDTEventTranslator();
206
+ const filter = new Filter(client.getUserId() ?? void 0);
207
+ filter.setDefinition({ room: { timeline: { types: [...translator.readEventTypes, "m.room.encrypted"] } } });
208
+ const readerClient = clientWithHistory(client, async () => {
209
+ let token = checkpoint?.token;
210
+ let initial = checkpoint ? [syntheticSnapshot(checkpoint.update)] : [];
211
+ let recent;
212
+ if (!token) {
213
+ const room2 = client.getRoom(roomId);
214
+ if (!room2 || room2.currentState.getStateEvents("m.room.encryption", "")) return;
215
+ recent = await client.createMessagesRequest(roomId, "", 200, Direction.Backward, filter);
216
+ if (!recent.end || recent.end === recent.start || recent.chunk.some((event) => translator.isAnySnapshotEvent(event))) return recent;
217
+ const snapshots = new Filter(client.getUserId() ?? void 0);
218
+ snapshots.setDefinition({ room: { timeline: { types: ["matrix-crdt.doc_snapshot", "matrix-crdt.doc_snapshot_v2"] } } });
219
+ try {
220
+ const page = await client.createMessagesRequest(roomId, "", 1, Direction.Backward, snapshots);
221
+ if (!page.chunk.length || !page.end) return recent;
222
+ token = page.end;
223
+ } catch {
224
+ return recent;
225
+ }
226
+ }
227
+ try {
228
+ for (; ; ) {
229
+ const page = await client.createMessagesRequest(roomId, token, 200, Direction.Forward, filter);
230
+ initial.push(...page.chunk);
231
+ if (!page.end || page.end === token || page.chunk.length === 0) {
232
+ return { chunk: initial.reverse(), start: page.end || token, end: void 0 };
233
+ }
234
+ token = page.end;
235
+ }
236
+ } catch {
237
+ return recent;
238
+ }
239
+ });
240
+ let reader = new MatrixReader(readerClient, roomId, translator);
241
+ try {
242
+ let events;
243
+ try {
244
+ events = await reader.getInitialDocumentUpdateEvents();
245
+ } catch {
246
+ reader.dispose();
247
+ reader = new MatrixReader(
248
+ clientWithHistory(client, async () => void 0),
249
+ roomId,
250
+ translator
251
+ );
252
+ events = await reader.getInitialDocumentUpdateEvents();
253
+ }
254
+ if (reader.snapshotDegradations.length) {
255
+ reader.dispose();
256
+ reader = new MatrixReader(
257
+ clientWithHistory(client, async () => void 0),
258
+ roomId,
259
+ translator
260
+ );
261
+ events = await reader.getInitialDocumentUpdateEvents();
262
+ }
263
+ const updates = events.map((event) => translator.getUpdateBytes(event)).filter((update) => !!update);
264
+ return { update: updates.length ? Y.mergeUpdates(updates) : Y.encodeStateAsUpdate(new Y.Doc()), token: reader.latestToken };
265
+ } finally {
266
+ reader.dispose();
267
+ }
268
+ }
269
+ var SharedFlowDocument = class {
270
+ constructor(client, roomId) {
271
+ this.client = client;
272
+ this.roomId = roomId;
273
+ this.doc = new Y.Doc();
274
+ this.lastAccess = Date.now();
275
+ this.status = "disconnected";
276
+ this.ready = false;
277
+ this.provider = null;
278
+ this.listeners = /* @__PURE__ */ new Set();
279
+ this.live = /* @__PURE__ */ new Set();
280
+ this.attempt = 0;
281
+ this.generation = 0;
282
+ this.notify = () => {
283
+ for (const listener of this.listeners) listener();
284
+ };
285
+ this.flush = () => {
286
+ void this.provider?.waitForFlush().catch(() => void 0);
287
+ };
288
+ this.reconnect = async () => {
289
+ clearTimeout(this.retry);
290
+ this.attempt = 0;
291
+ await this.stopProvider();
292
+ await this.connect();
293
+ };
294
+ }
295
+ watchPageExit(enabled) {
296
+ if (typeof window === "undefined") return;
297
+ if (enabled) {
298
+ window.addEventListener("pagehide", this.flush);
299
+ window.addEventListener("beforeunload", this.flush);
300
+ } else {
301
+ window.removeEventListener("pagehide", this.flush);
302
+ window.removeEventListener("beforeunload", this.flush);
303
+ }
304
+ }
305
+ evictIfIdle() {
306
+ if (this.listeners.size || this.pending) return false;
307
+ this.generation++;
308
+ clearTimeout(this.idle);
309
+ clearTimeout(this.retry);
310
+ clearTimeout(this.stopTimer);
311
+ if (sessions.get(this.client)?.get(this.roomId) === this) sessions.get(this.client)?.delete(this.roomId);
312
+ void this.stopProvider().finally(() => this.doc.destroy());
313
+ return true;
314
+ }
315
+ subscribe(listener, live = true) {
316
+ this.lastAccess = Date.now();
317
+ clearTimeout(this.idle);
318
+ clearTimeout(this.stopTimer);
319
+ this.listeners.add(listener);
320
+ if (live) this.live.add(listener);
321
+ void this.connect();
322
+ return () => {
323
+ this.listeners.delete(listener);
324
+ this.live.delete(listener);
325
+ if (!this.live.size && this.provider)
326
+ this.stopTimer = setTimeout(() => {
327
+ if (!this.live.size) void this.stopProvider();
328
+ }, 1e3);
329
+ if (!this.listeners.size) {
330
+ clearTimeout(this.retry);
331
+ this.idle = setTimeout(() => {
332
+ this.evictIfIdle();
333
+ }, RETAIN_MS);
334
+ this.idle.unref?.();
335
+ }
336
+ };
337
+ }
338
+ connect() {
339
+ if (this.pending) return this.pending;
340
+ if (this.provider || this.ready && !this.live.size && this.checkpoint && Date.now() - this.checkpoint.savedAt < 3e4) return Promise.resolve();
341
+ const generation = this.generation;
342
+ this.status = "connecting";
343
+ this.notify();
344
+ this.pending = (async () => {
345
+ await this.stopping;
346
+ if (!this.checkpoint) {
347
+ const membership = this.client.getRoom(this.roomId)?.getMyMembership?.();
348
+ if (!membership || membership === "join") this.checkpoint = await readFlowCheckpoint(this.client, this.roomId);
349
+ if (generation !== this.generation) return;
350
+ if (this.checkpoint) {
351
+ try {
352
+ Y.decodeUpdate(this.checkpoint.update);
353
+ Y.applyUpdate(this.doc, this.checkpoint.update, this);
354
+ this.ready = true;
355
+ this.notify();
356
+ } catch {
357
+ this.checkpoint = void 0;
358
+ }
359
+ }
360
+ }
361
+ const result = await withLoadSlot(() => readFlowDocumentHistory(this.client, this.roomId, this.checkpoint), this.live.size > 0);
362
+ if (generation !== this.generation) return;
363
+ Y.applyUpdate(this.doc, result.update, this);
364
+ this.ready = true;
365
+ this.error = void 0;
366
+ this.attempt = 0;
367
+ if (result.token) this.checkpoint = { update: result.update, token: result.token, savedAt: Date.now() };
368
+ this.status = this.live.size ? "connecting" : "connected";
369
+ if (this.live.size) {
370
+ const providerClient = clientWithHistory(
371
+ this.client,
372
+ async () => ({
373
+ chunk: [syntheticSnapshot(result.update)],
374
+ start: result.token,
375
+ end: void 0
376
+ })
377
+ );
378
+ const provider = new MatrixProvider(
379
+ this.doc,
380
+ providerClient,
381
+ { type: "id", id: this.roomId },
382
+ {
383
+ translator: { enableMediaSnapshots: true },
384
+ reader: { snapshotInterval: 10 },
385
+ writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 },
386
+ enableAwareness: true,
387
+ enableExperimentalWebrtcSync: true
388
+ }
389
+ );
390
+ this.provider = provider;
391
+ this.watchPageExit(true);
392
+ provider.onDocumentUnavailable(() => {
393
+ if (this.provider !== provider) return;
394
+ this.status = "error";
395
+ this.error = "Flow document is unavailable";
396
+ this.notify();
397
+ });
398
+ provider.onDocumentAvailable(() => {
399
+ if (this.provider !== provider) return;
400
+ this.status = "connected";
401
+ this.error = void 0;
402
+ this.notify();
403
+ });
404
+ void provider.initialize().catch((error) => {
405
+ if (this.provider !== provider) return;
406
+ provider.dispose();
407
+ this.watchPageExit(false);
408
+ this.provider = null;
409
+ this.fail(error);
410
+ });
411
+ }
412
+ this.save();
413
+ this.notify();
414
+ })().catch((error) => {
415
+ if (generation === this.generation) this.fail(error);
416
+ }).finally(() => {
417
+ this.pending = void 0;
418
+ });
419
+ return this.pending;
420
+ }
421
+ fail(error) {
422
+ const code = error?.errcode;
423
+ if (code === "M_FORBIDDEN" || code === "M_UNKNOWN_TOKEN") {
424
+ this.ready = false;
425
+ this.checkpoint = void 0;
426
+ }
427
+ this.status = "error";
428
+ this.error = error instanceof Error ? error.message : String(error);
429
+ this.notify();
430
+ clearTimeout(this.retry);
431
+ if (this.listeners.size) this.retry = setTimeout(() => void this.connect(), Math.min(5e3 * 2 ** this.attempt++, 3e4));
432
+ }
433
+ save() {
434
+ if (this.checkpoint && this.ready) void writeFlowCheckpoint(this.client, this.roomId, this.checkpoint);
435
+ }
436
+ async stopProvider() {
437
+ const provider = this.provider;
438
+ if (!provider) return;
439
+ this.save();
440
+ this.watchPageExit(false);
441
+ this.provider = null;
442
+ this.stopping = (async () => {
443
+ let timer;
444
+ try {
445
+ await Promise.race([
446
+ provider.waitForFlush(),
447
+ new Promise((resolve) => {
448
+ timer = setTimeout(resolve, 3e3);
449
+ })
450
+ ]);
451
+ } catch {
452
+ return;
453
+ } finally {
454
+ clearTimeout(timer);
455
+ provider.dispose();
456
+ }
457
+ })();
458
+ await this.stopping;
459
+ this.stopping = void 0;
460
+ }
461
+ };
462
+ function getSharedFlowDocument(client, roomId) {
463
+ let rooms = sessions.get(client);
464
+ if (!rooms) {
465
+ rooms = /* @__PURE__ */ new Map();
466
+ sessions.set(client, rooms);
467
+ }
468
+ let session = rooms.get(roomId);
469
+ if (!session) {
470
+ session = new SharedFlowDocument(client, roomId);
471
+ rooms.set(roomId, session);
472
+ }
473
+ session.lastAccess = Date.now();
474
+ if (rooms.size > 32) {
475
+ for (const candidate of [...rooms.values()].sort((a, b) => a.lastAccess - b.lastAccess)) {
476
+ if (rooms.size <= 32) break;
477
+ if (candidate !== session && Date.now() - candidate.lastAccess > 1e3) candidate.evictIfIdle();
478
+ }
479
+ }
480
+ return session;
481
+ }
482
+
483
+ // src/core/lib/flowCompiler/conditions.ts
484
+ var OPERATOR_MAP = {
485
+ // BaseUcan ConditionRef vocabulary
486
+ eq: "equals",
487
+ neq: "not_equals",
488
+ gt: "greater_than",
489
+ lt: "less_than",
490
+ in: "contains",
491
+ exists: "is_not_empty",
492
+ // Friendly camelCase (plugin FlowSpec `is`)
493
+ equals: "equals",
494
+ notEquals: "not_equals",
495
+ greaterThan: "greater_than",
496
+ lessThan: "less_than",
497
+ isEmpty: "is_empty",
498
+ isNotEmpty: "is_not_empty",
499
+ // Evaluator vocabulary passthrough
500
+ not_equals: "not_equals",
501
+ greater_than: "greater_than",
502
+ less_than: "less_than",
503
+ contains: "contains",
504
+ not_contains: "not_contains",
505
+ notContains: "not_contains",
506
+ is_empty: "is_empty",
507
+ is_not_empty: "is_not_empty"
508
+ };
509
+ function toEvaluatorOperator(operator) {
510
+ return OPERATOR_MAP[operator] ?? "equals";
511
+ }
512
+ function buildBlockConditionsProp(conditions, opts) {
513
+ return JSON.stringify({
514
+ enabled: opts?.enabled ?? true,
515
+ mode: opts?.mode ?? "all_must_pass",
516
+ conditions: conditions.map((c, i) => ({
517
+ id: `cond_${c.sourceBlockId}_${c.property}_${i}`,
518
+ name: c.name ?? `Condition from ${c.sourceBlockId}`,
519
+ sourceBlockId: c.sourceBlockId,
520
+ sourceBlockType: c.sourceBlockType ?? "action",
521
+ rule: {
522
+ type: "property_value",
523
+ property: c.property,
524
+ operator: toEvaluatorOperator(c.operator),
525
+ value: c.value
526
+ },
527
+ effect: c.effect ?? { action: "enable" }
528
+ }))
529
+ });
530
+ }
531
+
532
+ // src/core/lib/flowCompiler/blockMapping.ts
533
+ var ICON_DEFAULTS = {
534
+ "bid/submit": "gavel",
535
+ "bid/evaluate": "check-circle",
536
+ "claim/submit": "file-check",
537
+ "claim/evaluate": "clipboard-check",
538
+ "email/send": "mail",
539
+ "notification/push": "bell",
540
+ "matrix/dm": "message-circle",
541
+ "proposal/create": "scroll",
542
+ "proposal/vote": "vote",
543
+ "domain/card-preview": "id",
544
+ "domain/sign": "feather",
545
+ "credential/store": "shield",
546
+ "http/request": "cloud",
547
+ "protocol/select": "git-branch",
548
+ "human/checkbox": "check-square",
549
+ "human/form": "file-text",
550
+ "form/submit": "file-text",
551
+ "oracle/query": "cpu"
552
+ };
553
+ function compileBlockProps(cap, registryType) {
554
+ return {
555
+ title: cap.title || cap.can,
556
+ description: cap.description || "",
557
+ icon: cap.icon || ICON_DEFAULTS[cap.can] || "bolt",
558
+ actionType: registryType,
559
+ inputs: JSON.stringify(cap.nb || {}),
560
+ requiresConfirmation: "",
561
+ conditions: "",
562
+ // compiled separately by the compiler
563
+ // Authorization props
564
+ parentCapability: cap.actor?.parentCapability || "",
565
+ authorisedActors: cap.actor?.authorisedActors ? JSON.stringify(cap.actor.authorisedActors) : "",
566
+ // TTL props
567
+ ttlAbsoluteDueDate: cap.ttl?.absoluteDueDate || "",
568
+ ttlFromEnablement: cap.ttl?.fromEnablement || "",
569
+ ttlFromCommitment: cap.ttl?.fromCommitment || "",
570
+ // Trigger props (slice D — events and triggers feature). Stored as a
571
+ // JSON string mirroring how `inputs` serializes `nb`. Default empty
572
+ // string means "manual" — the runtime treats absent or empty as manual.
573
+ trigger: cap.trigger ? JSON.stringify(cap.trigger) : ""
574
+ };
575
+ }
576
+ var COMPILED_BLOCK_TYPE = "action";
577
+
578
+ // src/core/lib/flowCompiler/compiler.ts
579
+ function stripActiveScheduleBindings(plan) {
580
+ let changed = false;
581
+ const capabilities = plan.capabilities.map((cap) => {
582
+ if (cap.trigger?.type !== "schedule") return cap;
583
+ if (cap.trigger.scheduleRef === void 0 && cap.trigger.scheduleRevision === void 0) return cap;
584
+ changed = true;
585
+ const { scheduleRef: _ref, scheduleRevision: _rev, ...inactive } = cap.trigger;
586
+ return { ...cap, trigger: inactive };
587
+ });
588
+ return changed ? { ...plan, capabilities } : plan;
589
+ }
590
+ function compileBaseUcanFlow(plan, registry) {
591
+ if (!Array.isArray(plan.capabilities)) {
592
+ throw new Error("BaseUcanFlow.capabilities must be an array");
593
+ }
594
+ const capabilities = plan.capabilities;
595
+ if (capabilities.length === 0) {
596
+ throw new Error("BaseUcanFlow has no capabilities to compile");
597
+ }
598
+ const actionMap = /* @__PURE__ */ new Map();
599
+ for (const cap of capabilities) {
600
+ const nodeId = cap.id?.trim();
601
+ if (!nodeId) {
602
+ throw new Error("Every capability in BaseUcanFlow.capabilities must include a non-empty id.");
603
+ }
604
+ if (actionMap.has(nodeId)) {
605
+ throw new Error(`Duplicate capability id "${nodeId}" in BaseUcanFlow.capabilities.`);
606
+ }
607
+ const action = registry.getActionByCan(cap.can);
608
+ if (!action) {
609
+ throw new Error(`Unknown capability "${cap.can}" for node "${nodeId}". Not found in action registry.`);
610
+ }
611
+ actionMap.set(nodeId, { action, nodeId, cap });
612
+ }
613
+ const blockIndex = {};
614
+ for (const nodeId of actionMap.keys()) {
615
+ blockIndex[nodeId] = generateBlockId(nodeId);
616
+ }
617
+ const triggerEdges = [];
618
+ for (const [nodeId, { cap, action }] of actionMap) {
619
+ const trigger = cap.trigger;
620
+ if (!trigger) continue;
621
+ if (trigger.type === "block.event") {
622
+ if (action.eligibleForEventTrigger !== true) {
623
+ throw new Error(
624
+ `Block "${nodeId}" is configured with a block.event trigger, but its action type "${action.type}" is not marked eligibleForEventTrigger. Set eligibleForEventTrigger: true on the action definition or change the trigger to manual.`
625
+ );
626
+ }
627
+ const sourceId = trigger.sourceBlockId?.trim();
628
+ const eventName = trigger.eventName?.trim();
629
+ if (!sourceId || !eventName) {
630
+ throw new Error(`Block "${nodeId}" has a block.event trigger but is missing sourceBlockId or eventName.`);
631
+ }
632
+ const source = actionMap.get(sourceId);
633
+ if (!source) {
634
+ throw new Error(`Trigger on block "${nodeId}" references unknown source block "${sourceId}".`);
635
+ }
636
+ const declaredEvents = getEventsForBlock(source.action, source.cap.nb);
637
+ if (declaredEvents.length === 0) {
638
+ throw new Error(`Trigger on block "${nodeId}" references event "${eventName}" but source action "${source.action.type}" declares no events.`);
639
+ }
640
+ const found = declaredEvents.find((e) => e.name === eventName);
641
+ if (!found) {
642
+ const declared = declaredEvents.map((e) => e.name).join(", ");
643
+ throw new Error(`Trigger on block "${nodeId}" references unknown event "${eventName}" on action type "${source.action.type}". Declared events: [${declared}]`);
644
+ }
645
+ triggerEdges.push({
646
+ id: `${sourceId}~event:${eventName}~>${nodeId}`,
647
+ source: sourceId,
648
+ target: nodeId,
649
+ kind: "trigger"
650
+ });
651
+ }
652
+ if (trigger.type === "block.event.all") {
653
+ if (action.eligibleForEventTrigger !== true) {
654
+ throw new Error(`Block "${nodeId}" is configured with a block.event.all trigger, but its action type "${action.type}" is not marked eligibleForEventTrigger.`);
655
+ }
656
+ const sources = trigger.sources || [];
657
+ if (sources.length === 0) {
658
+ throw new Error(`Block "${nodeId}" has a block.event.all trigger but no sources configured.`);
659
+ }
660
+ for (const src of sources) {
661
+ const srcId = src.sourceBlockId?.trim();
662
+ const evtName = src.eventName?.trim();
663
+ if (!srcId || !evtName) {
664
+ throw new Error(`Block "${nodeId}" has a block.event.all source with missing sourceBlockId or eventName.`);
665
+ }
666
+ const sourceEntry = actionMap.get(srcId);
667
+ if (!sourceEntry) {
668
+ throw new Error(`Barrier trigger on block "${nodeId}" references unknown source block "${srcId}".`);
669
+ }
670
+ const declaredEvents = getEventsForBlock(sourceEntry.action, sourceEntry.cap.nb);
671
+ const found = declaredEvents.find((e) => e.name === evtName);
672
+ if (!found) {
673
+ const declared = declaredEvents.map((e) => e.name).join(", ");
674
+ throw new Error(`Barrier trigger on block "${nodeId}" references unknown event "${evtName}" on action type "${sourceEntry.action.type}". Declared events: [${declared}]`);
675
+ }
676
+ if (!src.alias?.trim()) {
677
+ throw new Error(`Barrier trigger on block "${nodeId}" has a source (${srcId}/${evtName}) with no alias.`);
678
+ }
679
+ triggerEdges.push({
680
+ id: `${srcId}~event:${evtName}~>${nodeId}`,
681
+ source: srcId,
682
+ target: nodeId,
683
+ kind: "trigger"
684
+ });
685
+ }
686
+ }
687
+ if (trigger.type === "schedule") {
688
+ if (action.eligibleForTimeTrigger !== true) {
689
+ throw new Error(
690
+ `Block "${nodeId}" is configured with a schedule trigger, but its action type "${action.type}" is not marked eligibleForTimeTrigger. Set eligibleForTimeTrigger: true on the action definition or change the trigger.`
691
+ );
692
+ }
693
+ if (trigger.sourceBlockId || trigger.sources || trigger.eventName) {
694
+ throw new Error(
695
+ `Block "${nodeId}" has a schedule trigger carrying event-trigger fields (sourceBlockId/eventName/sources). A schedule trigger holds only scheduleRef and scheduleRevision \u2014 timing lives in the referenced ScheduleSpec, never in the block.`
696
+ );
697
+ }
698
+ if (trigger.scheduleRevision !== void 0 && (!Number.isInteger(trigger.scheduleRevision) || trigger.scheduleRevision < 1)) {
699
+ throw new Error(`Block "${nodeId}" has a schedule trigger with an invalid scheduleRevision (must be an integer >= 1).`);
700
+ }
701
+ }
702
+ if (trigger.type === "block.event" || trigger.type === "block.event.all") {
703
+ const refs = collectOutputRefs(cap.nb || {});
704
+ for (const ref of refs) {
705
+ const parsed = parseOutputRef(ref);
706
+ if (!parsed) continue;
707
+ if (!actionMap.has(parsed.nodeId)) {
708
+ throw new Error(`Listener "${nodeId}" references output of unknown block "${parsed.nodeId}" via ref "${ref}".`);
709
+ }
710
+ }
711
+ }
712
+ }
713
+ const edges = [...triggerEdges];
714
+ detectTriggerCycles(triggerEdges);
715
+ const order = Array.from(actionMap.keys());
716
+ const blocks = [];
717
+ const nodes = {};
718
+ for (const nodeId of order) {
719
+ const { action, cap } = actionMap.get(nodeId);
720
+ const blockId = blockIndex[nodeId];
721
+ const props = compileBlockProps(cap, action.type);
722
+ if (cap.condition) {
723
+ props.conditions = compileCondition(cap.condition, blockIndex);
724
+ }
725
+ if (cap.trigger) {
726
+ props.trigger = compileTrigger(cap.trigger, blockIndex);
727
+ }
728
+ props.triggerMode = cap.trigger?.type || "manual";
729
+ blocks.push({
730
+ id: blockId,
731
+ type: COMPILED_BLOCK_TYPE,
732
+ props
733
+ });
734
+ nodes[nodeId] = {
735
+ id: nodeId,
736
+ blockId,
737
+ can: cap.can,
738
+ with: cap.with,
739
+ registryType: action.type,
740
+ title: cap.title || cap.can,
741
+ description: cap.description || "",
742
+ props,
743
+ phase: cap.phase,
744
+ parallelGroup: cap.parallelGroup,
745
+ actor: cap.actor
746
+ };
747
+ }
748
+ return {
749
+ meta: {
750
+ flowId: plan.flowId,
751
+ title: plan.title,
752
+ goal: plan.goal,
753
+ version: plan.version,
754
+ flowOwnerDid: plan.meta?.rootIssuer || "",
755
+ flowUri: plan.meta?.flowUri,
756
+ compiledAt: (/* @__PURE__ */ new Date()).toISOString(),
757
+ compiledFrom: "BaseUcanFlow"
758
+ },
759
+ blocks,
760
+ nodes,
761
+ edges,
762
+ order,
763
+ blockIndex
764
+ };
765
+ }
766
+ function generateBlockId(nodeId) {
767
+ return `flow_block_${nodeId}`;
768
+ }
769
+ function compileCondition(condition, blockIndex) {
770
+ const sourceBlockId = blockIndex[condition.sourceId];
771
+ if (!sourceBlockId) {
772
+ throw new Error(`Condition references unknown source "${condition.sourceId}".`);
773
+ }
774
+ const conditionConfig = {
775
+ enabled: true,
776
+ mode: "all_must_pass",
777
+ conditions: [
778
+ {
779
+ id: `cond_${condition.sourceId}_${condition.field}`,
780
+ name: `Condition from ${condition.sourceId}`,
781
+ sourceBlockId,
782
+ sourceBlockType: COMPILED_BLOCK_TYPE,
783
+ rule: {
784
+ type: "property_value",
785
+ property: condition.field,
786
+ // Map the BaseUcan ConditionRef operator (eq/neq/…) onto the FE evaluator's
787
+ // vocabulary (equals/not_equals/…). Writing it verbatim is the historical bug
788
+ // that made compiler-authored conditions silently never evaluate.
789
+ operator: toEvaluatorOperator(condition.operator),
790
+ value: condition.value
791
+ },
792
+ effect: condition.effect || { action: "enable" }
793
+ }
794
+ ]
795
+ };
796
+ return JSON.stringify(conditionConfig);
797
+ }
798
+ function compileTrigger(trigger, blockIndex) {
799
+ if (trigger.type === "block.event" && trigger.sourceBlockId) {
800
+ return JSON.stringify({ ...trigger, sourceBlockId: blockIndex[trigger.sourceBlockId.trim()] });
801
+ }
802
+ if (trigger.type === "block.event.all" && trigger.sources) {
803
+ return JSON.stringify({
804
+ ...trigger,
805
+ sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: blockIndex[src.sourceBlockId.trim()] }))
806
+ });
807
+ }
808
+ return JSON.stringify(trigger);
809
+ }
810
+ function collectOutputRefs(value) {
811
+ const refs = [];
812
+ walk(value);
813
+ return refs;
814
+ function walk(v) {
815
+ if (isRuntimeRef(v)) {
816
+ const r = v.$ref;
817
+ if (!r.startsWith("trigger.")) refs.push(r);
818
+ return;
819
+ }
820
+ if (Array.isArray(v)) {
821
+ for (const item of v) walk(item);
822
+ return;
823
+ }
824
+ if (v !== null && typeof v === "object") {
825
+ for (const inner of Object.values(v)) walk(inner);
826
+ }
827
+ }
828
+ }
829
+ function parseOutputRef(ref) {
830
+ const outputIndex = ref.indexOf(".output.");
831
+ if (outputIndex === -1) return null;
832
+ return {
833
+ nodeId: ref.slice(0, outputIndex),
834
+ fieldPath: ref.slice(outputIndex + ".output.".length)
835
+ };
836
+ }
837
+ function detectTriggerCycles(triggerEdges) {
838
+ if (triggerEdges.length === 0) return;
839
+ const adjacency = /* @__PURE__ */ new Map();
840
+ const allNodes = /* @__PURE__ */ new Set();
841
+ for (const edge of triggerEdges) {
842
+ if (!adjacency.has(edge.source)) adjacency.set(edge.source, []);
843
+ adjacency.get(edge.source).push(edge.target);
844
+ allNodes.add(edge.source);
845
+ allNodes.add(edge.target);
846
+ }
847
+ const WHITE = 0;
848
+ const GRAY = 1;
849
+ const BLACK = 2;
850
+ const color = /* @__PURE__ */ new Map();
851
+ for (const id of allNodes) color.set(id, WHITE);
852
+ const path = [];
853
+ const visit = (node) => {
854
+ color.set(node, GRAY);
855
+ path.push(node);
856
+ for (const next of adjacency.get(node) || []) {
857
+ if (color.get(next) === GRAY) {
858
+ const start = path.indexOf(next);
859
+ const cycle = path.slice(start).concat(next).join(" \u2192 ");
860
+ throw new Error(`Trigger cycle detected: ${cycle}. Block.event triggers must form a DAG; remove one of the trigger declarations to break the cycle.`);
861
+ }
862
+ if (color.get(next) === WHITE) {
863
+ visit(next);
864
+ }
865
+ }
866
+ path.pop();
867
+ color.set(node, BLACK);
868
+ };
869
+ for (const id of allNodes) {
870
+ if (color.get(id) === WHITE) visit(id);
871
+ }
872
+ }
873
+
874
+ // src/core/lib/flowCompiler/hydrate.ts
875
+ import * as Y2 from "yjs";
876
+ var DRAFT_CONTROL_MAP = "qi.flow.draftControl";
877
+ var LEGACY_COMMAND_REVISION_KEY = "legacyCommandRevision";
878
+ function nextDraftRevision(yDoc, current) {
879
+ const currentRevision = Number(current ?? 0);
880
+ const legacyRevision = Number(yDoc.getMap(DRAFT_CONTROL_MAP).get(LEGACY_COMMAND_REVISION_KEY) ?? 0);
881
+ return Math.max(0, Number.isFinite(currentRevision) ? currentRevision : 0, Number.isFinite(legacyRevision) ? legacyRevision : 0) + 1;
882
+ }
883
+ function jsonOutputSchema(fields) {
884
+ if (fields.length === 0) return { type: "object", additionalProperties: true };
885
+ const properties = {};
886
+ for (const field of fields) {
887
+ const [root] = field.path.split(".");
888
+ if (!root) continue;
889
+ properties[root] = field.path.includes(".") ? { type: "object" } : { type: field.type };
890
+ }
891
+ return { type: "object", properties, additionalProperties: true };
892
+ }
893
+ var ACTION_SAFETY_BY_TYPE = {
894
+ "qi/noop": "pure",
895
+ "qi/data.constant": "pure",
896
+ // Reads a public endpoint and returns the body. No effect to fence.
897
+ "qi/http.fetch": "pure",
898
+ // Calls out and may change the far side, so it is not pure — but the runner
899
+ // makes the call itself, so it is a provider action, not a fenced one. That
900
+ // keeps the `flow/block/execute` grant every flow already holds sufficient.
901
+ "qi/http.request": "provider_idempotent"
902
+ };
903
+ function resolveActionSafety(type, executionOwner) {
904
+ if (executionOwner === "human") return "approval_only";
905
+ return ACTION_SAFETY_BY_TYPE[type] ?? "fenced";
906
+ }
907
+ function executionContract(node) {
908
+ const action = getAction(node.registryType);
909
+ const manifest = generateActionManifest();
910
+ const entry = manifest.actions.find((candidate) => candidate.type === node.registryType);
911
+ if (!action || !entry || !entry.can) return void 0;
912
+ const safety = resolveActionSafety(action.type, action.executionOwner);
913
+ const contract = {
914
+ kind: "qi.action.contract",
915
+ schemaVersion: "1.0",
916
+ type: action.type,
917
+ can: entry.can,
918
+ contractVersion: action.contractVersion,
919
+ manifestDigest: manifest.manifestDigest,
920
+ inputSchema: action.inputSchema ?? { type: "object", additionalProperties: true },
921
+ outputSchema: jsonOutputSchema(entry.outputSchema),
922
+ safety,
923
+ handlerVersion: `${action.type}@${action.contractVersion}`,
924
+ dataClassification: action.sensitiveInputPaths?.length || action.sensitiveOutputPaths?.length ? "confidential" : "shared",
925
+ requiredServices: [...action.requiredServices ?? []],
926
+ idempotency: {
927
+ providerKey: false,
928
+ readback: safety === "fenced" ? "required" : "unavailable",
929
+ compensation: "unavailable"
930
+ },
931
+ contractDigest: entry.contractDigest
932
+ };
933
+ return contract;
934
+ }
935
+ function writeExecutionMeta(yDoc) {
936
+ const meta = yDoc.getMap("qi.flow.meta");
937
+ meta.set(
938
+ "definitionDigest",
939
+ sha256Digest({
940
+ nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
941
+ edges: yDoc.getMap("qi.flow.edges").toJSON(),
942
+ order: yDoc.getArray("qi.flow.order").toArray()
943
+ })
944
+ );
945
+ meta.set("executionSchemaVersion", 3);
946
+ }
947
+ function rebaseStepResource(authored, flowPrefix, stepIds) {
948
+ if (authored === flowPrefix || authored.startsWith(`${flowPrefix}:`)) return void 0;
949
+ for (const stepId of stepIds) {
950
+ if (stepId && authored.endsWith(`:${stepId}`)) return `${flowPrefix}:${stepId}`;
951
+ }
952
+ return void 0;
953
+ }
954
+ function ensureFlowExecutionMetadata(yDoc) {
955
+ if (yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") !== 1) return false;
956
+ let changed = false;
957
+ yDoc.transact(() => {
958
+ const docId = yDoc.getMap("root").get("doc_id");
959
+ const flowPrefix = typeof docId === "string" && docId ? `ixo:flow:${docId}` : void 0;
960
+ for (const [nodeId, value] of yDoc.getMap("qi.flow.nodes").entries()) {
961
+ if (!(value instanceof Y2.Map)) continue;
962
+ const registryType = value.get("registryType");
963
+ if (typeof registryType !== "string" || !registryType) continue;
964
+ const authoredResource = value.get("with");
965
+ const rebased = flowPrefix && typeof authoredResource === "string" ? rebaseStepResource(authoredResource, flowPrefix, [String(value.get("id") ?? nodeId), String(value.get("blockId") ?? "")]) : void 0;
966
+ if (rebased) {
967
+ value.set("with", rebased);
968
+ const props = asRecord(value.get("props"));
969
+ if (props && props.with === authoredResource) value.set("props", { ...props, with: rebased });
970
+ changed = true;
971
+ }
972
+ const executionOwner = getAction(registryType)?.executionOwner ?? "agent";
973
+ if (value.get("executionOwner") !== executionOwner) {
974
+ value.set("executionOwner", executionOwner);
975
+ changed = true;
976
+ }
977
+ const contract = executionContract({
978
+ id: String(value.get("id") ?? nodeId),
979
+ blockId: String(value.get("blockId") ?? ""),
980
+ can: String(value.get("can") ?? ""),
981
+ with: String(value.get("with") ?? ""),
982
+ registryType,
983
+ title: String(value.get("title") ?? ""),
984
+ description: String(value.get("description") ?? ""),
985
+ props: value.get("props") ?? {}
986
+ });
987
+ if (contract && JSON.stringify(value.get("actionContract")) !== JSON.stringify(contract)) {
988
+ value.set("actionContract", contract);
989
+ changed = true;
990
+ }
991
+ }
992
+ const meta = yDoc.getMap("qi.flow.meta");
993
+ if (changed || typeof meta.get("definitionDigest") !== "string" || meta.get("executionSchemaVersion") !== 3) {
994
+ meta.set("draftRevision", nextDraftRevision(yDoc, meta.get("draftRevision")));
995
+ writeExecutionMeta(yDoc);
996
+ meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
997
+ changed = true;
998
+ }
999
+ });
1000
+ return changed;
1001
+ }
1002
+ function adoptLegacyFlowDocument(yDoc) {
1003
+ const adopted = adoptDraftShape(yDoc);
1004
+ const stamped = ensureFlowExecutionMetadata(yDoc);
1005
+ return adopted || stamped;
1006
+ }
1007
+ function legacyPropsByBlockId(yDoc) {
1008
+ const byBlockId = /* @__PURE__ */ new Map();
1009
+ collectLegacyBlockProps(yDoc.getXmlFragment("document"), byBlockId);
1010
+ return byBlockId;
1011
+ }
1012
+ function asRecord(value) {
1013
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1014
+ }
1015
+ function collectLegacyBlockProps(parent, out) {
1016
+ for (let index = 0; index < parent.length; index += 1) {
1017
+ const child = parent.get(index);
1018
+ if (!(child instanceof Y2.XmlElement)) continue;
1019
+ if (child.nodeName === "blockContainer") readContainerProps(child, out);
1020
+ collectLegacyBlockProps(child, out);
1021
+ }
1022
+ }
1023
+ function readContainerProps(container, out) {
1024
+ const attrs = asRecord(container.getAttribute("attrs"));
1025
+ const directId = container.getAttribute("id");
1026
+ const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
1027
+ if (!blockId) return;
1028
+ const props = {};
1029
+ const addAll = (source) => {
1030
+ for (const [key, value] of Object.entries(source ?? {})) {
1031
+ if (typeof value === "string" && value !== "") props[key] = value;
1032
+ }
1033
+ };
1034
+ addAll(asRecord(attrs?.props));
1035
+ const content = container.get(0);
1036
+ if (content instanceof Y2.XmlElement && content.nodeName !== "blockGroup") addAll(content.getAttributes());
1037
+ const textColor = container.getAttribute("textColor");
1038
+ if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
1039
+ const backgroundColor = container.getAttribute("backgroundColor");
1040
+ if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
1041
+ if (Object.keys(props).length > 0) out.set(blockId, props);
1042
+ }
1043
+ function adoptDraftShape(yDoc) {
1044
+ const meta = yDoc.getMap("qi.flow.meta");
1045
+ if (meta.get("draftSchemaVersion") === 1) return false;
1046
+ const nodes = yDoc.getMap("qi.flow.nodes");
1047
+ if (nodes.size === 0) return false;
1048
+ const propsByBlockId = legacyPropsByBlockId(yDoc);
1049
+ yDoc.transact(() => {
1050
+ for (const value of nodes.values()) {
1051
+ if (!(value instanceof Y2.Map)) continue;
1052
+ const existing = value.get("props");
1053
+ if (existing && typeof existing === "object" && Object.keys(existing).length > 0) continue;
1054
+ const blockId = value.get("blockId");
1055
+ const props = typeof blockId === "string" ? propsByBlockId.get(blockId) : void 0;
1056
+ if (props && Object.keys(props).length > 0) value.set("props", { ...props });
1057
+ }
1058
+ meta.set("draftSchemaVersion", 1);
1059
+ });
1060
+ return true;
1061
+ }
1062
+ function hydrateYDocFromCompiledFlow(yDoc, compiled) {
1063
+ yDoc.transact(() => {
1064
+ const flowMeta = yDoc.getMap("qi.flow.meta");
1065
+ for (const [key, value] of Object.entries(compiled.meta)) {
1066
+ if (value !== void 0) {
1067
+ flowMeta.set(key, value);
1068
+ }
1069
+ }
1070
+ const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
1071
+ flowMeta.set("draftSchemaVersion", 1);
1072
+ flowMeta.set("draftRevision", draftRevision);
1073
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
1074
+ for (const [nodeId, node] of Object.entries(compiled.nodes)) {
1075
+ flowNodes.set(nodeId, createYMapFromNode(node));
1076
+ }
1077
+ const flowEdges = yDoc.getMap("qi.flow.edges");
1078
+ for (const edge of compiled.edges) {
1079
+ const yEdge = new Y2.Map();
1080
+ yEdge.set("id", edge.id);
1081
+ yEdge.set("source", edge.source);
1082
+ yEdge.set("target", edge.target);
1083
+ yEdge.set("kind", edge.kind);
1084
+ if (edge.condition) yEdge.set("condition", edge.condition);
1085
+ flowEdges.set(edge.id, yEdge);
1086
+ }
1087
+ const flowOrder = yDoc.getArray("qi.flow.order");
1088
+ for (const nodeId of compiled.order) {
1089
+ flowOrder.push([nodeId]);
1090
+ }
1091
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1092
+ for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
1093
+ flowBlockIndex.set(nodeId, blockId);
1094
+ }
1095
+ writeExecutionMeta(yDoc);
1096
+ });
1097
+ }
1098
+ function clearFlowState(yDoc) {
1099
+ yDoc.transact(() => {
1100
+ const flowMeta = yDoc.getMap("qi.flow.meta");
1101
+ flowMeta.forEach((_, key) => flowMeta.delete(key));
1102
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
1103
+ flowNodes.forEach((_, key) => flowNodes.delete(key));
1104
+ const flowEdges = yDoc.getMap("qi.flow.edges");
1105
+ flowEdges.forEach((_, key) => flowEdges.delete(key));
1106
+ const flowOrder = yDoc.getArray("qi.flow.order");
1107
+ if (flowOrder.length > 0) {
1108
+ flowOrder.delete(0, flowOrder.length);
1109
+ }
1110
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1111
+ flowBlockIndex.forEach((_, key) => flowBlockIndex.delete(key));
1112
+ });
1113
+ }
1114
+ function hydrateYDocFromMergeResult(yDoc, mergeResult) {
1115
+ const { merged, added, replaced } = mergeResult;
1116
+ yDoc.transact(() => {
1117
+ const flowMeta = yDoc.getMap("qi.flow.meta");
1118
+ for (const [key, value] of Object.entries(merged.meta)) {
1119
+ if (value !== void 0) {
1120
+ flowMeta.set(key, value);
1121
+ }
1122
+ }
1123
+ const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
1124
+ flowMeta.set("draftSchemaVersion", 1);
1125
+ flowMeta.set("draftRevision", draftRevision);
1126
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
1127
+ for (const nodeId of replaced) {
1128
+ flowNodes.delete(nodeId);
1129
+ flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
1130
+ }
1131
+ for (const nodeId of added) {
1132
+ flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
1133
+ }
1134
+ const flowEdges = yDoc.getMap("qi.flow.edges");
1135
+ flowEdges.forEach((_, key) => flowEdges.delete(key));
1136
+ for (const edge of merged.edges) {
1137
+ const yEdge = new Y2.Map();
1138
+ yEdge.set("id", edge.id);
1139
+ yEdge.set("source", edge.source);
1140
+ yEdge.set("target", edge.target);
1141
+ yEdge.set("kind", edge.kind);
1142
+ if (edge.condition) yEdge.set("condition", edge.condition);
1143
+ flowEdges.set(edge.id, yEdge);
1144
+ }
1145
+ const flowOrder = yDoc.getArray("qi.flow.order");
1146
+ if (flowOrder.length > 0) {
1147
+ flowOrder.delete(0, flowOrder.length);
1148
+ }
1149
+ for (const nodeId of merged.order) {
1150
+ flowOrder.push([nodeId]);
1151
+ }
1152
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1153
+ for (const nodeId of [...added, ...replaced]) {
1154
+ flowBlockIndex.set(nodeId, merged.blockIndex[nodeId]);
1155
+ }
1156
+ writeExecutionMeta(yDoc);
1157
+ });
1158
+ }
1159
+ function initializeRuntime(yDoc, compiled, runId) {
1160
+ const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
1161
+ if (!resolvedRunId) return;
1162
+ yDoc.transact(() => {
1163
+ for (const nodeId of compiled.order) {
1164
+ const blockId = compiled.blockIndex[nodeId];
1165
+ if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
1166
+ }
1167
+ });
1168
+ }
1169
+ function initializeRuntimeForNodes(yDoc, compiled, nodeIds, runId) {
1170
+ const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
1171
+ if (!resolvedRunId) return;
1172
+ yDoc.transact(() => {
1173
+ for (const nodeId of nodeIds) {
1174
+ const blockId = compiled.blockIndex[nodeId];
1175
+ if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
1176
+ }
1177
+ });
1178
+ }
1179
+ function createYMapFromNode(node) {
1180
+ const yNode = new Y2.Map();
1181
+ yNode.set("id", node.id);
1182
+ yNode.set("blockId", node.blockId);
1183
+ yNode.set("can", node.can);
1184
+ yNode.set("with", node.with);
1185
+ yNode.set("registryType", node.registryType);
1186
+ yNode.set("executionOwner", getAction(node.registryType)?.executionOwner ?? "agent");
1187
+ yNode.set("title", node.title);
1188
+ yNode.set("description", node.description);
1189
+ yNode.set("props", { ...node.props });
1190
+ const contract = executionContract(node);
1191
+ if (contract) yNode.set("actionContract", contract);
1192
+ if (node.phase) yNode.set("phase", node.phase);
1193
+ if (node.parallelGroup) yNode.set("parallelGroup", node.parallelGroup);
1194
+ if (node.actor) yNode.set("actor", node.actor);
1195
+ return yNode;
1196
+ }
1197
+
1198
+ // src/core/lib/flowCompiler/documentFragment.ts
1199
+ import * as Y3 from "yjs";
1200
+ function writeCompiledBlocksToFragment(fragment, blocks) {
1201
+ const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
1202
+ for (const block of blocks) {
1203
+ appendBlockToGroup(documentBlockGroup, block);
1204
+ }
1205
+ }
1206
+ function insertCompiledBlockIntoFragment(fragment, block, beforeBlockId) {
1207
+ const blockGroup = getOrCreateDocumentBlockGroup(fragment);
1208
+ if (beforeBlockId) {
1209
+ for (let index = 0; index < blockGroup.length; index += 1) {
1210
+ const candidate = blockGroup.get(index);
1211
+ if (isYXmlElementLike(candidate) && candidate.getAttribute("id") === beforeBlockId) {
1212
+ blockGroup.insert(index, [createBlockContainer(block)]);
1213
+ return;
1214
+ }
1215
+ }
1216
+ }
1217
+ appendBlockToGroup(blockGroup, block);
1218
+ }
1219
+ function removeAllFlowBlocks(fragment) {
1220
+ const blockGroup = getExistingBlockGroup(fragment);
1221
+ if (!blockGroup) return;
1222
+ while (blockGroup.length > 0) {
1223
+ blockGroup.delete(0, 1);
1224
+ }
1225
+ }
1226
+ function removeBlockFromFragment(fragment, blockId) {
1227
+ const blockGroup = getExistingBlockGroup(fragment);
1228
+ if (!blockGroup) return false;
1229
+ for (let i = 0; i < blockGroup.length; i++) {
1230
+ const container = blockGroup.get(i);
1231
+ if (isYXmlElementLike(container) && container.getAttribute("id") === blockId) {
1232
+ blockGroup.delete(i, 1);
1233
+ return true;
1234
+ }
1235
+ }
1236
+ return false;
1237
+ }
1238
+ function replaceBlockInFragment(fragment, block) {
1239
+ const blockGroup = getExistingBlockGroup(fragment);
1240
+ if (!blockGroup) return false;
1241
+ for (let i = 0; i < blockGroup.length; i++) {
1242
+ const container = blockGroup.get(i);
1243
+ if (isYXmlElementLike(container) && container.getAttribute("id") === block.id) {
1244
+ blockGroup.delete(i, 1);
1245
+ const newContainer = createBlockContainer(block);
1246
+ blockGroup.insert(i, [newContainer]);
1247
+ return true;
1248
+ }
1249
+ }
1250
+ return false;
1251
+ }
1252
+ function swapBlocksInFragment(fragment, idA, idB) {
1253
+ const blockGroup = getExistingBlockGroup(fragment);
1254
+ if (!blockGroup) return false;
1255
+ let ia = -1;
1256
+ let ib = -1;
1257
+ for (let i = 0; i < blockGroup.length; i++) {
1258
+ const container = blockGroup.get(i);
1259
+ if (isYXmlElementLike(container)) {
1260
+ const id = container.getAttribute("id");
1261
+ if (id === idA) ia = i;
1262
+ else if (id === idB) ib = i;
1263
+ }
1264
+ }
1265
+ if (ia < 0 || ib < 0 || ia === ib) return false;
1266
+ const lo = Math.min(ia, ib);
1267
+ const hi = Math.max(ia, ib);
1268
+ const loClone = blockGroup.get(lo).clone();
1269
+ const hiClone = blockGroup.get(hi).clone();
1270
+ blockGroup.delete(hi, 1);
1271
+ blockGroup.insert(hi, [loClone]);
1272
+ blockGroup.delete(lo, 1);
1273
+ blockGroup.insert(lo, [hiClone]);
1274
+ return true;
1275
+ }
1276
+ function applyMergeResultToFragment(fragment, mergeResult) {
1277
+ const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
1278
+ const blockByNodeId = /* @__PURE__ */ new Map();
1279
+ for (const block of mergeResult.merged.blocks) {
1280
+ for (const [nodeId, blockId] of Object.entries(mergeResult.merged.blockIndex)) {
1281
+ if (blockId === block.id) {
1282
+ blockByNodeId.set(nodeId, block);
1283
+ break;
1284
+ }
1285
+ }
1286
+ }
1287
+ for (const nodeId of mergeResult.replaced) {
1288
+ const block = blockByNodeId.get(nodeId);
1289
+ if (block) {
1290
+ replaceBlockInFragment(fragment, block);
1291
+ }
1292
+ }
1293
+ for (const nodeId of mergeResult.added) {
1294
+ const block = blockByNodeId.get(nodeId);
1295
+ if (block) {
1296
+ appendBlockToGroup(documentBlockGroup, block);
1297
+ }
1298
+ }
1299
+ }
1300
+ function readBlocksFromFragment(fragment) {
1301
+ const blockGroup = getExistingBlockGroup(fragment);
1302
+ if (!blockGroup) return [];
1303
+ const blocks = [];
1304
+ for (let i = 0; i < blockGroup.length; i++) {
1305
+ const container = blockGroup.get(i);
1306
+ if (!isYXmlElementLike(container) || container.nodeName !== "blockContainer") continue;
1307
+ const id = container.getAttribute("id");
1308
+ if (typeof id !== "string" || id.length === 0) continue;
1309
+ const content = container.get(0);
1310
+ if (!isYXmlElementLike(content)) continue;
1311
+ const props = { ...content.getAttributes() };
1312
+ const textColor = container.getAttribute("textColor");
1313
+ if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
1314
+ const backgroundColor = container.getAttribute("backgroundColor");
1315
+ if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
1316
+ blocks.push({ id, type: content.nodeName, props });
1317
+ }
1318
+ return blocks;
1319
+ }
1320
+ function createBlockContainer(block) {
1321
+ const blockContainer = new Y3.XmlElement("blockContainer");
1322
+ const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;
1323
+ blockContainer.setAttribute("id", block.id);
1324
+ blockContainer.setAttribute("textColor", rawTextColor || "default");
1325
+ blockContainer.setAttribute("backgroundColor", rawBackgroundColor || "default");
1326
+ const blockContent = new Y3.XmlElement(block.type);
1327
+ for (const [key, value] of Object.entries(contentProps)) {
1328
+ if (value !== "") {
1329
+ blockContent.setAttribute(key, value);
1330
+ }
1331
+ }
1332
+ blockContainer.insert(0, [blockContent]);
1333
+ return blockContainer;
1334
+ }
1335
+ function appendBlockToGroup(blockGroup, block) {
1336
+ const container = createBlockContainer(block);
1337
+ blockGroup.insert(blockGroup.length, [container]);
1338
+ }
1339
+ function getOrCreateDocumentBlockGroup(fragment) {
1340
+ if (fragment.length === 0) {
1341
+ const blockGroup = new Y3.XmlElement("blockGroup");
1342
+ fragment.insert(0, [blockGroup]);
1343
+ return blockGroup;
1344
+ }
1345
+ if (fragment.length === 1) {
1346
+ const rootNode = fragment.get(0);
1347
+ if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
1348
+ return rootNode;
1349
+ }
1350
+ }
1351
+ throw new Error("Unexpected BlockNote document shape in XmlFragment. Expected a single top-level blockGroup node.");
1352
+ }
1353
+ function getExistingBlockGroup(fragment) {
1354
+ if (fragment.length === 0) return null;
1355
+ if (fragment.length === 1) {
1356
+ const rootNode = fragment.get(0);
1357
+ if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
1358
+ return rootNode;
1359
+ }
1360
+ }
1361
+ return null;
1362
+ }
1363
+
1364
+ // src/core/lib/flowCompiler/readFlow.ts
1365
+ function readCompiledFlowFromYDoc(yDoc) {
1366
+ const flowMeta = yDoc.getMap("qi.flow.meta");
1367
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
1368
+ const nodes = {};
1369
+ flowNodes.forEach((value, nodeId) => {
1370
+ if (isYMapLike(value)) {
1371
+ nodes[nodeId] = yMapToFlowNode(value);
1372
+ }
1373
+ });
1374
+ if (flowNodes.size === 0 && flowMeta.size === 0) {
1375
+ return null;
1376
+ }
1377
+ const meta = {
1378
+ flowId: flowMeta.get("flowId") || "",
1379
+ title: flowMeta.get("title") || "",
1380
+ goal: flowMeta.get("goal"),
1381
+ version: flowMeta.get("version") || "",
1382
+ flowOwnerDid: flowMeta.get("flowOwnerDid") || "",
1383
+ flowUri: flowMeta.get("flowUri"),
1384
+ compiledAt: flowMeta.get("compiledAt") || "",
1385
+ compiledFrom: "BaseUcanFlow"
1386
+ };
1387
+ const flowEdges = yDoc.getMap("qi.flow.edges");
1388
+ const edges = [];
1389
+ flowEdges.forEach((value) => {
1390
+ if (isYMapLike(value)) {
1391
+ edges.push(yMapToEdge(value));
1392
+ }
1393
+ });
1394
+ const flowOrder = yDoc.getArray("qi.flow.order");
1395
+ const order = flowOrder.toArray();
1396
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1397
+ const blockIndex = {};
1398
+ flowBlockIndex.forEach((value, key) => {
1399
+ blockIndex[key] = value;
1400
+ });
1401
+ const blocks = order.filter((nodeId) => nodes[nodeId]).map((nodeId) => {
1402
+ const node = nodes[nodeId];
1403
+ return {
1404
+ id: node.blockId,
1405
+ type: COMPILED_BLOCK_TYPE,
1406
+ props: { ...node.props }
1407
+ };
1408
+ });
1409
+ return { meta, blocks, nodes, edges, order, blockIndex };
1410
+ }
1411
+ function yMapToFlowNode(yMap) {
1412
+ return {
1413
+ id: yMap.get("id") || "",
1414
+ blockId: yMap.get("blockId") || "",
1415
+ can: yMap.get("can") || "",
1416
+ with: yMap.get("with") || "",
1417
+ registryType: yMap.get("registryType") || "",
1418
+ title: yMap.get("title") || "",
1419
+ description: yMap.get("description") || "",
1420
+ props: yMap.get("props") || {},
1421
+ phase: yMap.get("phase"),
1422
+ parallelGroup: yMap.get("parallelGroup"),
1423
+ actor: yMap.get("actor")
1424
+ };
1425
+ }
1426
+ function yMapToEdge(yMap) {
1427
+ return {
1428
+ id: yMap.get("id") || "",
1429
+ source: yMap.get("source") || "",
1430
+ target: yMap.get("target") || "",
1431
+ // Only 'trigger' edges exist. Legacy 'dependency' edges from older
1432
+ // Y.Docs (before dependsOn was removed) get coerced — they'll be
1433
+ // overwritten on the next compile pass.
1434
+ kind: "trigger",
1435
+ condition: yMap.get("condition")
1436
+ };
1437
+ }
1438
+
1439
+ // src/core/lib/flowCompiler/mergeFlows.ts
1440
+ function mergeCompiledFlows(existing, incoming, strategy) {
1441
+ const added = [];
1442
+ const replaced = [];
1443
+ const kept = [];
1444
+ const mergedNodes = {};
1445
+ const mergedBlockIndex = {};
1446
+ for (const [nodeId, node] of Object.entries(existing.nodes)) {
1447
+ mergedNodes[nodeId] = node;
1448
+ mergedBlockIndex[nodeId] = existing.blockIndex[nodeId];
1449
+ }
1450
+ for (const [nodeId, node] of Object.entries(incoming.nodes)) {
1451
+ if (mergedNodes[nodeId]) {
1452
+ if (strategy === "patch") {
1453
+ mergedNodes[nodeId] = node;
1454
+ mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1455
+ replaced.push(nodeId);
1456
+ } else {
1457
+ kept.push(nodeId);
1458
+ }
1459
+ } else {
1460
+ mergedNodes[nodeId] = node;
1461
+ mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1462
+ added.push(nodeId);
1463
+ }
1464
+ }
1465
+ for (const nodeId of Object.keys(existing.nodes)) {
1466
+ if (!replaced.includes(nodeId)) {
1467
+ kept.push(nodeId);
1468
+ }
1469
+ }
1470
+ const edgeMap = /* @__PURE__ */ new Map();
1471
+ for (const edge of [...existing.edges, ...incoming.edges]) {
1472
+ if (mergedNodes[edge.source] && mergedNodes[edge.target]) {
1473
+ edgeMap.set(edge.id, edge);
1474
+ }
1475
+ }
1476
+ const edges = Array.from(edgeMap.values());
1477
+ const order = Object.keys(mergedNodes);
1478
+ const blocks = order.map((nodeId) => {
1479
+ const node = mergedNodes[nodeId];
1480
+ return {
1481
+ id: node.blockId,
1482
+ type: COMPILED_BLOCK_TYPE,
1483
+ props: { ...node.props }
1484
+ };
1485
+ });
1486
+ const meta = {
1487
+ ...incoming.meta,
1488
+ flowId: existing.meta.flowId,
1489
+ compiledAt: (/* @__PURE__ */ new Date()).toISOString()
1490
+ };
1491
+ return {
1492
+ merged: { meta, blocks, nodes: mergedNodes, edges, order, blockIndex: mergedBlockIndex },
1493
+ added,
1494
+ replaced,
1495
+ kept
1496
+ };
1497
+ }
1498
+
1499
+ // src/core/lib/flowCompiler/decompile.ts
1500
+ function decompileToBaseUcanFlow(compiled) {
1501
+ const nodeIdByBlockId = {};
1502
+ for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
1503
+ nodeIdByBlockId[blockId] = nodeId;
1504
+ }
1505
+ const capabilities = compiled.order.map((nodeId) => {
1506
+ const node = compiled.nodes[nodeId];
1507
+ return nodeToCapability(node, nodeIdByBlockId);
1508
+ });
1509
+ return {
1510
+ kind: "qi.flow.base-ucan",
1511
+ version: "1.0",
1512
+ flowId: compiled.meta.flowId,
1513
+ title: compiled.meta.title,
1514
+ goal: compiled.meta.goal,
1515
+ meta: {
1516
+ rootIssuer: compiled.meta.flowOwnerDid || void 0,
1517
+ flowUri: compiled.meta.flowUri
1518
+ },
1519
+ capabilities
1520
+ };
1521
+ }
1522
+ function nodeToCapability(node, nodeIdByBlockId) {
1523
+ const cap = {
1524
+ id: node.id,
1525
+ can: node.can,
1526
+ with: node.with
1527
+ };
1528
+ if (node.props.inputs) {
1529
+ try {
1530
+ const nb = JSON.parse(node.props.inputs);
1531
+ if (nb && typeof nb === "object" && Object.keys(nb).length > 0) {
1532
+ cap.nb = nb;
1533
+ }
1534
+ } catch {
1535
+ }
1536
+ }
1537
+ if (node.parallelGroup) {
1538
+ cap.parallelGroup = node.parallelGroup;
1539
+ }
1540
+ if (node.phase) {
1541
+ cap.phase = node.phase;
1542
+ }
1543
+ if (node.actor) {
1544
+ cap.actor = { ...node.actor };
1545
+ }
1546
+ const ttl = {};
1547
+ if (node.props.ttlAbsoluteDueDate) ttl.absoluteDueDate = node.props.ttlAbsoluteDueDate;
1548
+ if (node.props.ttlFromEnablement) ttl.fromEnablement = node.props.ttlFromEnablement;
1549
+ if (node.props.ttlFromCommitment) ttl.fromCommitment = node.props.ttlFromCommitment;
1550
+ if (Object.keys(ttl).length > 0) {
1551
+ cap.ttl = ttl;
1552
+ }
1553
+ if (typeof node.props.trigger === "string" && node.props.trigger.length > 0) {
1554
+ try {
1555
+ const trigger = JSON.parse(node.props.trigger);
1556
+ if (trigger && typeof trigger === "object" && typeof trigger.type === "string") {
1557
+ cap.trigger = triggerToNodeIds(trigger, nodeIdByBlockId);
1558
+ }
1559
+ } catch {
1560
+ }
1561
+ }
1562
+ if (node.title && node.title !== node.can) {
1563
+ cap.title = node.title;
1564
+ }
1565
+ if (node.description) {
1566
+ cap.description = node.description;
1567
+ }
1568
+ if (node.props.icon) {
1569
+ cap.icon = node.props.icon;
1570
+ }
1571
+ return cap;
1572
+ }
1573
+ function triggerToNodeIds(trigger, nodeIdByBlockId) {
1574
+ if (trigger.type === "block.event" && trigger.sourceBlockId) {
1575
+ return { ...trigger, sourceBlockId: nodeIdByBlockId[trigger.sourceBlockId] ?? trigger.sourceBlockId };
1576
+ }
1577
+ if (trigger.type === "block.event.all" && trigger.sources) {
1578
+ return {
1579
+ ...trigger,
1580
+ sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: nodeIdByBlockId[src.sourceBlockId] ?? src.sourceBlockId }))
1581
+ };
1582
+ }
1583
+ return trigger;
1584
+ }
1585
+
1586
+ // src/core/lib/flowCompiler/setup.ts
1587
+ import * as Y4 from "yjs";
1588
+ import { MatrixProvider as MatrixProvider2 } from "@ixo/matrix-crdt";
1589
+ async function readFlowAsBaseUcan(options) {
1590
+ const { roomId, matrixClient } = options;
1591
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: false });
1592
+ try {
1593
+ const compiled = readCompiledFlowFromYDoc(yDoc);
1594
+ if (!compiled) return null;
1595
+ const plan = decompileToBaseUcanFlow(compiled);
1596
+ return { plan, compiled, roomId };
1597
+ } finally {
1598
+ provider.dispose();
1599
+ yDoc.destroy();
1600
+ }
1601
+ }
1602
+ function readFlowFromEditor(editor) {
1603
+ const yDoc = editor._yDoc;
1604
+ if (!yDoc) return null;
1605
+ const compiled = readCompiledFlowFromYDoc(yDoc);
1606
+ if (!compiled) return null;
1607
+ const plan = decompileToBaseUcanFlow(compiled);
1608
+ const roomId = editor.getRoomId?.() || "";
1609
+ return { plan, compiled, roomId };
1610
+ }
1611
+ var activeEditor = null;
1612
+ function setActiveEditor(editor) {
1613
+ activeEditor = editor;
1614
+ }
1615
+ function getActiveEditor() {
1616
+ return activeEditor;
1617
+ }
1618
+ function readFlow() {
1619
+ if (!activeEditor) {
1620
+ console.warn("[readFlow] No active editor registered. Did the editor finish mounting?");
1621
+ return null;
1622
+ }
1623
+ return readFlowFromEditor(activeEditor);
1624
+ }
1625
+ async function setupFlowFromBaseUcan(options) {
1626
+ const { plan: rawPlan, roomId, matrixClient, creatorDid, docId, templateId, strategy = "full" } = options;
1627
+ const identified = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: docId || roomId };
1628
+ const plan = templateId ? stripActiveScheduleBindings(identified) : identified;
1629
+ const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
1630
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
1631
+ let finalCompiled;
1632
+ try {
1633
+ finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, docId, templateId, strategy });
1634
+ await provider.waitForFlush();
1635
+ } finally {
1636
+ provider.dispose();
1637
+ yDoc.destroy();
1638
+ }
1639
+ return {
1640
+ compiled: finalCompiled,
1641
+ roomId,
1642
+ flowId: plan.flowId
1643
+ };
1644
+ }
1645
+ async function seedDesignPodTemplateFlow(options) {
1646
+ const { methodId, roomId, matrixClient, creatorDid } = options;
1647
+ const rawPlan = createDesignPodPortalJourneyPlan(methodId);
1648
+ const plan = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: roomId };
1649
+ const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
1650
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
1651
+ let finalCompiled;
1652
+ try {
1653
+ finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, strategy: "full" });
1654
+ seedDesignPodMethodDefinition(yDoc, methodId);
1655
+ await provider.waitForFlush();
1656
+ } finally {
1657
+ provider.dispose();
1658
+ yDoc.destroy();
1659
+ }
1660
+ return { compiled: finalCompiled, roomId, flowId: plan.flowId };
1661
+ }
1662
+ function applyFlowPlanToYDoc(yDoc, options) {
1663
+ const { plan, incomingCompiled, creatorDid, docId, templateId, strategy, runId } = options;
1664
+ const root = yDoc.getMap("root");
1665
+ const fragment = yDoc.getXmlFragment("document");
1666
+ const existingFlow = readCompiledFlowFromYDoc(yDoc);
1667
+ if (strategy === "full") {
1668
+ if (existingFlow) {
1669
+ clearFlowState(yDoc);
1670
+ removeAllFlowBlocks(fragment);
1671
+ }
1672
+ setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
1673
+ hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
1674
+ if (!existingFlow) {
1675
+ initializeRuntime(yDoc, incomingCompiled, runId);
1676
+ }
1677
+ yDoc.transact(() => {
1678
+ writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
1679
+ });
1680
+ return incomingCompiled;
1681
+ }
1682
+ if (!existingFlow) {
1683
+ setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
1684
+ hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
1685
+ initializeRuntime(yDoc, incomingCompiled, runId);
1686
+ yDoc.transact(() => {
1687
+ writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
1688
+ });
1689
+ return incomingCompiled;
1690
+ }
1691
+ const mergeResult = mergeCompiledFlows(existingFlow, incomingCompiled, strategy);
1692
+ hydrateYDocFromMergeResult(yDoc, mergeResult);
1693
+ const nodesToInit = [...mergeResult.added, ...mergeResult.replaced];
1694
+ initializeRuntimeForNodes(yDoc, mergeResult.merged, nodesToInit, runId);
1695
+ yDoc.transact(() => {
1696
+ applyMergeResultToFragment(fragment, mergeResult);
1697
+ });
1698
+ return mergeResult.merged;
1699
+ }
1700
+ async function connectToRoom(roomId, matrixClient, options) {
1701
+ const yDoc = new Y4.Doc();
1702
+ const client = matrixClient;
1703
+ client.canSupportVoip = false;
1704
+ client.clientOpts = { lazyLoadMembers: true };
1705
+ const provider = new MatrixProvider2(
1706
+ yDoc,
1707
+ client,
1708
+ { type: "id", id: roomId },
1709
+ {
1710
+ translator: {
1711
+ updateEventType: "matrix-crdt.doc_update",
1712
+ snapshotEventType: "matrix-crdt.doc_snapshot",
1713
+ enableMediaSnapshots: true
1714
+ },
1715
+ enableExperimentalWebrtcSync: false,
1716
+ enableAwareness: false,
1717
+ reader: { snapshotInterval: 10 },
1718
+ writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 }
1719
+ }
1720
+ );
1721
+ await new Promise((resolve, reject) => {
1722
+ const timeout = setTimeout(() => {
1723
+ reject(new Error(`Timed out connecting to room ${roomId}`));
1724
+ }, 3e4);
1725
+ provider.onDocumentAvailable(() => {
1726
+ clearTimeout(timeout);
1727
+ resolve();
1728
+ });
1729
+ provider.onDocumentUnavailable(() => {
1730
+ clearTimeout(timeout);
1731
+ reject(new Error(`Room ${roomId} is unavailable`));
1732
+ });
1733
+ provider.initialize().catch((err) => {
1734
+ clearTimeout(timeout);
1735
+ reject(err);
1736
+ });
1737
+ });
1738
+ if (options.adoptRuns && provider.canWrite) {
1739
+ collectPhantomLegacyRun(yDoc);
1740
+ }
1741
+ return { yDoc, provider };
1742
+ }
1743
+ function setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId) {
1744
+ yDoc.transact(() => {
1745
+ if (!root.get("@context")) root.set("@context", "https://ixo.world/flow/0.3");
1746
+ if (!root.get("_type")) root.set("_type", "ixo.flow.crdt");
1747
+ if (!root.get("schema_version")) root.set("schema_version", "0.3");
1748
+ if (!root.get("doc_id")) root.set("doc_id", docId || plan.flowId);
1749
+ if (!root.get("createdAt")) root.set("createdAt", (/* @__PURE__ */ new Date()).toISOString());
1750
+ if (!root.get("createdBy")) root.set("createdBy", creatorDid);
1751
+ root.set("flowOwnerDid", creatorDid);
1752
+ if (!hasLegacyRuntimeHistory(yDoc)) setMultiRunStorage(yDoc);
1753
+ if (templateId && !root.get("source_template_id")) {
1754
+ root.set("source_template_id", templateId);
1755
+ }
1756
+ const titleText = yDoc.getText("title");
1757
+ if (titleText.length === 0 && plan.title) {
1758
+ titleText.insert(0, plan.title);
1759
+ }
1760
+ });
1761
+ }
1762
+
1763
+ // src/core/lib/flowCompiler/authoring.ts
1764
+ function readFlowDocument(yDoc, runId) {
1765
+ const compiled = readCompiledFlowFromYDoc(yDoc);
1766
+ if (!compiled) return null;
1767
+ const propsByBlockId = /* @__PURE__ */ new Map();
1768
+ for (const block of readBlocksFromFragment(yDoc.getXmlFragment("document"))) {
1769
+ propsByBlockId.set(block.id, block.props);
1770
+ }
1771
+ const resolvedRunId = resolveRunIdForRead(yDoc, runId);
1772
+ const nodePropsAreAuthoritative = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1773
+ const nodes = compiled.order.filter((nodeId) => compiled.nodes[nodeId]).map((nodeId) => {
1774
+ const node = compiled.nodes[nodeId];
1775
+ const projectedProps = propsByBlockId.get(node.blockId) ?? {};
1776
+ const props = nodePropsAreAuthoritative && Object.keys(node.props ?? {}).length > 0 ? { ...node.props } : projectedProps;
1777
+ const runtime = resolvedRunId ? readActionState(yDoc, resolvedRunId, node.blockId) : {};
1778
+ return {
1779
+ nodeId,
1780
+ blockId: node.blockId,
1781
+ can: node.can,
1782
+ with: node.with,
1783
+ title: props.title ?? node.title,
1784
+ description: props.description ?? node.description,
1785
+ props,
1786
+ runtime
1787
+ };
1788
+ });
1789
+ return {
1790
+ meta: compiled.meta,
1791
+ order: compiled.order,
1792
+ edges: compiled.edges,
1793
+ blockIndex: compiled.blockIndex,
1794
+ nodes
1795
+ };
1796
+ }
1797
+ function addFlowNode(yDoc, opts) {
1798
+ const action = getAction(opts.type);
1799
+ if (!action) return null;
1800
+ const nodeId = opts.nodeId ?? `node_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1801
+ const blockId = opts.blockId ?? `flow_block_${nodeId}`;
1802
+ if (yDoc.getMap("qi.flow.nodes").has(nodeId) || [...yDoc.getMap("qi.flow.blockIndex").values()].includes(blockId)) return null;
1803
+ const flowId = yDoc.getMap("qi.flow.meta").get("flowId") || "";
1804
+ const withUri = flowId ? `ixo:flow:${flowId}:${nodeId}` : `ixo:flow:${nodeId}`;
1805
+ const can = action.can ?? "";
1806
+ const title = opts.title || can || action.type;
1807
+ const cap = { id: nodeId, can, with: withUri, title, nb: {} };
1808
+ const props = { ...compileBlockProps(cap, action.type), triggerMode: "manual", ...opts.props ?? {} };
1809
+ const node = {
1810
+ id: nodeId,
1811
+ blockId,
1812
+ can,
1813
+ with: withUri,
1814
+ registryType: action.type,
1815
+ title,
1816
+ description: "",
1817
+ props
1818
+ };
1819
+ yDoc.transact(() => {
1820
+ writeCompiledBlocksToFragment(yDoc.getXmlFragment("document"), [{ id: blockId, type: COMPILED_BLOCK_TYPE, props }]);
1821
+ yDoc.getMap("qi.flow.nodes").set(nodeId, createYMapFromNode(node));
1822
+ yDoc.getMap("qi.flow.blockIndex").set(nodeId, blockId);
1823
+ const order = yDoc.getArray("qi.flow.order");
1824
+ if (opts.afterNodeId) {
1825
+ const idx = order.toArray().indexOf(opts.afterNodeId);
1826
+ if (idx >= 0) order.insert(idx + 1, [nodeId]);
1827
+ else order.push([nodeId]);
1828
+ } else {
1829
+ order.push([nodeId]);
1830
+ }
1831
+ advanceDraftRevision(yDoc);
1832
+ });
1833
+ return { nodeId, blockId };
1834
+ }
1835
+ function setBlockProps(yDoc, blockId, partial) {
1836
+ const fragment = yDoc.getXmlFragment("document");
1837
+ const existing = readBlocksFromFragment(fragment).find((b) => b.id === blockId);
1838
+ if (!existing) return false;
1839
+ const nodeId = findNodeIdForBlock(yDoc, blockId);
1840
+ const node = nodeId ? yDoc.getMap("qi.flow.nodes").get(nodeId) : void 0;
1841
+ const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1842
+ const canonicalProps = isYMapLike(node) ? node.get("props") : void 0;
1843
+ const baseline = isVNextDraft && canonicalProps ? canonicalProps : existing.props;
1844
+ const merged = { ...baseline, ...partial };
1845
+ let ok = false;
1846
+ yDoc.transact(() => {
1847
+ ok = replaceBlockInFragment(fragment, { id: blockId, type: existing.type, props: merged });
1848
+ if (isYMapLike(node)) {
1849
+ node.set("props", { ...merged });
1850
+ if ("title" in partial) node.set("title", merged.title ?? "");
1851
+ if ("description" in partial) node.set("description", merged.description ?? "");
1852
+ if ("authorisedActors" in partial || "parentCapability" in partial) {
1853
+ const actor = actorFromProps(merged);
1854
+ if (actor) node.set("actor", actor);
1855
+ else node.delete("actor");
1856
+ }
1857
+ }
1858
+ advanceDraftRevision(yDoc);
1859
+ });
1860
+ return ok;
1861
+ }
1862
+ function syncFlowNodePropsFromProjection(yDoc, blockId, partial, legacyBaseline = {}) {
1863
+ const nodeId = findNodeIdForBlock(yDoc, blockId);
1864
+ if (!nodeId) return false;
1865
+ const node = yDoc.getMap("qi.flow.nodes").get(nodeId);
1866
+ if (!isYMapLike(node)) return false;
1867
+ const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1868
+ const projectedBaseline = readBlocksFromFragment(yDoc.getXmlFragment("document")).find((block) => block.id === blockId)?.props;
1869
+ const nodeProps = node.get("props");
1870
+ const baseline = isVNextDraft ? nodeProps ?? legacyBaseline : projectedBaseline ?? legacyBaseline;
1871
+ if (!isVNextDraft && !nodeProps && Object.keys(baseline).length === 0) return false;
1872
+ yDoc.transact(() => {
1873
+ const merged = { ...baseline, ...partial };
1874
+ node.set("props", merged);
1875
+ if ("title" in partial) node.set("title", merged.title ?? "");
1876
+ if ("description" in partial) node.set("description", merged.description ?? "");
1877
+ if ("authorisedActors" in partial || "parentCapability" in partial) {
1878
+ const actor = actorFromProps(merged);
1879
+ if (actor) node.set("actor", actor);
1880
+ else node.delete("actor");
1881
+ }
1882
+ if (isVNextDraft) advanceDraftRevision(yDoc);
1883
+ });
1884
+ return true;
1885
+ }
1886
+ function auditFlowProjections(yDoc) {
1887
+ const projected = new Map(readBlocksFromFragment(yDoc.getXmlFragment("document")).map((block) => [block.id, block.props]));
1888
+ const drift = [];
1889
+ yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
1890
+ if (!isYMapLike(value)) return;
1891
+ const blockId = String(value.get("blockId") ?? "");
1892
+ const canonical = value.get("props") ?? {};
1893
+ const projection = projected.get(blockId);
1894
+ if (!projection) drift.push({ nodeId, blockId, kind: "missing_block" });
1895
+ else if (stableProps(canonical) !== stableProps(projection)) drift.push({ nodeId, blockId, kind: "props_mismatch" });
1896
+ });
1897
+ return drift.sort((left, right) => left.nodeId.localeCompare(right.nodeId));
1898
+ }
1899
+ function repairFlowProjections(yDoc) {
1900
+ const before = auditFlowProjections(yDoc);
1901
+ if (before.length === 0) return before;
1902
+ const fragment = yDoc.getXmlFragment("document");
1903
+ const projected = new Map(readBlocksFromFragment(fragment).map((block) => [block.id, block]));
1904
+ const orderedNodeIds = yDoc.getArray("qi.flow.order").toArray();
1905
+ yDoc.transact(() => {
1906
+ for (const item of before) {
1907
+ const node = yDoc.getMap("qi.flow.nodes").get(item.nodeId);
1908
+ if (!isYMapLike(node)) continue;
1909
+ const props = node.get("props") ?? {};
1910
+ const block = projected.get(item.blockId);
1911
+ if (block) {
1912
+ replaceBlockInFragment(fragment, { ...block, props });
1913
+ continue;
1914
+ }
1915
+ const nodeIndex = orderedNodeIds.indexOf(item.nodeId);
1916
+ const nextProjectedBlockId = orderedNodeIds.slice(nodeIndex + 1).find((candidateNodeId) => {
1917
+ const candidate = yDoc.getMap("qi.flow.nodes").get(candidateNodeId);
1918
+ if (!isYMapLike(candidate)) return false;
1919
+ return projected.has(String(candidate.get("blockId") ?? ""));
1920
+ });
1921
+ const nextNode = nextProjectedBlockId ? yDoc.getMap("qi.flow.nodes").get(nextProjectedBlockId) : void 0;
1922
+ const beforeBlockId = isYMapLike(nextNode) ? String(nextNode.get("blockId") ?? "") : void 0;
1923
+ insertCompiledBlockIntoFragment(fragment, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props }, beforeBlockId);
1924
+ projected.set(item.blockId, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props });
1925
+ }
1926
+ yDoc.getMap("qi.flow.projections").set("document", {
1927
+ draftRevision: Number(yDoc.getMap("qi.flow.meta").get("draftRevision") ?? 0),
1928
+ repairedAt: (/* @__PURE__ */ new Date()).toISOString()
1929
+ });
1930
+ });
1931
+ return before;
1932
+ }
1933
+ function removeFlowNode(yDoc, nodeId, runId) {
1934
+ const doc = readFlowDocument(yDoc, resolveRunIdForRead(yDoc, runId));
1935
+ if (!doc) return { ok: false, referencedBy: [] };
1936
+ const target = doc.nodes.find((n) => n.nodeId === nodeId);
1937
+ if (!target) return { ok: false, referencedBy: [] };
1938
+ const referencedBy = doc.nodes.filter((n) => n.nodeId !== nodeId && nodeReferences(n, nodeId, target.blockId)).map((n) => n.nodeId);
1939
+ if (referencedBy.length > 0) return { ok: false, referencedBy };
1940
+ const blockId = target.blockId;
1941
+ yDoc.transact(() => {
1942
+ removeBlockFromFragment(yDoc.getXmlFragment("document"), blockId);
1943
+ yDoc.getMap("qi.flow.nodes").delete(nodeId);
1944
+ yDoc.getMap("qi.flow.blockIndex").delete(nodeId);
1945
+ const order = yDoc.getArray("qi.flow.order");
1946
+ const idx = order.toArray().indexOf(nodeId);
1947
+ if (idx >= 0) order.delete(idx, 1);
1948
+ const edges = yDoc.getMap("qi.flow.edges");
1949
+ for (const key of [...edges.keys()]) {
1950
+ const e = edges.get(key);
1951
+ if (isYMapLike(e) && (e.get("source") === nodeId || e.get("target") === nodeId)) edges.delete(key);
1952
+ }
1953
+ advanceDraftRevision(yDoc);
1954
+ });
1955
+ return { ok: true };
1956
+ }
1957
+ function reorderFlowNodes(yDoc, order) {
1958
+ const orderArr = yDoc.getArray("qi.flow.order");
1959
+ const current = orderArr.toArray();
1960
+ if (order.length !== current.length) return false;
1961
+ if (new Set(order).size !== order.length) return false;
1962
+ const currentSet = new Set(current);
1963
+ if (!order.every((id) => currentSet.has(id))) return false;
1964
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
1965
+ const fragment = yDoc.getXmlFragment("document");
1966
+ yDoc.transact(() => {
1967
+ orderArr.delete(0, orderArr.length);
1968
+ orderArr.push(order);
1969
+ if (!fragmentHasContentBlocks(fragment)) {
1970
+ const blocks = readBlocksFromFragment(fragment);
1971
+ const byId = new Map(blocks.map((b) => [b.id, b]));
1972
+ const orderedIds = order.map((nid) => blockIndex.get(nid)).filter((id) => !!id);
1973
+ const ordered = orderedIds.map((id) => byId.get(id)).filter((b) => !!b);
1974
+ const extras = blocks.filter((b) => !orderedIds.includes(b.id));
1975
+ removeAllFlowBlocks(fragment);
1976
+ writeCompiledBlocksToFragment(fragment, [...ordered, ...extras]);
1977
+ }
1978
+ advanceDraftRevision(yDoc);
1979
+ });
1980
+ return true;
1981
+ }
1982
+ function swapFlowBlocks(yDoc, blockIdA, blockIdB) {
1983
+ const fragment = yDoc.getXmlFragment("document");
1984
+ let ok = false;
1985
+ yDoc.transact(() => {
1986
+ ok = swapBlocksInFragment(fragment, blockIdA, blockIdB);
1987
+ if (!ok) return;
1988
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
1989
+ let nodeA;
1990
+ let nodeB;
1991
+ for (const [nodeId, bId] of blockIndex.entries()) {
1992
+ if (bId === blockIdA) nodeA = nodeId;
1993
+ else if (bId === blockIdB) nodeB = nodeId;
1994
+ }
1995
+ if (nodeA && nodeB) {
1996
+ const order = yDoc.getArray("qi.flow.order");
1997
+ const arr = order.toArray();
1998
+ const ia = arr.indexOf(nodeA);
1999
+ const ib = arr.indexOf(nodeB);
2000
+ if (ia >= 0 && ib >= 0) {
2001
+ [arr[ia], arr[ib]] = [arr[ib], arr[ia]];
2002
+ order.delete(0, order.length);
2003
+ order.push(arr);
2004
+ }
2005
+ }
2006
+ advanceDraftRevision(yDoc);
2007
+ });
2008
+ return ok;
2009
+ }
2010
+ function updateNodeRuntime(yDoc, blockId, partial, runId) {
2011
+ writeActionState(yDoc, resolveRunIdForExecution(yDoc, runId), blockId, partial);
2012
+ }
2013
+ function resetStepRuntime(yDoc, blockId, runId) {
2014
+ updateNodeRuntime(yDoc, blockId, { state: "idle", error: void 0, output: {} }, runId);
2015
+ }
2016
+ function setFormAnswers(yDoc, blockId, answers, runId) {
2017
+ const resolvedRunId = resolveRunIdForExecution(yDoc, runId);
2018
+ const base = readActionState(yDoc, resolvedRunId, blockId);
2019
+ const output = base.output && typeof base.output === "object" ? base.output : {};
2020
+ const form = output.form && typeof output.form === "object" ? output.form : {};
2021
+ writeActionState(yDoc, resolvedRunId, blockId, { output: { ...output, form: { ...form, answers: JSON.stringify(answers) } } });
2022
+ }
2023
+ function safeParseJson(value, fallback) {
2024
+ if (typeof value !== "string" || value.length === 0) return fallback;
2025
+ try {
2026
+ return JSON.parse(value);
2027
+ } catch {
2028
+ return fallback;
2029
+ }
2030
+ }
2031
+ function advanceDraftRevision(yDoc) {
2032
+ const meta = yDoc.getMap("qi.flow.meta");
2033
+ const current = Number(meta.get("draftRevision") ?? 0);
2034
+ if (meta.get("draftSchemaVersion") !== 1) return current;
2035
+ const next = current + 1;
2036
+ meta.set("draftRevision", next);
2037
+ meta.set(
2038
+ "definitionDigest",
2039
+ sha256Digest({
2040
+ nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
2041
+ edges: yDoc.getMap("qi.flow.edges").toJSON(),
2042
+ order: yDoc.getArray("qi.flow.order").toArray()
2043
+ })
2044
+ );
2045
+ meta.set("executionSchemaVersion", 3);
2046
+ meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
2047
+ return next;
2048
+ }
2049
+ function stableProps(props) {
2050
+ return JSON.stringify(
2051
+ Object.fromEntries(
2052
+ Object.entries(props).filter(([, value]) => value !== "").sort(([left], [right]) => left.localeCompare(right))
2053
+ )
2054
+ );
2055
+ }
2056
+ function findNodeIdForBlock(yDoc, blockId) {
2057
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
2058
+ for (const [nodeId, bId] of blockIndex.entries()) {
2059
+ if (bId === blockId) return nodeId;
2060
+ }
2061
+ return void 0;
2062
+ }
2063
+ function actorFromProps(props) {
2064
+ const authorisedActors = safeParseJson(props.authorisedActors, void 0);
2065
+ const parentCapability = props.parentCapability && props.parentCapability.length > 0 ? props.parentCapability : void 0;
2066
+ const hasActors = Array.isArray(authorisedActors) && authorisedActors.length > 0;
2067
+ if (!hasActors && !parentCapability) return void 0;
2068
+ const actor = {};
2069
+ if (hasActors) actor.authorisedActors = authorisedActors;
2070
+ if (parentCapability) actor.parentCapability = parentCapability;
2071
+ return actor;
2072
+ }
2073
+ function nodeReferences(node, nodeId, blockId) {
2074
+ const trigger = safeParseJson(node.props.trigger, void 0);
2075
+ if (trigger?.sourceBlockId === nodeId || trigger?.sourceBlockId === blockId) return true;
2076
+ if (Array.isArray(trigger?.sources) && trigger.sources.some((s) => s?.sourceBlockId === nodeId || s?.sourceBlockId === blockId)) return true;
2077
+ const cond = safeParseJson(node.props.conditions, void 0);
2078
+ if (Array.isArray(cond?.conditions) && cond.conditions.some((c) => c?.sourceBlockId === blockId)) return true;
2079
+ const inputs = typeof node.props.inputs === "string" ? node.props.inputs : "";
2080
+ if (inputs.includes(`${nodeId}.output`)) return true;
2081
+ return false;
2082
+ }
2083
+ function fragmentHasContentBlocks(fragment) {
2084
+ if (fragment.length === 0) return false;
2085
+ const root = fragment.get(0);
2086
+ if (!isYXmlElementLike(root) || root.nodeName !== "blockGroup") return false;
2087
+ for (let i = 0; i < root.length; i++) {
2088
+ const container = root.get(i);
2089
+ if (!isYXmlElementLike(container)) continue;
2090
+ const content = container.get(0);
2091
+ if (isYXmlElementLike(content) && content.length > 0) return true;
2092
+ }
2093
+ return false;
2094
+ }
2095
+
2096
+ // src/core/lib/flowAgent/policy.ts
2097
+ var COMMAND_CAPABILITIES = {
2098
+ diagnose_blocker: "flow/observe",
2099
+ assign_actor: "flow/node/assign",
2100
+ notify_actor: "flow/notify",
2101
+ execute_action: "flow/node/execute",
2102
+ validate_external_state: "flow/mutation/execute",
2103
+ archive_flow: "flow/archive",
2104
+ propose_config_change: "flow/config/propose"
2105
+ };
2106
+ function requiredCapabilityForCommand(type, flowUri, nodeId) {
2107
+ return capabilityForCommand(COMMAND_CAPABILITIES[type], flowUri, nodeId);
2108
+ }
2109
+ function isCapabilityMatch(granted, required) {
2110
+ return canMatches(granted.can, required.can) && resourceMatches(granted.with, required.with);
2111
+ }
2112
+ function canMatches(granted, required) {
2113
+ return capabilityPatternCoversCan(granted, required, { allowGlobalWildcard: true });
2114
+ }
2115
+ function resourceMatches(granted, required) {
2116
+ if (granted === "*" || granted === required) return true;
2117
+ if (granted.endsWith("*")) {
2118
+ const prefix = granted.slice(0, -1);
2119
+ return required.startsWith(prefix);
2120
+ }
2121
+ return false;
2122
+ }
2123
+ function evaluateFlowAgentPolicy({
2124
+ actorDid,
2125
+ commandType,
2126
+ flowUri,
2127
+ nodeId,
2128
+ delegationStore,
2129
+ delegations,
2130
+ now = Date.now()
2131
+ }) {
2132
+ const required = requiredCapabilityForCommand(commandType, flowUri, nodeId);
2133
+ const candidates = delegations || delegationStore?.getByAudience(actorDid) || [];
2134
+ for (const delegation of candidates) {
2135
+ if (delegation.audienceDid !== actorDid) continue;
2136
+ if (delegation.expiration != null && delegation.expiration <= now) continue;
2137
+ if (!delegation.capabilities.some((capability) => isCapabilityMatch(capability, required))) continue;
2138
+ return {
2139
+ allowed: true,
2140
+ reason: "Allowed by UCAN delegation",
2141
+ capability: required,
2142
+ proofCids: [delegation.cid, ...delegation.proofCids]
2143
+ };
2144
+ }
2145
+ return {
2146
+ allowed: false,
2147
+ reason: `Actor ${actorDid} lacks ${required.can} on ${required.with}`,
2148
+ capability: required,
2149
+ proofCids: []
2150
+ };
2151
+ }
2152
+
2153
+ // src/core/lib/flowAgent/commands.ts
2154
+ function createAgentCommand({ type, flowId, sessionRunId, flowUri, nodeId, actor, reason, payload = {}, now = Date.now() }) {
2155
+ const capability = requiredCapabilityForCommand(type, flowUri, nodeId);
2156
+ const id = computeAgentCommandId({ flowId, sessionRunId, nodeId, type, payload });
2157
+ return {
2158
+ id,
2159
+ type,
2160
+ flowId,
2161
+ sessionRunId,
2162
+ flowUri,
2163
+ nodeId,
2164
+ actorDid: actor.did,
2165
+ status: "queued",
2166
+ capability,
2167
+ idempotencyKey: `${id}:${createIntentHash({ capability, payload })}`,
2168
+ createdAt: now,
2169
+ updatedAt: now,
2170
+ reason,
2171
+ payload
2172
+ };
2173
+ }
2174
+ function validateAgentCommand(command) {
2175
+ if (!command.id) return { valid: false, error: "Command id is required" };
2176
+ if (!command.flowId) return { valid: false, error: "flowId is required" };
2177
+ if (!command.sessionRunId) return { valid: false, error: "sessionRunId is required" };
2178
+ if (!command.flowUri) return { valid: false, error: "flowUri is required" };
2179
+ if (!command.nodeId) return { valid: false, error: "nodeId is required" };
2180
+ if (!command.actorDid) return { valid: false, error: "actorDid is required" };
2181
+ if (!command.capability?.can || !command.capability?.with) return { valid: false, error: "capability is required" };
2182
+ if (!command.idempotencyKey) return { valid: false, error: "idempotencyKey is required" };
2183
+ if (isExternalMutation(command.type) && !command.payload.validator) {
2184
+ return {
2185
+ valid: false,
2186
+ error: `${command.type} requires payload.validator for post-action read-back validation`
2187
+ };
2188
+ }
2189
+ if (command.type === "propose_config_change" && !command.payload.proposal) {
2190
+ return { valid: false, error: "Config changes must be expressed as payload.proposal" };
2191
+ }
2192
+ return { valid: true };
2193
+ }
2194
+ function isExternalMutation(type) {
2195
+ return type === "validate_external_state";
2196
+ }
2197
+
2198
+ // src/core/lib/flowAgent/context.ts
2199
+ function buildFlowAgentContext({
2200
+ yDoc,
2201
+ flowId,
2202
+ sessionRunId,
2203
+ flowUri = `ixo:flow:${flowId}`,
2204
+ actor,
2205
+ blocks,
2206
+ documentBlocks,
2207
+ editor,
2208
+ now
2209
+ }) {
2210
+ return {
2211
+ yDoc,
2212
+ flowId,
2213
+ sessionRunId,
2214
+ flowUri,
2215
+ actor,
2216
+ ...blocks ? { blocks } : {},
2217
+ ...documentBlocks ? { documentBlocks } : {},
2218
+ ...editor ? { editor } : {},
2219
+ ...now ? { now } : {}
2220
+ };
2221
+ }
2222
+
2223
+ // src/core/lib/flowAgent/lease.ts
2224
+ var DEFAULT_FLOW_AGENT_LEASE_TTL_MS = 6e4;
2225
+ function acquireFlowAgentLease({
2226
+ leases,
2227
+ commandId,
2228
+ sessionRunId,
2229
+ nodeId,
2230
+ actorDid,
2231
+ now = Date.now(),
2232
+ ttlMs = DEFAULT_FLOW_AGENT_LEASE_TTL_MS
2233
+ }) {
2234
+ const current = leases.get(commandId);
2235
+ if (current && current.expiresAt > now && current.actorDid !== actorDid) {
2236
+ return null;
2237
+ }
2238
+ const nextEpoch = current ? current.epoch + 1 : 1;
2239
+ const lease = {
2240
+ id: `${commandId}:lease:${nextEpoch}`,
2241
+ commandId,
2242
+ sessionRunId,
2243
+ nodeId,
2244
+ actorDid,
2245
+ acquiredAt: now,
2246
+ expiresAt: now + ttlMs,
2247
+ epoch: nextEpoch
2248
+ };
2249
+ leases.set(commandId, lease);
2250
+ return lease;
2251
+ }
2252
+ function validateFlowAgentLease(leases, lease, now = Date.now()) {
2253
+ const current = leases.get(lease.commandId);
2254
+ return !!current && current.actorDid === lease.actorDid && current.epoch === lease.epoch && current.expiresAt > now;
2255
+ }
2256
+ function releaseFlowAgentLease(leases, lease) {
2257
+ const current = leases.get(lease.commandId);
2258
+ if (!current || current.actorDid !== lease.actorDid || current.epoch !== lease.epoch) return false;
2259
+ leases.delete(lease.commandId);
2260
+ return true;
2261
+ }
2262
+ function cleanupExpiredFlowAgentLeases(leases, now = Date.now()) {
2263
+ const expired = [];
2264
+ leases.forEach((lease, commandId) => {
2265
+ if (lease.expiresAt <= now) {
2266
+ expired.push(lease);
2267
+ leases.delete(commandId);
2268
+ }
2269
+ });
2270
+ return expired;
2271
+ }
2272
+
2273
+ // src/core/lib/flowAgent/state.ts
2274
+ function classifyBlockerCause(block, runtime) {
2275
+ const props = getBlockProps(block);
2276
+ if (runtime.error?.code === "missing_ucan") return "missing_ucan";
2277
+ if (runtime.error?.code === "validation_mismatch") return "validation_mismatch";
2278
+ if (runtime.error?.code === "external_confirmation_pending") return "external_confirmation_pending";
2279
+ if (runtime.error) return "service_error";
2280
+ const conditions = parseJsonProp(props.conditions, {});
2281
+ if (conditions.enabled && Array.isArray(conditions.conditions) && conditions.conditions.length > 0) {
2282
+ return "failed_upstream";
2283
+ }
2284
+ const inputs = parseJsonProp(props.inputs, {});
2285
+ const requiredInputs = parseJsonProp(props.requiredInputs, []);
2286
+ if (requiredInputs.some((key) => inputs[key] == null || inputs[key] === "")) {
2287
+ return "missing_input";
2288
+ }
2289
+ return void 0;
2290
+ }
2291
+ function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0, completionVerification }) {
2292
+ const derived = deriveBlockPhase({
2293
+ runtime,
2294
+ actionType: getBlockActionType(block),
2295
+ completionVerification,
2296
+ pendingInvocationCount
2297
+ });
2298
+ if (derived.phase === "failed") return "Blocked";
2299
+ if (derived.phase === "complete") return "Done";
2300
+ if (derived.detail === "standing" && pendingInvocationCount === 0) return "Done";
2301
+ if (runtime.error) return "Blocked";
2302
+ const dueAt = getDueAt(block);
2303
+ if (dueAt != null && dueAt <= now) return "Overdue";
2304
+ return "Pending";
2305
+ }
2306
+ function snapshotNode(block, runtime, now, pendingInvocationCount = 0, completionVerification) {
2307
+ const nodeId = getBlockId(block);
2308
+ if (!nodeId) {
2309
+ throw new Error("Cannot snapshot a block without an id");
2310
+ }
2311
+ const publicState = classifyNodeState({ block, runtime, now, pendingInvocationCount, completionVerification });
2312
+ const dueAt = getDueAt(block);
2313
+ const assigneeDid = getAssigneeDid(block);
2314
+ const snapshot = {
2315
+ nodeId,
2316
+ blockType: getBlockType(block),
2317
+ runtime,
2318
+ publicState,
2319
+ pendingInvocationCount
2320
+ };
2321
+ const actionType = getBlockActionType(block);
2322
+ if (actionType) snapshot.actionType = actionType;
2323
+ const title = getBlockTitle(block);
2324
+ if (title) snapshot.title = title;
2325
+ if (publicState === "Blocked") {
2326
+ if (runtime.state === "needs_verification") {
2327
+ snapshot.blockerCause = "awaiting_verification";
2328
+ } else {
2329
+ snapshot.blockerCause = classifyBlockerCause(block, runtime) || "unknown";
2330
+ }
2331
+ }
2332
+ if (assigneeDid) snapshot.assigneeDid = assigneeDid;
2333
+ if (dueAt != null) snapshot.dueAt = dueAt;
2334
+ return snapshot;
2335
+ }
2336
+
2337
+ // src/core/lib/flowAgent/actionExecutionPolicy.ts
2338
+ var RUNTIME_INPUT_REQUIRED_ACTIONS = /* @__PURE__ */ new Set(["qi/form.submit", "qi/human.form.submit", "qi/human.checkbox.set", "qi/protocol.select"]);
2339
+ function isRecord(value) {
2340
+ return value != null && typeof value === "object" && !Array.isArray(value);
2341
+ }
2342
+ function parseStringList(value) {
2343
+ const parsed = parseJsonProp(value, []);
2344
+ if (!Array.isArray(parsed)) return [];
2345
+ return parsed.filter((item) => typeof item === "string" && item.length > 0);
2346
+ }
2347
+ function normalizeMode(value) {
2348
+ if (value === "saved-input" || value === "saved_input" || value === "savedInput") return "saved-input";
2349
+ if (value === "runtime-input-required" || value === "runtime_input_required" || value === "runtimeInputRequired") return "runtime-input-required";
2350
+ if (value === "human-only" || value === "human_only" || value === "humanOnly") return "human-only";
2351
+ return void 0;
2352
+ }
2353
+ function parseExecutionConfig(value) {
2354
+ if (value == null || value === "") return {};
2355
+ if (typeof value === "string") {
2356
+ const directMode = normalizeMode(value);
2357
+ if (directMode) return { mode: directMode };
2358
+ }
2359
+ const parsed = parseJsonProp(value, {});
2360
+ if (!isRecord(parsed)) return {};
2361
+ return {
2362
+ mode: normalizeMode(parsed.mode),
2363
+ requiredRuntimeInputs: parseStringList(parsed.requiredRuntimeInputs)
2364
+ };
2365
+ }
2366
+ function inferDefaultMode(actionType, requiredRuntimeInputs) {
2367
+ if (requiredRuntimeInputs.length > 0) return "runtime-input-required";
2368
+ if (actionType && RUNTIME_INPUT_REQUIRED_ACTIONS.has(actionType)) return "runtime-input-required";
2369
+ return "saved-input";
2370
+ }
2371
+ function getFlowAgentActionExecutionPolicy(block) {
2372
+ const props = getBlockProps(block);
2373
+ const actionType = getBlockActionType(block);
2374
+ const config = parseExecutionConfig(props.flowAgentExecution || props.flowAgentExecutionMode || props.agentExecutionMode);
2375
+ const requiredRuntimeInputs = [
2376
+ ...config.requiredRuntimeInputs || [],
2377
+ ...parseStringList(props.requiredRuntimeInputs || props.runtimeRequiredInputs || props.flowAgentRequiredRuntimeInputs)
2378
+ ];
2379
+ return {
2380
+ mode: config.mode || inferDefaultMode(actionType, requiredRuntimeInputs),
2381
+ requiredRuntimeInputs: Array.from(new Set(requiredRuntimeInputs))
2382
+ };
2383
+ }
2384
+ function getCommandRuntimeInputs(payload) {
2385
+ return isRecord(payload.runtimeInputs) ? payload.runtimeInputs : void 0;
2386
+ }
2387
+ function validateFlowAgentExecuteActionPayload(block, payload) {
2388
+ const policy = getFlowAgentActionExecutionPolicy(block);
2389
+ if (policy.mode === "human-only") {
2390
+ return {
2391
+ valid: false,
2392
+ mode: policy.mode,
2393
+ missingRuntimeInputs: [],
2394
+ reason: "Action requires human execution and cannot be run by the Flow Agent"
2395
+ };
2396
+ }
2397
+ if (policy.mode !== "runtime-input-required") {
2398
+ return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };
2399
+ }
2400
+ const runtimeInputs = getCommandRuntimeInputs(payload);
2401
+ const missingRuntimeInputs = policy.requiredRuntimeInputs.length > 0 ? policy.requiredRuntimeInputs.filter((key) => runtimeInputs?.[key] == null || runtimeInputs[key] === "") : runtimeInputs ? [] : ["runtimeInputs"];
2402
+ if (missingRuntimeInputs.length > 0) {
2403
+ return {
2404
+ valid: false,
2405
+ mode: policy.mode,
2406
+ missingRuntimeInputs,
2407
+ reason: policy.requiredRuntimeInputs.length > 0 ? `Missing required runtimeInputs: ${missingRuntimeInputs.join(", ")}` : "Action requires runtimeInputs before the Flow Agent can execute it"
2408
+ };
2409
+ }
2410
+ return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };
2411
+ }
2412
+
2413
+ // src/core/lib/flowAgent/orchestrator.ts
2414
+ var BLOCKER_DIAGNOSIS_VERSION = 2;
2415
+ function getBlocks(context) {
2416
+ const flattened = [];
2417
+ const visit = (block) => {
2418
+ flattened.push(block);
2419
+ const children = block?.children;
2420
+ if (Array.isArray(children)) children.forEach(visit);
2421
+ };
2422
+ (context.blocks || context.editor?.document || []).forEach(visit);
2423
+ return flattened;
2424
+ }
2425
+ function getConditionDocument(context) {
2426
+ return context.documentBlocks || context.blocks || context.editor?.document || [];
2427
+ }
2428
+ function getRuntime(yDoc, sessionRunId, nodeId) {
2429
+ const value = readActionState(yDoc, sessionRunId, nodeId);
2430
+ return value && typeof value === "object" ? value : {};
2431
+ }
2432
+ function validateInputs(block) {
2433
+ const props = getBlockProps(block);
2434
+ const inputs = parseJsonProp(props.inputs, {});
2435
+ const requiredInputs = parseJsonProp(props.requiredInputs, []);
2436
+ const missing = requiredInputs.filter((key) => inputs[key] == null || inputs[key] === "");
2437
+ if (missing.length > 0) {
2438
+ return { valid: false, reason: `Missing required inputs: ${missing.join(", ")}` };
2439
+ }
2440
+ return { valid: true };
2441
+ }
2442
+ function chooseActor(block, options) {
2443
+ const props = getBlockProps(block);
2444
+ const actionType = getBlockActionType(block);
2445
+ const requiredSkill = typeof props.requiredSkill === "string" ? props.requiredSkill : actionType;
2446
+ if (!options.candidateActors || options.candidateActors.length === 0) return void 0;
2447
+ if (!requiredSkill) return options.candidateActors[0];
2448
+ return options.candidateActors.find((actor) => actor.skills?.includes(requiredSkill)) || options.candidateActors[0];
2449
+ }
2450
+ function canQueueCommand(type, nodeId, context, options) {
2451
+ return evaluateFlowAgentPolicy({
2452
+ actorDid: context.actor.did,
2453
+ commandType: type,
2454
+ flowUri: context.flowUri,
2455
+ nodeId,
2456
+ delegationStore: options.delegationStore,
2457
+ delegations: options.delegations,
2458
+ now: context.now?.() || Date.now()
2459
+ }).allowed;
2460
+ }
2461
+ function safeAppendAgentLedgerEvent(yDoc, event) {
2462
+ try {
2463
+ appendAgentLedgerEvent(yDoc, event);
2464
+ } catch (error) {
2465
+ const message = error instanceof Error ? error.message : "Failed to append flow-agent ledger event";
2466
+ if (message.includes("Unexpected content type") || message.includes("already been defined with a different constructor")) {
2467
+ return;
2468
+ }
2469
+ throw error;
2470
+ }
2471
+ }
2472
+ function queueIfAuthorized(context, options, type, nodeId, reason, payload) {
2473
+ const now = context.now?.() || Date.now();
2474
+ const policy = evaluateFlowAgentPolicy({
2475
+ actorDid: context.actor.did,
2476
+ commandType: type,
2477
+ flowUri: context.flowUri,
2478
+ nodeId,
2479
+ delegationStore: options.delegationStore,
2480
+ delegations: options.delegations,
2481
+ now
2482
+ });
2483
+ safeAppendAgentLedgerEvent(context.yDoc, {
2484
+ type: "agent.decision",
2485
+ flowId: context.flowId,
2486
+ sessionRunId: context.sessionRunId,
2487
+ nodeId,
2488
+ actorDid: context.actor.did,
2489
+ timestamp: now,
2490
+ details: {
2491
+ commandType: type,
2492
+ allowed: policy.allowed,
2493
+ reason: policy.reason,
2494
+ capability: policy.capability
2495
+ }
2496
+ });
2497
+ if (!policy.allowed) return null;
2498
+ const command = createAgentCommand({
2499
+ type,
2500
+ flowId: context.flowId,
2501
+ sessionRunId: context.sessionRunId,
2502
+ flowUri: context.flowUri,
2503
+ nodeId,
2504
+ actor: context.actor,
2505
+ reason,
2506
+ payload,
2507
+ now
2508
+ });
2509
+ const validation = validateAgentCommand(command);
2510
+ if (!validation.valid) {
2511
+ safeAppendAgentLedgerEvent(context.yDoc, {
2512
+ type: "agent.validation",
2513
+ flowId: context.flowId,
2514
+ sessionRunId: context.sessionRunId,
2515
+ nodeId,
2516
+ commandId: command.id,
2517
+ actorDid: context.actor.did,
2518
+ timestamp: now,
2519
+ details: { valid: false, error: validation.error }
2520
+ });
2521
+ return null;
2522
+ }
2523
+ return queueAgentCommand(context.yDoc, command).created ? command : null;
2524
+ }
2525
+ function statusForResult(result) {
2526
+ if (result.status) return result.status;
2527
+ if (!result.success) return "failed";
2528
+ return result.confirmed === false ? "awaiting_readback" : "confirmed";
2529
+ }
2530
+ function planForSnapshot(context, options, block, snapshot) {
2531
+ const queued = [];
2532
+ const actionType = getBlockActionType(block);
2533
+ if (snapshot.publicState === "Done") {
2534
+ return queued;
2535
+ }
2536
+ if (snapshot.publicState === "Overdue") {
2537
+ const command = queueIfAuthorized(context, options, "notify_actor", snapshot.nodeId, "Action node is overdue", {
2538
+ assigneeDid: snapshot.assigneeDid,
2539
+ dueAt: snapshot.dueAt,
2540
+ severity: "overdue"
2541
+ });
2542
+ if (command) queued.push(command);
2543
+ return queued;
2544
+ }
2545
+ if (snapshot.publicState === "Blocked") {
2546
+ const command = queueIfAuthorized(context, options, "diagnose_blocker", snapshot.nodeId, "Action node is blocked and requires diagnosis", {
2547
+ cause: snapshot.blockerCause || "unknown",
2548
+ error: snapshot.runtime.error,
2549
+ diagnosisVersion: BLOCKER_DIAGNOSIS_VERSION
2550
+ });
2551
+ if (command) queued.push(command);
2552
+ return queued;
2553
+ }
2554
+ const assigneeDid = getAssigneeDid(block);
2555
+ if (!assigneeDid) {
2556
+ const actor = chooseActor(block, options);
2557
+ const command = queueIfAuthorized(context, options, "assign_actor", snapshot.nodeId, "Action node has no assigned actor", {
2558
+ targetActorDid: actor?.did,
2559
+ targetMatrixUserId: actor?.matrixUserId,
2560
+ requiredActionType: actionType
2561
+ });
2562
+ if (command) queued.push(command);
2563
+ return queued;
2564
+ }
2565
+ const inputValidation = validateInputs(block);
2566
+ if (!inputValidation.valid) {
2567
+ const command = queueIfAuthorized(context, options, "diagnose_blocker", snapshot.nodeId, inputValidation.reason || "Action node inputs are not ready", {
2568
+ cause: "missing_input"
2569
+ });
2570
+ if (command) queued.push(command);
2571
+ return queued;
2572
+ }
2573
+ if (actionType && canQueueCommand("execute_action", snapshot.nodeId, context, options)) {
2574
+ const pendingInvocation = readPendingInvocations(context.yDoc, snapshot.nodeId, context.sessionRunId)[0];
2575
+ const payload = {
2576
+ actionType,
2577
+ ...pendingInvocation ? { pendingInvocationId: pendingInvocation.id } : {}
2578
+ };
2579
+ const actionValidation = validateFlowAgentExecuteActionPayload(block, payload);
2580
+ if (!actionValidation.valid) {
2581
+ const commandType = actionValidation.mode === "human-only" ? "notify_actor" : "diagnose_blocker";
2582
+ const command2 = queueIfAuthorized(context, options, commandType, snapshot.nodeId, actionValidation.reason || "Action node cannot be executed by Flow Agent yet", {
2583
+ cause: actionValidation.mode === "runtime-input-required" ? "missing_input" : "unknown",
2584
+ requiredActionType: actionType,
2585
+ requiredRuntimeInputs: actionValidation.missingRuntimeInputs,
2586
+ severity: actionValidation.mode === "human-only" ? "attention" : void 0
2587
+ });
2588
+ if (command2) queued.push(command2);
2589
+ return queued;
2590
+ }
2591
+ const command = queueIfAuthorized(context, options, "execute_action", snapshot.nodeId, "Action node is pending and executable", {
2592
+ ...payload
2593
+ });
2594
+ if (command) queued.push(command);
2595
+ return queued;
2596
+ }
2597
+ const notifyCommand = queueIfAuthorized(context, options, "notify_actor", snapshot.nodeId, "Action node is pending but the Flow Agent cannot execute it", {
2598
+ assigneeDid,
2599
+ requiredActionType: actionType,
2600
+ severity: "attention"
2601
+ });
2602
+ if (notifyCommand) queued.push(notifyCommand);
2603
+ return queued;
2604
+ }
2605
+ function planRalphLoopCommands(context, options = {}) {
2606
+ const now = context.now?.() || Date.now();
2607
+ const blocks = getBlocks(context);
2608
+ const conditionDocument = getConditionDocument(context);
2609
+ const snapshots = [];
2610
+ const queuedCommands = [];
2611
+ for (const block of blocks) {
2612
+ const nodeId = getBlockId(block);
2613
+ if (!nodeId) continue;
2614
+ const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId, context.sessionRunId).length;
2615
+ const runtime = getRuntime(context.yDoc, context.sessionRunId, nodeId);
2616
+ const snapshot = snapshotNode(block, runtime, now, pendingInvocationCount);
2617
+ try {
2618
+ const eligibility = evaluateBlockExecutionEligibilityForRun(
2619
+ parseConditionConfigStrict(getBlockProps(block).conditions),
2620
+ conditionDocument,
2621
+ context.yDoc,
2622
+ context.sessionRunId
2623
+ );
2624
+ if (!eligibility.eligible && snapshot.publicState !== "Done") {
2625
+ snapshot.publicState = "Blocked";
2626
+ snapshot.blockerCause = "failed_upstream";
2627
+ }
2628
+ } catch {
2629
+ if (snapshot.publicState !== "Done") {
2630
+ snapshot.publicState = "Blocked";
2631
+ snapshot.blockerCause = "validation_mismatch";
2632
+ }
2633
+ }
2634
+ snapshots.push(snapshot);
2635
+ queuedCommands.push(...planForSnapshot(context, options, block, snapshot));
2636
+ }
2637
+ const flowDone = snapshots.length > 0 && snapshots.every((snapshot) => snapshot.publicState === "Done");
2638
+ if (flowDone && options.archiveWhenDone === true) {
2639
+ const archiveCommand = queueIfAuthorized(context, options, "archive_flow", context.flowId, "All Ralph loop action nodes are done", {
2640
+ restartIfRepeats: true
2641
+ });
2642
+ if (archiveCommand) queuedCommands.push(archiveCommand);
2643
+ }
2644
+ return { snapshots, queuedCommands, flowDone };
2645
+ }
2646
+ async function callExecutor(command, context, executor) {
2647
+ switch (command.type) {
2648
+ case "execute_action":
2649
+ return executor.executeAction ? executor.executeAction(command, context) : { commandId: command.id, success: false, error: "No executeAction handler configured" };
2650
+ case "assign_actor":
2651
+ return executor.assignActor ? executor.assignActor(command, context) : { commandId: command.id, success: false, error: "No assignActor handler configured" };
2652
+ case "notify_actor":
2653
+ return executor.notifyActor ? executor.notifyActor(command, context) : { commandId: command.id, success: false, error: "No notifyActor handler configured" };
2654
+ case "validate_external_state":
2655
+ return executor.validateExternalState ? executor.validateExternalState(command, context) : { commandId: command.id, success: false, error: "No validateExternalState handler configured" };
2656
+ case "archive_flow":
2657
+ return executor.archiveFlow ? executor.archiveFlow(command, context) : { commandId: command.id, success: false, error: "No archiveFlow handler configured" };
2658
+ case "propose_config_change":
2659
+ return executor.proposeConfigChange ? executor.proposeConfigChange(command, context) : { commandId: command.id, success: false, error: "No proposeConfigChange handler configured" };
2660
+ case "diagnose_blocker":
2661
+ return executor.diagnoseBlocker ? executor.diagnoseBlocker(command, context) : { commandId: command.id, success: false, error: "No diagnoseBlocker handler configured" };
2662
+ }
2663
+ }
2664
+ async function executeQueuedAgentCommands(context, options = {}) {
2665
+ const executor = options.executor;
2666
+ if (!executor) return [];
2667
+ const now = context.now?.() || Date.now();
2668
+ const { leases } = getFlowAgentMaps(context.yDoc);
2669
+ const results = [];
2670
+ for (const command of readQueuedAgentCommands(context.yDoc, context.sessionRunId)) {
2671
+ const validation = validateAgentCommand(command);
2672
+ if (!validation.valid) {
2673
+ updateAgentCommand(context.yDoc, command.id, { status: "failed", error: validation.error, updatedAt: now });
2674
+ results.push({ commandId: command.id, success: false, error: validation.error });
2675
+ continue;
2676
+ }
2677
+ const policy = evaluateFlowAgentPolicy({
2678
+ actorDid: context.actor.did,
2679
+ commandType: command.type,
2680
+ flowUri: context.flowUri,
2681
+ nodeId: command.nodeId,
2682
+ delegationStore: options.delegationStore,
2683
+ delegations: options.delegations,
2684
+ now
2685
+ });
2686
+ if (!policy.allowed) {
2687
+ updateAgentCommand(context.yDoc, command.id, { status: "skipped", error: policy.reason, updatedAt: now });
2688
+ results.push({ commandId: command.id, success: false, error: policy.reason });
2689
+ continue;
2690
+ }
2691
+ const lease = acquireFlowAgentLease({
2692
+ leases,
2693
+ commandId: command.id,
2694
+ sessionRunId: context.sessionRunId,
2695
+ nodeId: command.nodeId,
2696
+ actorDid: context.actor.did,
2697
+ now,
2698
+ ttlMs: options.leaseTtlMs
2699
+ });
2700
+ if (!lease) {
2701
+ continue;
2702
+ }
2703
+ updateAgentCommand(context.yDoc, command.id, { status: "running", lease, updatedAt: now });
2704
+ try {
2705
+ const result = await callExecutor({ ...command, lease, status: "running" }, context, executor);
2706
+ if (!validateFlowAgentLease(leases, lease, context.now?.() || Date.now())) {
2707
+ const leaseError = "Lease expired or was superseded before command commit";
2708
+ updateAgentCommand(context.yDoc, command.id, { status: "failed", error: leaseError, updatedAt: context.now?.() || Date.now() });
2709
+ results.push({ commandId: command.id, success: false, error: leaseError });
2710
+ continue;
2711
+ }
2712
+ updateAgentCommand(context.yDoc, command.id, {
2713
+ status: statusForResult(result),
2714
+ error: result.error,
2715
+ updatedAt: context.now?.() || Date.now()
2716
+ });
2717
+ safeAppendAgentLedgerEvent(context.yDoc, {
2718
+ type: result.success ? "agent.validation" : "agent.escalation",
2719
+ flowId: context.flowId,
2720
+ sessionRunId: context.sessionRunId,
2721
+ nodeId: command.nodeId,
2722
+ commandId: command.id,
2723
+ actorDid: context.actor.did,
2724
+ timestamp: context.now?.() || Date.now(),
2725
+ details: {
2726
+ success: result.success,
2727
+ confirmed: result.confirmed,
2728
+ output: result.output,
2729
+ error: result.error
2730
+ }
2731
+ });
2732
+ results.push(result);
2733
+ } finally {
2734
+ releaseFlowAgentLease(leases, lease);
2735
+ }
2736
+ }
2737
+ return results;
2738
+ }
2739
+ async function tickFlowAgent(context, options = {}) {
2740
+ const plan = planRalphLoopCommands(context, options);
2741
+ const executedCommands = await executeQueuedAgentCommands(context, options);
2742
+ return {
2743
+ flowDone: plan.flowDone,
2744
+ snapshots: plan.snapshots,
2745
+ queuedCommands: plan.queuedCommands,
2746
+ executedCommands
2747
+ };
2748
+ }
2749
+
2750
+ // src/core/lib/flowAgent/execution.ts
2751
+ var DEFAULT_SCHEMA_VERSION = "1.0.0";
2752
+ function resolveExecutionContext(context) {
2753
+ const sessionRunId = resolveRunIdForExecution(context.yDoc, context.sessionRunId);
2754
+ return sessionRunId === context.sessionRunId ? context : { ...context, sessionRunId };
2755
+ }
2756
+ function safeAppendAgentLedgerEvent2(yDoc, event) {
2757
+ try {
2758
+ appendAgentLedgerEvent(yDoc, event);
2759
+ } catch (error) {
2760
+ const message = error instanceof Error ? error.message : "Failed to append flow-agent ledger event";
2761
+ if (message.includes("Unexpected content type") || message.includes("already been defined with a different constructor")) {
2762
+ return;
2763
+ }
2764
+ throw error;
2765
+ }
2766
+ }
2767
+ function getRuntimeRecord(yDoc, sessionRunId, nodeId) {
2768
+ return readActionState(yDoc, sessionRunId, nodeId);
2769
+ }
2770
+ function clearRuntimeBlocker(yDoc, sessionRunId, nodeId, updates) {
2771
+ const current = getRuntimeRecord(yDoc, sessionRunId, nodeId);
2772
+ const { state: _state, error: _error, ...rest } = current;
2773
+ resetActionState(yDoc, sessionRunId, nodeId, {
2774
+ ...rest,
2775
+ ...updates
2776
+ });
2777
+ }
2778
+ function findContextBlock(context, nodeId) {
2779
+ const visit = (blocks) => {
2780
+ for (const entry of blocks) {
2781
+ if (getBlockId(entry) === nodeId && entry && typeof entry === "object") {
2782
+ return entry;
2783
+ }
2784
+ const children = entry?.children;
2785
+ if (Array.isArray(children)) {
2786
+ const found = visit(children);
2787
+ if (found) return found;
2788
+ }
2789
+ }
2790
+ return null;
2791
+ };
2792
+ return visit(context.blocks || context.documentBlocks || context.editor?.document || []);
2793
+ }
2794
+ function getXmlAttribute(element, key) {
2795
+ return element.getAttribute(key);
2796
+ }
2797
+ function setXmlAttribute(element, key, value) {
2798
+ element.setAttribute(key, value);
2799
+ }
2800
+ function isRecord2(value) {
2801
+ return value != null && typeof value === "object" && !Array.isArray(value);
2802
+ }
2803
+ function isYXmlContainerLike(value) {
2804
+ return value != null && typeof value === "object" && typeof value.toArray === "function";
2805
+ }
2806
+ function isYXmlElementLike2(value) {
2807
+ return isYXmlContainerLike(value) && typeof value.nodeName === "string" && typeof value.getAttribute === "function" && typeof value.setAttribute === "function";
2808
+ }
2809
+ function getElementBlockId(element) {
2810
+ const directId = getXmlAttribute(element, "id");
2811
+ if (typeof directId === "string" && directId.length > 0) return directId;
2812
+ const attrs = getXmlAttribute(element, "attrs");
2813
+ const attrsId = isRecord2(attrs) ? attrs.id : void 0;
2814
+ return typeof attrsId === "string" && attrsId.length > 0 ? attrsId : void 0;
2815
+ }
2816
+ function updateXmlElementProps(element, blockId, propsPatch) {
2817
+ const attrs = getXmlAttribute(element, "attrs");
2818
+ if (isRecord2(attrs)) {
2819
+ const existingProps = isRecord2(attrs.props) ? attrs.props : {};
2820
+ setXmlAttribute(element, "attrs", {
2821
+ ...attrs,
2822
+ id: typeof attrs.id === "string" ? attrs.id : blockId,
2823
+ props: {
2824
+ ...existingProps,
2825
+ ...propsPatch
2826
+ }
2827
+ });
2828
+ }
2829
+ for (const [key, value] of Object.entries(propsPatch)) {
2830
+ element.setAttribute(key, typeof value === "string" ? value : JSON.stringify(value));
2831
+ }
2832
+ }
2833
+ function findXmlElementById(container, blockId) {
2834
+ for (const node of container.toArray()) {
2835
+ if (!isYXmlElementLike2(node)) continue;
2836
+ const id = getElementBlockId(node);
2837
+ if (id === blockId) return node;
2838
+ const nested = findXmlElementById(node, blockId);
2839
+ if (nested) return nested;
2840
+ }
2841
+ return null;
2842
+ }
2843
+ function updateDocumentBlockProps(yDoc, blockId, propsPatch) {
2844
+ const target = findXmlElementById(yDoc.getXmlFragment("document"), blockId);
2845
+ if (!target) return false;
2846
+ updateXmlElementProps(target, blockId, propsPatch);
2847
+ const content = target.toArray().find((node) => isYXmlElementLike2(node) && node.nodeName !== "blockGroup");
2848
+ if (content) {
2849
+ updateXmlElementProps(content, blockId, propsPatch);
2850
+ }
2851
+ return true;
2852
+ }
2853
+ function assignActorInYDoc(yDoc, command, context) {
2854
+ const targetActorDid = typeof command.payload.targetActorDid === "string" && command.payload.targetActorDid.length > 0 ? command.payload.targetActorDid : context.actor.did;
2855
+ const targetMatrixUserId = typeof command.payload.targetMatrixUserId === "string" ? command.payload.targetMatrixUserId : void 0;
2856
+ const assignment = {
2857
+ assignedActor: {
2858
+ did: targetActorDid,
2859
+ avatar: "",
2860
+ displayName: targetMatrixUserId || targetActorDid
2861
+ },
2862
+ assignedBy: {
2863
+ did: context.actor.did,
2864
+ avatar: "",
2865
+ displayName: context.actor.displayName || context.actor.matrixUserId || ""
2866
+ },
2867
+ assignedTimestamp: new Date(context.now?.() || Date.now()).toISOString()
2868
+ };
2869
+ const assignmentJson = JSON.stringify(assignment);
2870
+ const updatedDocument = updateDocumentBlockProps(yDoc, command.nodeId, {
2871
+ assignment: assignmentJson
2872
+ });
2873
+ if (!updatedDocument) {
2874
+ throw new Error(`Block ${command.nodeId} was not found for assignment`);
2875
+ }
2876
+ const runtime = createYDocRuntimeManager(yDoc, context.sessionRunId);
2877
+ runtime.update(command.nodeId, {
2878
+ assignedActorDid: targetActorDid,
2879
+ assignedByDid: context.actor.did,
2880
+ assignedAt: assignment.assignedTimestamp,
2881
+ lastCommandId: command.id
2882
+ });
2883
+ return assignment;
2884
+ }
2885
+ async function executeAssignActorCommand(command, context, options) {
2886
+ const capability = { can: "flow/node/assign", with: `${context.flowUri}:${command.nodeId}` };
2887
+ const proofs = await options.ucanService.findValidProofs(context.actor.did, capability);
2888
+ if (!proofs.found || !proofs.proofCids) {
2889
+ return {
2890
+ commandId: command.id,
2891
+ success: false,
2892
+ error: proofs.error || "No valid delegation found for assignment"
2893
+ };
2894
+ }
2895
+ const result = await options.ucanService.executeWithInvocation(
2896
+ {
2897
+ invokerDid: context.actor.did,
2898
+ invokerType: options.actorType,
2899
+ entityRoomId: options.entityRoomId,
2900
+ capability,
2901
+ proofs: proofs.proofCids,
2902
+ pin: options.pin
2903
+ },
2904
+ async () => assignActorInYDoc(context.yDoc, command, context),
2905
+ context.flowId,
2906
+ command.nodeId,
2907
+ context.sessionRunId
2908
+ );
2909
+ return {
2910
+ commandId: command.id,
2911
+ success: result.success,
2912
+ confirmed: result.success,
2913
+ output: result.actionResult && typeof result.actionResult === "object" ? { assignment: result.actionResult, invocationCid: result.invocationCid } : { invocationCid: result.invocationCid },
2914
+ error: result.error
2915
+ };
2916
+ }
2917
+ async function recoverPendingActionTimeline(command, context, options) {
2918
+ const pendingTimeline = readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId);
2919
+ if (pendingTimeline.length === 0) return void 0;
2920
+ if (!options.runEventLog) {
2921
+ return {
2922
+ commandId: command.id,
2923
+ success: false,
2924
+ confirmed: false,
2925
+ status: "awaiting_readback",
2926
+ error: "Canonical run history is pending and no run event log is available for replay."
2927
+ };
2928
+ }
2929
+ const replay = await retryPendingRunTimelineEvents({
2930
+ yDoc: context.yDoc,
2931
+ sessionRunId: context.sessionRunId,
2932
+ blockId: command.nodeId,
2933
+ eventLog: options.runEventLog,
2934
+ now: options.now || context.now
2935
+ });
2936
+ const current = readActionState(context.yDoc, context.sessionRunId, command.nodeId);
2937
+ const replayedOutput = boundRunActionOutput(current.output || {}).output;
2938
+ const replayStatus = replay.remaining > 0 || current.state === "awaiting_readback" ? "awaiting_readback" : current.state === "completed" ? "confirmed" : "failed";
2939
+ return {
2940
+ commandId: command.id,
2941
+ success: replayStatus === "confirmed",
2942
+ confirmed: replayStatus === "confirmed",
2943
+ status: replayStatus,
2944
+ output: {
2945
+ ...replayedOutput,
2946
+ ...current.lastEventId ? { lastEventId: current.lastEventId } : {},
2947
+ replayedTimelineEvents: replay.attempted,
2948
+ remainingTimelineEvents: replay.remaining
2949
+ },
2950
+ ...replay.remaining > 0 ? { error: "Canonical run history replay remains incomplete." } : replayStatus === "failed" ? {
2951
+ error: current.error?.message || "The action completed in a non-confirmable terminal state."
2952
+ } : {},
2953
+ completionState: current.state === "completed" ? "completed" : current.state === "needs_verification" ? "needs_verification" : current.state === "awaiting_readback" ? "awaiting_readback" : "failed"
2954
+ };
2955
+ }
2956
+ async function executeActionCommand(command, context, options) {
2957
+ const recoveredTimeline = await recoverPendingActionTimeline(command, context, options);
2958
+ if (recoveredTimeline) return recoveredTimeline;
2959
+ const actionType = typeof command.payload.actionType === "string" ? command.payload.actionType : void 0;
2960
+ if (!actionType) {
2961
+ return { commandId: command.id, success: false, error: "execute_action command is missing payload.actionType" };
2962
+ }
2963
+ const block = findContextBlock(context, command.nodeId);
2964
+ if (!block) {
2965
+ return { commandId: command.id, success: false, error: `Block ${command.nodeId} was not found in runtime context` };
2966
+ }
2967
+ const props = getBlockProps(block);
2968
+ if (typeof props.actionType === "string" && props.actionType !== actionType) {
2969
+ return {
2970
+ commandId: command.id,
2971
+ success: false,
2972
+ error: `execute_action payload.actionType ${actionType} does not match block actionType ${props.actionType}`
2973
+ };
2974
+ }
2975
+ const runtimeInputs = command.payload.runtimeInputs;
2976
+ if (runtimeInputs != null && !isRecord2(runtimeInputs)) {
2977
+ return { commandId: command.id, success: false, error: "execute_action payload.runtimeInputs must be an object when provided" };
2978
+ }
2979
+ const inputValidation = validateFlowAgentExecuteActionPayload(block, command.payload);
2980
+ if (!inputValidation.valid) {
2981
+ return {
2982
+ commandId: command.id,
2983
+ success: false,
2984
+ confirmed: false,
2985
+ status: inputValidation.mode === "human-only" ? "skipped" : "failed",
2986
+ error: inputValidation.reason
2987
+ };
2988
+ }
2989
+ const pendingInvocationId = typeof command.payload.pendingInvocationId === "string" ? command.payload.pendingInvocationId : void 0;
2990
+ const outcome = await executeActionBlock({
2991
+ editorOrYDoc: context.editor || context.yDoc,
2992
+ // The SESSION run (runs.ts), not the per-execution audit id. Constant in
2993
+ // Phase A; passed explicitly so the headless path is already shaped for
2994
+ // Phase B run selection instead of falling back to a doc-level default.
2995
+ runId: context.sessionRunId,
2996
+ block,
2997
+ blockId: command.nodeId,
2998
+ document: context.documentBlocks || context.blocks || context.editor?.document || [],
2999
+ actorDid: context.actor.did,
3000
+ actorType: options.actorType,
3001
+ entityRoomId: options.entityRoomId,
3002
+ ucanService: options.ucanService,
3003
+ invocationStore: options.invocationStore,
3004
+ services: options.actionServices || {},
3005
+ handlers: options.actionHandlers,
3006
+ runtimeInputs: getCommandRuntimeInputs(command.payload),
3007
+ pendingInvocationId,
3008
+ pin: options.pin,
3009
+ flowUri: context.flowUri,
3010
+ flowId: context.flowId,
3011
+ flowOwnerDid: options.flowOwnerDid || "",
3012
+ schemaVersion: options.schemaVersion || DEFAULT_SCHEMA_VERSION,
3013
+ runEventLog: options.runEventLog,
3014
+ now: options.now || context.now
3015
+ });
3016
+ const persisted = readActionState(context.yDoc, context.sessionRunId, command.nodeId);
3017
+ const durableOutput = boundRunActionOutput(persisted.output || {}).output;
3018
+ const pendingAfterExecution = readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId);
3019
+ const timelinePending = pendingAfterExecution.length > 0;
3020
+ return {
3021
+ commandId: command.id,
3022
+ success: outcome.success,
3023
+ confirmed: !timelinePending && outcome.success && outcome.completionState === "completed",
3024
+ ...timelinePending ? { status: "awaiting_readback" } : {},
3025
+ output: {
3026
+ ...durableOutput,
3027
+ ...persisted.lastEventId ? { lastEventId: persisted.lastEventId } : {},
3028
+ ...outcome.invocationCid ? { invocationCid: outcome.invocationCid } : {},
3029
+ ...outcome.capabilityId ? { capabilityId: outcome.capabilityId } : {},
3030
+ // Execution audit id under both names: `runId` is what flow-manager and
3031
+ // flow-agent read today (deprecated), `executionId` is the forward name.
3032
+ ...outcome.runId ? { runId: outcome.runId } : {},
3033
+ ...outcome.executionId ? { executionId: outcome.executionId } : {},
3034
+ ...pendingInvocationId ? { pendingInvocationId, pendingInvocationRemoved: outcome.pendingInvocationRemoved } : {},
3035
+ completionState: outcome.completionState,
3036
+ ...timelinePending ? { remainingTimelineEvents: pendingAfterExecution.length } : {}
3037
+ },
3038
+ error: timelinePending ? "The action effect completed, but canonical run history is pending replay." : outcome.error,
3039
+ completionState: outcome.completionState
3040
+ };
3041
+ }
3042
+ function getRecoverableBlockerReason(runtime) {
3043
+ const error = runtime.error;
3044
+ const message = error && typeof error === "object" && typeof error.message === "string" ? error.message : typeof error === "string" ? error : void 0;
3045
+ if (!message) return null;
3046
+ if (message.includes("Invalid DID") && message.includes("must start with 'did:'")) {
3047
+ return "matrix_did_normalization";
3048
+ }
3049
+ if (message.includes("Failed to parse URL from undefined")) {
3050
+ return "http_endpoint_input_normalization";
3051
+ }
3052
+ if (message.includes("Unexpected content type") || message.includes("already been defined with a different constructor")) {
3053
+ return "audit_trail_shape";
3054
+ }
3055
+ return null;
3056
+ }
3057
+ function resetFailedActionCommands(context, nodeId, now) {
3058
+ const { outbox } = getFlowAgentMaps(context.yDoc);
3059
+ const resetIds = [];
3060
+ outbox.forEach((command) => {
3061
+ if (command.sessionRunId !== context.sessionRunId || command.nodeId !== nodeId || command.type !== "execute_action" || command.status !== "failed") {
3062
+ return;
3063
+ }
3064
+ outbox.set(command.id, {
3065
+ ...command,
3066
+ status: "queued",
3067
+ error: void 0,
3068
+ lease: void 0,
3069
+ updatedAt: now,
3070
+ reason: `Retry after blocker diagnosis: ${command.reason}`
3071
+ });
3072
+ resetIds.push(command.id);
3073
+ });
3074
+ return resetIds;
3075
+ }
3076
+ async function executeDiagnoseBlockerCommand(command, context, options) {
3077
+ const now = options.now?.() || context.now?.() || Date.now();
3078
+ const runtime = getRuntimeRecord(context.yDoc, context.sessionRunId, command.nodeId);
3079
+ const recovery = getRecoverableBlockerReason(runtime);
3080
+ if (!recovery) {
3081
+ return {
3082
+ commandId: command.id,
3083
+ success: true,
3084
+ confirmed: true,
3085
+ output: {
3086
+ blockerCause: command.payload.cause || "unknown",
3087
+ recovery: "manual_intervention_required"
3088
+ }
3089
+ };
3090
+ }
3091
+ clearRuntimeBlocker(context.yDoc, context.sessionRunId, command.nodeId, {
3092
+ diagnosedAt: now,
3093
+ diagnosedByDid: context.actor.did,
3094
+ lastDiagnosisCommandId: command.id,
3095
+ lastRecovery: recovery
3096
+ });
3097
+ const resetCommandIds = resetFailedActionCommands(context, command.nodeId, now);
3098
+ return {
3099
+ commandId: command.id,
3100
+ success: true,
3101
+ confirmed: true,
3102
+ output: {
3103
+ blockerCause: command.payload.cause || "unknown",
3104
+ recovery,
3105
+ resetCommandIds
3106
+ }
3107
+ };
3108
+ }
3109
+ async function executeFlowAgentCoreCommand(command, context, options) {
3110
+ const executionContext = resolveExecutionContext(context);
3111
+ switch (command.type) {
3112
+ case "assign_actor":
3113
+ return executeAssignActorCommand(command, executionContext, options);
3114
+ case "execute_action":
3115
+ return executeActionCommand(command, executionContext, options);
3116
+ case "diagnose_blocker":
3117
+ return executeDiagnoseBlockerCommand(command, executionContext, options);
3118
+ default:
3119
+ return { commandId: command.id, success: false, error: `No editor-core executor for ${command.type}` };
3120
+ }
3121
+ }
3122
+ async function callConfiguredExecutor(command, context, options) {
3123
+ if (!options.executor) return void 0;
3124
+ switch (command.type) {
3125
+ case "assign_actor":
3126
+ return options.executor.assignActor?.(command, context);
3127
+ case "execute_action":
3128
+ return options.executor.executeAction?.(command, context);
3129
+ case "notify_actor":
3130
+ return options.executor.notifyActor?.(command, context);
3131
+ case "diagnose_blocker":
3132
+ return options.executor.diagnoseBlocker?.(command, context);
3133
+ default:
3134
+ return void 0;
3135
+ }
3136
+ }
3137
+ function statusForResult2(result) {
3138
+ if (result.status) return result.status;
3139
+ if (!result.success) return "failed";
3140
+ return result.confirmed === false ? "awaiting_readback" : "confirmed";
3141
+ }
3142
+ async function executeQueuedFlowAgentCoreCommands(context, options) {
3143
+ context = resolveExecutionContext(context);
3144
+ const now = options.now?.() || context.now?.() || Date.now();
3145
+ const { leases } = getFlowAgentMaps(context.yDoc);
3146
+ const results = [];
3147
+ const queued = readQueuedAgentCommands(context.yDoc, context.sessionRunId);
3148
+ const queuedIds = new Set(queued.map((command) => command.id));
3149
+ const retainedTimelineRecoveries = readAgentCommands(context.yDoc, context.sessionRunId).filter(
3150
+ (command) => command.status === "awaiting_readback" && command.type === "execute_action" && !queuedIds.has(command.id) && readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId).length > 0
3151
+ );
3152
+ for (const command of [...retainedTimelineRecoveries, ...queued]) {
3153
+ if (options.commandTypes && !options.commandTypes.includes(command.type)) {
3154
+ continue;
3155
+ }
3156
+ const validation = validateAgentCommand(command);
3157
+ if (!validation.valid) {
3158
+ updateAgentCommand(context.yDoc, command.id, { status: "failed", error: validation.error, updatedAt: now });
3159
+ results.push({ commandId: command.id, success: false, error: validation.error });
3160
+ continue;
3161
+ }
3162
+ const policy = evaluateFlowAgentPolicy({
3163
+ actorDid: context.actor.did,
3164
+ commandType: command.type,
3165
+ flowUri: context.flowUri,
3166
+ nodeId: command.nodeId,
3167
+ delegationStore: options.delegationStore,
3168
+ delegations: options.delegations,
3169
+ now
3170
+ });
3171
+ if (!policy.allowed) {
3172
+ updateAgentCommand(context.yDoc, command.id, { status: "skipped", error: policy.reason, updatedAt: now });
3173
+ results.push({ commandId: command.id, success: false, error: policy.reason });
3174
+ continue;
3175
+ }
3176
+ const lease = acquireFlowAgentLease({
3177
+ leases,
3178
+ commandId: command.id,
3179
+ sessionRunId: context.sessionRunId,
3180
+ nodeId: command.nodeId,
3181
+ actorDid: context.actor.did,
3182
+ now,
3183
+ ttlMs: options.leaseTtlMs
3184
+ });
3185
+ if (!lease) continue;
3186
+ updateAgentCommand(context.yDoc, command.id, { status: "running", lease, updatedAt: now });
3187
+ try {
3188
+ const runningCommand = { ...command, lease, status: "running" };
3189
+ const result = await Promise.resolve(callConfiguredExecutor(runningCommand, context, options)) || await executeFlowAgentCoreCommand(runningCommand, context, options);
3190
+ const normalized = result || {
3191
+ commandId: command.id,
3192
+ success: false,
3193
+ error: `No executor configured for ${command.type}`
3194
+ };
3195
+ if (!validateFlowAgentLease(leases, lease, options.now?.() || context.now?.() || Date.now())) {
3196
+ const error = "Lease expired or was superseded before command commit";
3197
+ updateAgentCommand(context.yDoc, command.id, { status: "failed", error, updatedAt: options.now?.() || context.now?.() || Date.now() });
3198
+ results.push({ commandId: command.id, success: false, error });
3199
+ continue;
3200
+ }
3201
+ updateAgentCommand(context.yDoc, command.id, {
3202
+ status: statusForResult2(normalized),
3203
+ error: normalized.error,
3204
+ updatedAt: options.now?.() || context.now?.() || Date.now()
3205
+ });
3206
+ safeAppendAgentLedgerEvent2(context.yDoc, {
3207
+ type: normalized.success ? "agent.validation" : "agent.escalation",
3208
+ flowId: context.flowId,
3209
+ sessionRunId: context.sessionRunId,
3210
+ nodeId: command.nodeId,
3211
+ commandId: command.id,
3212
+ actorDid: context.actor.did,
3213
+ timestamp: options.now?.() || context.now?.() || Date.now(),
3214
+ details: {
3215
+ success: normalized.success,
3216
+ confirmed: normalized.confirmed,
3217
+ output: boundRunActionOutput(normalized.output || {}).output,
3218
+ error: normalized.error
3219
+ }
3220
+ });
3221
+ results.push(normalized);
3222
+ } finally {
3223
+ releaseFlowAgentLease(leases, lease);
3224
+ }
3225
+ }
3226
+ return results;
3227
+ }
3228
+
3229
+ // src/core/lib/flowAgent/service.ts
3230
+ var FlowAgentService = class {
3231
+ constructor(context, options = {}) {
3232
+ this.context = context;
3233
+ this.options = options;
3234
+ this.timer = null;
3235
+ this.running = false;
3236
+ }
3237
+ async tick() {
3238
+ if (this.running) {
3239
+ return {
3240
+ flowDone: false,
3241
+ snapshots: [],
3242
+ queuedCommands: [],
3243
+ executedCommands: []
3244
+ };
3245
+ }
3246
+ this.running = true;
3247
+ try {
3248
+ const result = await tickFlowAgent(this.context, this.options);
3249
+ await this.options.onTick?.(result);
3250
+ return result;
3251
+ } catch (error) {
3252
+ this.options.onError?.(error);
3253
+ throw error;
3254
+ } finally {
3255
+ this.running = false;
3256
+ }
3257
+ }
3258
+ start() {
3259
+ if (this.timer) return;
3260
+ const intervalMs = this.options.intervalMs || 3e4;
3261
+ this.timer = setInterval(() => {
3262
+ this.tick().catch((error) => {
3263
+ this.options.onError?.(error);
3264
+ });
3265
+ }, intervalMs);
3266
+ }
3267
+ stop() {
3268
+ if (!this.timer) return;
3269
+ clearInterval(this.timer);
3270
+ this.timer = null;
3271
+ }
3272
+ };
3273
+
3274
+ export {
3275
+ readFlowDocumentHistory,
3276
+ getSharedFlowDocument,
3277
+ toEvaluatorOperator,
3278
+ buildBlockConditionsProp,
3279
+ compileBaseUcanFlow,
3280
+ ACTION_SAFETY_BY_TYPE,
3281
+ resolveActionSafety,
3282
+ ensureFlowExecutionMetadata,
3283
+ adoptLegacyFlowDocument,
3284
+ writeCompiledBlocksToFragment,
3285
+ removeBlockFromFragment,
3286
+ replaceBlockInFragment,
3287
+ readBlocksFromFragment,
3288
+ readCompiledFlowFromYDoc,
3289
+ mergeCompiledFlows,
3290
+ decompileToBaseUcanFlow,
3291
+ readFlowAsBaseUcan,
3292
+ readFlowFromEditor,
3293
+ setActiveEditor,
3294
+ getActiveEditor,
3295
+ readFlow,
3296
+ setupFlowFromBaseUcan,
3297
+ seedDesignPodTemplateFlow,
3298
+ readFlowDocument,
3299
+ addFlowNode,
3300
+ setBlockProps,
3301
+ syncFlowNodePropsFromProjection,
3302
+ auditFlowProjections,
3303
+ repairFlowProjections,
3304
+ removeFlowNode,
3305
+ reorderFlowNodes,
3306
+ swapFlowBlocks,
3307
+ updateNodeRuntime,
3308
+ resetStepRuntime,
3309
+ setFormAnswers,
3310
+ requiredCapabilityForCommand,
3311
+ isCapabilityMatch,
3312
+ canMatches,
3313
+ resourceMatches,
3314
+ evaluateFlowAgentPolicy,
3315
+ createAgentCommand,
3316
+ validateAgentCommand,
3317
+ isExternalMutation,
3318
+ buildFlowAgentContext,
3319
+ acquireFlowAgentLease,
3320
+ validateFlowAgentLease,
3321
+ releaseFlowAgentLease,
3322
+ cleanupExpiredFlowAgentLeases,
3323
+ classifyBlockerCause,
3324
+ classifyNodeState,
3325
+ snapshotNode,
3326
+ planRalphLoopCommands,
3327
+ executeQueuedAgentCommands,
3328
+ tickFlowAgent,
3329
+ executeFlowAgentCoreCommand,
3330
+ executeQueuedFlowAgentCoreCommands,
3331
+ FlowAgentService
3332
+ };
3333
+ //# sourceMappingURL=chunk-3O42FYT3.js.map