@ixo/editor 7.4.0 → 7.5.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 (319) hide show
  1. package/dist/{BidConfig-KNA5F754.js → BidConfig-7OPADSLJ.js} +10 -10
  2. package/dist/{BidFlowDetail-35VAQFG5.js → BidFlowDetail-CLGN6RFS.js} +15 -15
  3. package/dist/{CalendarEventCreateConfig-YAL6TVL4.js → CalendarEventCreateConfig-HFHRPWXW.js} +11 -11
  4. package/dist/{CalendarEventCreateFlowDetail-SAX5W3YK.js → CalendarEventCreateFlowDetail-ZXPHYLF4.js} +12 -12
  5. package/dist/{CalendarEventListConfig-DCTNJGDY.js → CalendarEventListConfig-LYPXEDYO.js} +11 -11
  6. package/dist/{CalendarEventListFlowDetail-UY2AZ6RC.js → CalendarEventListFlowDetail-3P5I6NWJ.js} +5 -5
  7. package/dist/{CalendarEventUpdateConfig-WKXJD2HV.js → CalendarEventUpdateConfig-FZNZRRCQ.js} +11 -11
  8. package/dist/{CalendarEventUpdateFlowDetail-7WBBCKLF.js → CalendarEventUpdateFlowDetail-SBODZKHB.js} +12 -12
  9. package/dist/{ClaimConfig-FFODSFKZ.js → ClaimConfig-T7KRYXOU.js} +13 -13
  10. package/dist/{ClaimFlowDetail-KYQN7T3O.js → ClaimFlowDetail-DI27NHDH.js} +15 -15
  11. package/dist/{CollectionLifecycleConfig-QB6IPNQH.js → CollectionLifecycleConfig-SLU7TWJI.js} +4 -4
  12. package/dist/{CollectionLifecycleFlowDetail-IS67MULY.js → CollectionLifecycleFlowDetail-NHMR566C.js} +14 -14
  13. package/dist/{CollectionUsersConfig-PKS552AQ.js → CollectionUsersConfig-XUIJ6DSW.js} +10 -10
  14. package/dist/{CollectionUsersFlowDetail-E26KNRRR.js → CollectionUsersFlowDetail-IM3YWT6E.js} +16 -16
  15. package/dist/{CredentialStoreConfig-HTO27S4R.js → CredentialStoreConfig-KAST7NSD.js} +8 -8
  16. package/dist/{CredentialStoreFlowDetail-JWHL2EWV.js → CredentialStoreFlowDetail-FKIAQZJ7.js} +7 -7
  17. package/dist/{DesignPodFlowDetail-OTK2MILV.js → DesignPodFlowDetail-UXGGFJRH.js} +5 -5
  18. package/dist/{DomainCardPreviewFlowDetail-HTMQUADZ.js → DomainCardPreviewFlowDetail-IT2OJF46.js} +7 -7
  19. package/dist/{DomainIndexerLookupFlowDetail-OVE2U2SJ.js → DomainIndexerLookupFlowDetail-Y7JRRKD5.js} +5 -5
  20. package/dist/{DomainSignFlowDetail-RGX4ZLLZ.js → DomainSignFlowDetail-T5PZHM6M.js} +8 -8
  21. package/dist/{DomainSingleSelectionConfig-TW5CQXD5.js → DomainSingleSelectionConfig-H7RSNYC2.js} +4 -4
  22. package/dist/{DomainSingleSelectionFlowDetail-LATPKYGI.js → DomainSingleSelectionFlowDetail-JHSD5G3A.js} +5 -5
  23. package/dist/{EmailSendConfig-WK3N3Y5H.js → EmailSendConfig-6RJNKNVV.js} +10 -10
  24. package/dist/{EntityCreateOracleFlowDetail-BX3663I6.js → EntityCreateOracleFlowDetail-LZPSS3GS.js} +7 -7
  25. package/dist/{EntitySingleSelectionFlowDetail-44E7FIAF.js → EntitySingleSelectionFlowDetail-HMCMVXKR.js} +5 -5
  26. package/dist/{EntityTransferFlowDetail-UED7MVTT.js → EntityTransferFlowDetail-RSFDF5PB.js} +7 -7
  27. package/dist/{EvalEngineConfig-OLHCNPSF.js → EvalEngineConfig-7JSFDMQR.js} +16 -14
  28. package/dist/{EvalEngineConfig-OLHCNPSF.js.map → EvalEngineConfig-7JSFDMQR.js.map} +1 -1
  29. package/dist/{EvalEngineFlowDetail-VJPJH2PZ.js → EvalEngineFlowDetail-OAM3AGN2.js} +15 -13
  30. package/dist/{EvalEngineFlowDetail-VJPJH2PZ.js.map → EvalEngineFlowDetail-OAM3AGN2.js.map} +1 -1
  31. package/dist/{EvaluateBidConfig-QQTV3JMC.js → EvaluateBidConfig-WYWY3SSW.js} +10 -10
  32. package/dist/{EvaluateBidFlowDetail-TNLDTBJ4.js → EvaluateBidFlowDetail-QMSIAFG5.js} +14 -14
  33. package/dist/{EvaluateClaimConfig-Q56H4TIK.js → EvaluateClaimConfig-FMGZ3UG7.js} +10 -10
  34. package/dist/{EvaluateClaimFlowDetail-J3K2FXHT.js → EvaluateClaimFlowDetail-AL6AL5FV.js} +760 -275
  35. package/dist/EvaluateClaimFlowDetail-AL6AL5FV.js.map +1 -0
  36. package/dist/{FormSubmitFlowDetail-EWCK6AFO.js → FormSubmitFlowDetail-ICG3GSOA.js} +59 -10
  37. package/dist/FormSubmitFlowDetail-ICG3GSOA.js.map +1 -0
  38. package/dist/{GovernanceAuthzExecFlowDetail-C7SVYIHL.js → GovernanceAuthzExecFlowDetail-IW76KM4Q.js} +8 -8
  39. package/dist/{GovernanceAuthzGrantFlowDetail-D6ULSNL4.js → GovernanceAuthzGrantFlowDetail-BTCMC2ZN.js} +9 -9
  40. package/dist/{GovernanceAuthzRevokeFlowDetail-FVZZOOVR.js → GovernanceAuthzRevokeFlowDetail-7DVXQWXC.js} +9 -9
  41. package/dist/{GovernanceChainVoteFlowDetail-LPUYSQJI.js → GovernanceChainVoteFlowDetail-CIBRJPP6.js} +8 -8
  42. package/dist/{GovernanceConfigFlowDetail-WV5UCYWW.js → GovernanceConfigFlowDetail-6P7GLUT4.js} +5 -5
  43. package/dist/{GovernanceContractExecuteFlowDetail-N3IX6ZUE.js → GovernanceContractExecuteFlowDetail-4Q32MNXQ.js} +9 -9
  44. package/dist/{GovernanceContractInstantiateFlowDetail-PEG3YS3J.js → GovernanceContractInstantiateFlowDetail-GOFRJNS6.js} +9 -9
  45. package/dist/{GovernanceContractManageCw20FlowDetail-PGJLC6HG.js → GovernanceContractManageCw20FlowDetail-QYFC2CBY.js} +8 -8
  46. package/dist/{GovernanceContractMigrateFlowDetail-WAATSI24.js → GovernanceContractMigrateFlowDetail-YS575HJK.js} +9 -9
  47. package/dist/{GovernanceContractUpdateAdminFlowDetail-FX2MQO3P.js → GovernanceContractUpdateAdminFlowDetail-YNN5VVUN.js} +8 -8
  48. package/dist/{GovernanceCustomMessageFlowDetail-RKZIPQBE.js → GovernanceCustomMessageFlowDetail-AP2DYHPG.js} +9 -9
  49. package/dist/{GovernanceDaoAcceptToMarketplaceFlowDetail-GS4K573O.js → GovernanceDaoAcceptToMarketplaceFlowDetail-WHC2GXB7.js} +9 -9
  50. package/dist/{GovernanceDaoAdminExecFlowDetail-5GAJ677O.js → GovernanceDaoAdminExecFlowDetail-5545VOCJ.js} +10 -10
  51. package/dist/{GovernanceDaoCreateEntityFlowDetail-YQBK5ZJ6.js → GovernanceDaoCreateEntityFlowDetail-QKSNQHT3.js} +9 -9
  52. package/dist/{GovernanceDaoJoinFlowDetail-TUWWA76P.js → GovernanceDaoJoinFlowDetail-ZIZA4CHJ.js} +9 -9
  53. package/dist/{GovernanceDaoManageStorageFlowDetail-ZABNXYGW.js → GovernanceDaoManageStorageFlowDetail-V7CNBFD5.js} +8 -8
  54. package/dist/{GovernanceDaoManageSubDaosFlowDetail-JUZOW3NX.js → GovernanceDaoManageSubDaosFlowDetail-U6HCZEWB.js} +9 -9
  55. package/dist/{GovernanceDaoUpdateInfoFlowDetail-GTPZETSW.js → GovernanceDaoUpdateInfoFlowDetail-YGVZWXYR.js} +8 -8
  56. package/dist/{GovernanceMemberProposalConfig-MYHHSBWL.js → GovernanceMemberProposalConfig-3HKKBDJ5.js} +5 -5
  57. package/dist/{GovernanceMemberProposalFlowDetail-NYKIPRXZ.js → GovernanceMemberProposalFlowDetail-5DYOTEMZ.js} +9 -9
  58. package/dist/{GovernanceNftBurnFlowDetail-V5YEWTZZ.js → GovernanceNftBurnFlowDetail-ZHL6NSBB.js} +8 -8
  59. package/dist/{GovernanceNftManageCollectionsFlowDetail-NV5IQJQY.js → GovernanceNftManageCollectionsFlowDetail-YKWXV6PI.js} +8 -8
  60. package/dist/{GovernanceNftTransferFlowDetail-MT4A3IPX.js → GovernanceNftTransferFlowDetail-SQ5ZSKIK.js} +9 -9
  61. package/dist/{GovernanceSettingsProposalConfig-U7SO63AZ.js → GovernanceSettingsProposalConfig-IZFFFRHS.js} +5 -5
  62. package/dist/{GovernanceSettingsProposalFlowDetail-A6HNAOCP.js → GovernanceSettingsProposalFlowDetail-72OGJWPM.js} +8 -8
  63. package/dist/{GovernanceStakingStakeFlowDetail-ANPDO5CW.js → GovernanceStakingStakeFlowDetail-TQT6JVX5.js} +8 -8
  64. package/dist/{GovernanceStakingStakeToGroupFlowDetail-3EXFBNXM.js → GovernanceStakingStakeToGroupFlowDetail-RHW3KT4J.js} +8 -8
  65. package/dist/{GovernanceSubmissionConfigProposalFlowDetail-W7J6W3CX.js → GovernanceSubmissionConfigProposalFlowDetail-ELSE6QV6.js} +8 -8
  66. package/dist/{GovernanceTransactionMintFlowDetail-H5T5SHDW.js → GovernanceTransactionMintFlowDetail-3I7F3FSC.js} +9 -9
  67. package/dist/{GovernanceTransactionPerformTokenSwapFlowDetail-T7QTOJEJ.js → GovernanceTransactionPerformTokenSwapFlowDetail-5UTYTE3P.js} +8 -8
  68. package/dist/{GovernanceTransactionSendFundsConfig-7GWFZYBO.js → GovernanceTransactionSendFundsConfig-UITDQIEX.js} +5 -5
  69. package/dist/{GovernanceTransactionSendFundsFlowDetail-SSGQKOYI.js → GovernanceTransactionSendFundsFlowDetail-FUHTFFYK.js} +9 -9
  70. package/dist/{GovernanceTransactionSendGroupTokenFlowDetail-YKWCSXQO.js → GovernanceTransactionSendGroupTokenFlowDetail-JEGHRGVA.js} +9 -9
  71. package/dist/{GovernanceTransactionWithdrawTokenSwapFlowDetail-Y44MBQSJ.js → GovernanceTransactionWithdrawTokenSwapFlowDetail-IGKD3XFX.js} +8 -8
  72. package/dist/{GovernanceValidatorActionsFlowDetail-KVPO7XYV.js → GovernanceValidatorActionsFlowDetail-XFJM4T54.js} +8 -8
  73. package/dist/{HarvestConfig-WMHB3Z4M.js → HarvestConfig-MQCRQM6E.js} +9 -9
  74. package/dist/{HarvestFlowDetail-2E6FAG5D.js → HarvestFlowDetail-4AGZTR7Z.js} +7 -7
  75. package/dist/{HttpRequestConfig-MSVW46CZ.js → HttpRequestConfig-24VT44SK.js} +8 -8
  76. package/dist/{HttpRequestFlowDetail-AHYCCC7Z.js → HttpRequestFlowDetail-LGWILJCS.js} +5 -5
  77. package/dist/{IdentityCreateFlowDetail-KKQP5H6J.js → IdentityCreateFlowDetail-6UVA3GLT.js} +13 -13
  78. package/dist/{IidCreateFlowDetail-HZ3IBACZ.js → IidCreateFlowDetail-6DMLKXSP.js} +13 -13
  79. package/dist/{KycVerifyConfig-MRFKB3RS.js → KycVerifyConfig-QKU3GYXH.js} +8 -8
  80. package/dist/{KycVerifyFlowDetail-UL4YW23S.js → KycVerifyFlowDetail-MJB5DFB5.js} +13 -13
  81. package/dist/{ListDomainFlowsFlowDetail-NBTEXXR6.js → ListDomainFlowsFlowDetail-PDUSV2TD.js} +5 -5
  82. package/dist/{LoadBatchesFlowDetail-6B6EUQUU.js → LoadBatchesFlowDetail-SXLSDRVT.js} +7 -7
  83. package/dist/{MatrixDmConfig-VCECTS77.js → MatrixDmConfig-XCS2HCGZ.js} +4 -4
  84. package/dist/{MatrixRegisterFlowDetail-Q5GRDCJ3.js → MatrixRegisterFlowDetail-7JMBMOTF.js} +7 -7
  85. package/dist/{MemberMultiSelectFlowDetail-EOJ6UIUT.js → MemberMultiSelectFlowDetail-DLAKXCRC.js} +5 -5
  86. package/dist/{OracleConfig-QR62IIUE.js → OracleConfig-RU6N4JBF.js} +8 -8
  87. package/dist/{OracleConfigureOracleFlowDetail-WJM6LIC2.js → OracleConfigureOracleFlowDetail-AET56AV6.js} +13 -13
  88. package/dist/{OracleContractFlowDetail-LQEGQ6CN.js → OracleContractFlowDetail-4RWSGCLI.js} +7 -7
  89. package/dist/{OracleDeployFlowDetail-KUPXAFG2.js → OracleDeployFlowDetail-2HOKGJEO.js} +7 -7
  90. package/dist/{OracleDeploySetupFlowDetail-MKWUVJWU.js → OracleDeploySetupFlowDetail-AOUCBEJK.js} +7 -7
  91. package/dist/{OracleDeployStartFlowDetail-XUKADF5E.js → OracleDeployStartFlowDetail-5R5O54VE.js} +7 -7
  92. package/dist/{OracleFlowDetail-ZB4BXPMP.js → OracleFlowDetail-REP3CDHK.js} +7 -7
  93. package/dist/{OraclePromptFlowDetail-BJCIRJC7.js → OraclePromptFlowDetail-RWGI7Y46.js} +7 -7
  94. package/dist/{OracleStoreConfigFlowDetail-PUDZJ6XK.js → OracleStoreConfigFlowDetail-F2E4ZEVA.js} +7 -7
  95. package/dist/{OracleStoreSecretsAndConfigFlowDetail-WWJ5EE65.js → OracleStoreSecretsAndConfigFlowDetail-6X4CPXKW.js} +13 -13
  96. package/dist/{OracleStoreSecretsFlowDetail-74KT4D5R.js → OracleStoreSecretsFlowDetail-DYPIPYIT.js} +13 -13
  97. package/dist/{ProposalCreateConfig-UKWLNGGT.js → ProposalCreateConfig-DRYE2AKJ.js} +10 -10
  98. package/dist/{ProposalCreateFlowDetail-HTA7MM6V.js → ProposalCreateFlowDetail-CHIA2XWY.js} +14 -14
  99. package/dist/{ProposalVoteConfig-GQ2EFLLM.js → ProposalVoteConfig-7UNWFROZ.js} +10 -10
  100. package/dist/{ProposalVoteFlowDetail-WXYSRQVM.js → ProposalVoteFlowDetail-DSMBVP3E.js} +8 -8
  101. package/dist/{ProtocolSelectFlowDetail-M533L2VH.js → ProtocolSelectFlowDetail-NTLOLTSO.js} +4 -4
  102. package/dist/{RetireConfig-TTS4O56B.js → RetireConfig-BF2DX5IS.js} +9 -9
  103. package/dist/{RetireFlowDetail-5MPYK3Y4.js → RetireFlowDetail-LY77O4VE.js} +7 -7
  104. package/dist/{SandboxProvisionFlowDetail-RQV3OVSV.js → SandboxProvisionFlowDetail-QPRFK7N3.js} +7 -7
  105. package/dist/{WalletFundConfig-32GHDUYC.js → WalletFundConfig-QF2D65SA.js} +5 -5
  106. package/dist/{WalletFundFlowDetail-BVSKFSCJ.js → WalletFundFlowDetail-CTWM57AK.js} +8 -8
  107. package/dist/{WalletGenerateAndFundFlowDetail-MLULHQ2V.js → WalletGenerateAndFundFlowDetail-TY3HOGEU.js} +5 -5
  108. package/dist/{WalletGenerateFlowDetail-EHYFCON2.js → WalletGenerateFlowDetail-F5LNH4VY.js} +5 -5
  109. package/dist/{XeroContactCreateConfig-F46RAJZ3.js → XeroContactCreateConfig-GTRMV4MO.js} +11 -11
  110. package/dist/{XeroContactCreateFlowDetail-BXZPZRN6.js → XeroContactCreateFlowDetail-4IFZRJOF.js} +12 -12
  111. package/dist/{XeroInvoiceCreateConfig-3C57CRA5.js → XeroInvoiceCreateConfig-HVMMNUU4.js} +11 -11
  112. package/dist/{XeroInvoiceCreateFlowDetail-TB5ILGFK.js → XeroInvoiceCreateFlowDetail-4UPL55DU.js} +14 -14
  113. package/dist/{XeroInvoiceListConfig-NJL2XCJU.js → XeroInvoiceListConfig-IMXZZTNF.js} +11 -11
  114. package/dist/{XeroInvoiceListFlowDetail-SW77EBQJ.js → XeroInvoiceListFlowDetail-SUWMEU7K.js} +5 -5
  115. package/dist/{XeroPaymentCreateConfig-36RZJ572.js → XeroPaymentCreateConfig-ONPADVHN.js} +8 -8
  116. package/dist/{XeroPaymentCreateFlowDetail-ASEL73SM.js → XeroPaymentCreateFlowDetail-52FOC77L.js} +13 -13
  117. package/dist/action-manifest.json +489 -5
  118. package/dist/{chunk-TWPAZA5U.js → chunk-3S6HH3LV.js} +2 -2
  119. package/dist/{chunk-3ZY7LBMV.js → chunk-5JEXVSJG.js} +11 -129
  120. package/dist/chunk-5JEXVSJG.js.map +1 -0
  121. package/dist/chunk-5WYFQEOS.js +49 -0
  122. package/dist/chunk-5WYFQEOS.js.map +1 -0
  123. package/dist/{chunk-BLXL5LNU.js → chunk-6332CJVF.js} +2 -2
  124. package/dist/{chunk-YICU2BTW.js → chunk-66EWPWA5.js} +2 -2
  125. package/dist/{chunk-V2K5S3GW.js → chunk-66XW6TQT.js} +580 -8
  126. package/dist/chunk-66XW6TQT.js.map +1 -0
  127. package/dist/{chunk-YSKMW5N4.js → chunk-6OBTZWYM.js} +3 -3
  128. package/dist/{chunk-4SNJX2WR.js → chunk-7XB6INJ4.js} +2 -2
  129. package/dist/{chunk-FVRGJE6M.js → chunk-ALJO4A2R.js} +2984 -860
  130. package/dist/chunk-ALJO4A2R.js.map +1 -0
  131. package/dist/{chunk-QSUE3ZFB.js → chunk-AZGVSR3T.js} +2 -2
  132. package/dist/{chunk-AAUAZ4YK.js → chunk-DMWXSWLO.js} +2 -2
  133. package/dist/{chunk-SCLMJ7FE.js → chunk-FYPDR7DJ.js} +2010 -1891
  134. package/dist/chunk-FYPDR7DJ.js.map +1 -0
  135. package/dist/{chunk-C376YPPE.js → chunk-HPHWYDGB.js} +3 -3
  136. package/dist/{chunk-JWC4VVY7.js → chunk-JCI46234.js} +2 -2
  137. package/dist/{chunk-ZWBVAYXF.js → chunk-KIAAAFZF.js} +2 -2
  138. package/dist/{chunk-D3OHPJQD.js → chunk-KSITH7AN.js} +3 -3
  139. package/dist/chunk-KSITH7AN.js.map +1 -0
  140. package/dist/{chunk-MY22PTP4.js → chunk-LMQT3VUE.js} +2 -2
  141. package/dist/{chunk-VVXNHTWA.js → chunk-M5ELO3A5.js} +2 -2
  142. package/dist/{chunk-RETGBEFM.js → chunk-M7XUQCKC.js} +2 -2
  143. package/dist/{chunk-F6BSA345.js → chunk-MDCOAGIF.js} +10 -7
  144. package/dist/chunk-MDCOAGIF.js.map +1 -0
  145. package/dist/{chunk-W2GRWAXP.js → chunk-MFUWKWMA.js} +2 -2
  146. package/dist/{chunk-I3BKKGB6.js → chunk-P365VW4X.js} +2 -2
  147. package/dist/{chunk-TOHRTMHF.js → chunk-PCRDF4BQ.js} +2 -2
  148. package/dist/{chunk-W6Z3HNIC.js → chunk-PNS4Y2PQ.js} +2 -2
  149. package/dist/{chunk-WKZQA4KR.js → chunk-PWPTKUNE.js} +2 -2
  150. package/dist/{chunk-EAMEGHQZ.js → chunk-SAOQXHK6.js} +2 -2
  151. package/dist/{chunk-MCKX6WIM.js → chunk-SI2AUBY5.js} +4 -4
  152. package/dist/{chunk-CMG6TZKH.js → chunk-TGRBWL3B.js} +3 -3
  153. package/dist/{chunk-EVCXBPHP.js → chunk-TGTS2R2O.js} +5 -5
  154. package/dist/{chunk-JK6RAKE3.js → chunk-UOYPASUI.js} +2 -2
  155. package/dist/{chunk-KRWN6IDZ.js → chunk-VD4HSZSN.js} +2 -2
  156. package/dist/{chunk-O365JU7B.js → chunk-VOBXFJLM.js} +2 -2
  157. package/dist/{chunk-M3GHFF5N.js → chunk-X5BU6FRG.js} +3 -47
  158. package/dist/chunk-X5BU6FRG.js.map +1 -0
  159. package/dist/{chunk-QW7LA67J.js → chunk-X5W725D3.js} +11 -4
  160. package/dist/chunk-X5W725D3.js.map +1 -0
  161. package/dist/{chunk-RRLKIT5M.js → chunk-XUJPJRLW.js} +2 -2
  162. package/dist/{connections-Dm0-mxre.d.ts → connections-Dx7agyTM.d.ts} +1 -1
  163. package/dist/core/index.cjs +581 -15
  164. package/dist/core/index.cjs.map +1 -1
  165. package/dist/core/index.d.ts +6 -4
  166. package/dist/core/index.js +12 -12
  167. package/dist/{graphql-client-VK7-KGDc.d.ts → graphql-client-VfvdQc02.d.ts} +1 -1
  168. package/dist/index.d.ts +3 -3
  169. package/dist/index.js +23 -21
  170. package/dist/index.js.map +1 -1
  171. package/dist/mantine/index.d.ts +3 -3
  172. package/dist/mantine/index.js +22 -20
  173. package/dist/mantine/index.js.map +1 -1
  174. package/dist/{types-CYtPUWc7.d.ts → types-BjlQ_0i3.d.ts} +590 -0
  175. package/package.json +1 -1
  176. package/dist/EvaluateClaimFlowDetail-J3K2FXHT.js.map +0 -1
  177. package/dist/FormSubmitFlowDetail-EWCK6AFO.js.map +0 -1
  178. package/dist/chunk-3ZY7LBMV.js.map +0 -1
  179. package/dist/chunk-D3OHPJQD.js.map +0 -1
  180. package/dist/chunk-F6BSA345.js.map +0 -1
  181. package/dist/chunk-FVRGJE6M.js.map +0 -1
  182. package/dist/chunk-M3GHFF5N.js.map +0 -1
  183. package/dist/chunk-QW7LA67J.js.map +0 -1
  184. package/dist/chunk-SCLMJ7FE.js.map +0 -1
  185. package/dist/chunk-V2K5S3GW.js.map +0 -1
  186. /package/dist/{BidConfig-KNA5F754.js.map → BidConfig-7OPADSLJ.js.map} +0 -0
  187. /package/dist/{BidFlowDetail-35VAQFG5.js.map → BidFlowDetail-CLGN6RFS.js.map} +0 -0
  188. /package/dist/{CalendarEventCreateConfig-YAL6TVL4.js.map → CalendarEventCreateConfig-HFHRPWXW.js.map} +0 -0
  189. /package/dist/{CalendarEventCreateFlowDetail-SAX5W3YK.js.map → CalendarEventCreateFlowDetail-ZXPHYLF4.js.map} +0 -0
  190. /package/dist/{CalendarEventListConfig-DCTNJGDY.js.map → CalendarEventListConfig-LYPXEDYO.js.map} +0 -0
  191. /package/dist/{CalendarEventListFlowDetail-UY2AZ6RC.js.map → CalendarEventListFlowDetail-3P5I6NWJ.js.map} +0 -0
  192. /package/dist/{CalendarEventUpdateConfig-WKXJD2HV.js.map → CalendarEventUpdateConfig-FZNZRRCQ.js.map} +0 -0
  193. /package/dist/{CalendarEventUpdateFlowDetail-7WBBCKLF.js.map → CalendarEventUpdateFlowDetail-SBODZKHB.js.map} +0 -0
  194. /package/dist/{ClaimConfig-FFODSFKZ.js.map → ClaimConfig-T7KRYXOU.js.map} +0 -0
  195. /package/dist/{ClaimFlowDetail-KYQN7T3O.js.map → ClaimFlowDetail-DI27NHDH.js.map} +0 -0
  196. /package/dist/{CollectionLifecycleConfig-QB6IPNQH.js.map → CollectionLifecycleConfig-SLU7TWJI.js.map} +0 -0
  197. /package/dist/{CollectionLifecycleFlowDetail-IS67MULY.js.map → CollectionLifecycleFlowDetail-NHMR566C.js.map} +0 -0
  198. /package/dist/{CollectionUsersConfig-PKS552AQ.js.map → CollectionUsersConfig-XUIJ6DSW.js.map} +0 -0
  199. /package/dist/{CollectionUsersFlowDetail-E26KNRRR.js.map → CollectionUsersFlowDetail-IM3YWT6E.js.map} +0 -0
  200. /package/dist/{CredentialStoreConfig-HTO27S4R.js.map → CredentialStoreConfig-KAST7NSD.js.map} +0 -0
  201. /package/dist/{CredentialStoreFlowDetail-JWHL2EWV.js.map → CredentialStoreFlowDetail-FKIAQZJ7.js.map} +0 -0
  202. /package/dist/{DesignPodFlowDetail-OTK2MILV.js.map → DesignPodFlowDetail-UXGGFJRH.js.map} +0 -0
  203. /package/dist/{DomainCardPreviewFlowDetail-HTMQUADZ.js.map → DomainCardPreviewFlowDetail-IT2OJF46.js.map} +0 -0
  204. /package/dist/{DomainIndexerLookupFlowDetail-OVE2U2SJ.js.map → DomainIndexerLookupFlowDetail-Y7JRRKD5.js.map} +0 -0
  205. /package/dist/{DomainSignFlowDetail-RGX4ZLLZ.js.map → DomainSignFlowDetail-T5PZHM6M.js.map} +0 -0
  206. /package/dist/{DomainSingleSelectionConfig-TW5CQXD5.js.map → DomainSingleSelectionConfig-H7RSNYC2.js.map} +0 -0
  207. /package/dist/{DomainSingleSelectionFlowDetail-LATPKYGI.js.map → DomainSingleSelectionFlowDetail-JHSD5G3A.js.map} +0 -0
  208. /package/dist/{EmailSendConfig-WK3N3Y5H.js.map → EmailSendConfig-6RJNKNVV.js.map} +0 -0
  209. /package/dist/{EntityCreateOracleFlowDetail-BX3663I6.js.map → EntityCreateOracleFlowDetail-LZPSS3GS.js.map} +0 -0
  210. /package/dist/{EntitySingleSelectionFlowDetail-44E7FIAF.js.map → EntitySingleSelectionFlowDetail-HMCMVXKR.js.map} +0 -0
  211. /package/dist/{EntityTransferFlowDetail-UED7MVTT.js.map → EntityTransferFlowDetail-RSFDF5PB.js.map} +0 -0
  212. /package/dist/{EvaluateBidConfig-QQTV3JMC.js.map → EvaluateBidConfig-WYWY3SSW.js.map} +0 -0
  213. /package/dist/{EvaluateBidFlowDetail-TNLDTBJ4.js.map → EvaluateBidFlowDetail-QMSIAFG5.js.map} +0 -0
  214. /package/dist/{EvaluateClaimConfig-Q56H4TIK.js.map → EvaluateClaimConfig-FMGZ3UG7.js.map} +0 -0
  215. /package/dist/{GovernanceAuthzExecFlowDetail-C7SVYIHL.js.map → GovernanceAuthzExecFlowDetail-IW76KM4Q.js.map} +0 -0
  216. /package/dist/{GovernanceAuthzGrantFlowDetail-D6ULSNL4.js.map → GovernanceAuthzGrantFlowDetail-BTCMC2ZN.js.map} +0 -0
  217. /package/dist/{GovernanceAuthzRevokeFlowDetail-FVZZOOVR.js.map → GovernanceAuthzRevokeFlowDetail-7DVXQWXC.js.map} +0 -0
  218. /package/dist/{GovernanceChainVoteFlowDetail-LPUYSQJI.js.map → GovernanceChainVoteFlowDetail-CIBRJPP6.js.map} +0 -0
  219. /package/dist/{GovernanceConfigFlowDetail-WV5UCYWW.js.map → GovernanceConfigFlowDetail-6P7GLUT4.js.map} +0 -0
  220. /package/dist/{GovernanceContractExecuteFlowDetail-N3IX6ZUE.js.map → GovernanceContractExecuteFlowDetail-4Q32MNXQ.js.map} +0 -0
  221. /package/dist/{GovernanceContractInstantiateFlowDetail-PEG3YS3J.js.map → GovernanceContractInstantiateFlowDetail-GOFRJNS6.js.map} +0 -0
  222. /package/dist/{GovernanceContractManageCw20FlowDetail-PGJLC6HG.js.map → GovernanceContractManageCw20FlowDetail-QYFC2CBY.js.map} +0 -0
  223. /package/dist/{GovernanceContractMigrateFlowDetail-WAATSI24.js.map → GovernanceContractMigrateFlowDetail-YS575HJK.js.map} +0 -0
  224. /package/dist/{GovernanceContractUpdateAdminFlowDetail-FX2MQO3P.js.map → GovernanceContractUpdateAdminFlowDetail-YNN5VVUN.js.map} +0 -0
  225. /package/dist/{GovernanceCustomMessageFlowDetail-RKZIPQBE.js.map → GovernanceCustomMessageFlowDetail-AP2DYHPG.js.map} +0 -0
  226. /package/dist/{GovernanceDaoAcceptToMarketplaceFlowDetail-GS4K573O.js.map → GovernanceDaoAcceptToMarketplaceFlowDetail-WHC2GXB7.js.map} +0 -0
  227. /package/dist/{GovernanceDaoAdminExecFlowDetail-5GAJ677O.js.map → GovernanceDaoAdminExecFlowDetail-5545VOCJ.js.map} +0 -0
  228. /package/dist/{GovernanceDaoCreateEntityFlowDetail-YQBK5ZJ6.js.map → GovernanceDaoCreateEntityFlowDetail-QKSNQHT3.js.map} +0 -0
  229. /package/dist/{GovernanceDaoJoinFlowDetail-TUWWA76P.js.map → GovernanceDaoJoinFlowDetail-ZIZA4CHJ.js.map} +0 -0
  230. /package/dist/{GovernanceDaoManageStorageFlowDetail-ZABNXYGW.js.map → GovernanceDaoManageStorageFlowDetail-V7CNBFD5.js.map} +0 -0
  231. /package/dist/{GovernanceDaoManageSubDaosFlowDetail-JUZOW3NX.js.map → GovernanceDaoManageSubDaosFlowDetail-U6HCZEWB.js.map} +0 -0
  232. /package/dist/{GovernanceDaoUpdateInfoFlowDetail-GTPZETSW.js.map → GovernanceDaoUpdateInfoFlowDetail-YGVZWXYR.js.map} +0 -0
  233. /package/dist/{GovernanceMemberProposalConfig-MYHHSBWL.js.map → GovernanceMemberProposalConfig-3HKKBDJ5.js.map} +0 -0
  234. /package/dist/{GovernanceMemberProposalFlowDetail-NYKIPRXZ.js.map → GovernanceMemberProposalFlowDetail-5DYOTEMZ.js.map} +0 -0
  235. /package/dist/{GovernanceNftBurnFlowDetail-V5YEWTZZ.js.map → GovernanceNftBurnFlowDetail-ZHL6NSBB.js.map} +0 -0
  236. /package/dist/{GovernanceNftManageCollectionsFlowDetail-NV5IQJQY.js.map → GovernanceNftManageCollectionsFlowDetail-YKWXV6PI.js.map} +0 -0
  237. /package/dist/{GovernanceNftTransferFlowDetail-MT4A3IPX.js.map → GovernanceNftTransferFlowDetail-SQ5ZSKIK.js.map} +0 -0
  238. /package/dist/{GovernanceSettingsProposalConfig-U7SO63AZ.js.map → GovernanceSettingsProposalConfig-IZFFFRHS.js.map} +0 -0
  239. /package/dist/{GovernanceSettingsProposalFlowDetail-A6HNAOCP.js.map → GovernanceSettingsProposalFlowDetail-72OGJWPM.js.map} +0 -0
  240. /package/dist/{GovernanceStakingStakeFlowDetail-ANPDO5CW.js.map → GovernanceStakingStakeFlowDetail-TQT6JVX5.js.map} +0 -0
  241. /package/dist/{GovernanceStakingStakeToGroupFlowDetail-3EXFBNXM.js.map → GovernanceStakingStakeToGroupFlowDetail-RHW3KT4J.js.map} +0 -0
  242. /package/dist/{GovernanceSubmissionConfigProposalFlowDetail-W7J6W3CX.js.map → GovernanceSubmissionConfigProposalFlowDetail-ELSE6QV6.js.map} +0 -0
  243. /package/dist/{GovernanceTransactionMintFlowDetail-H5T5SHDW.js.map → GovernanceTransactionMintFlowDetail-3I7F3FSC.js.map} +0 -0
  244. /package/dist/{GovernanceTransactionPerformTokenSwapFlowDetail-T7QTOJEJ.js.map → GovernanceTransactionPerformTokenSwapFlowDetail-5UTYTE3P.js.map} +0 -0
  245. /package/dist/{GovernanceTransactionSendFundsConfig-7GWFZYBO.js.map → GovernanceTransactionSendFundsConfig-UITDQIEX.js.map} +0 -0
  246. /package/dist/{GovernanceTransactionSendFundsFlowDetail-SSGQKOYI.js.map → GovernanceTransactionSendFundsFlowDetail-FUHTFFYK.js.map} +0 -0
  247. /package/dist/{GovernanceTransactionSendGroupTokenFlowDetail-YKWCSXQO.js.map → GovernanceTransactionSendGroupTokenFlowDetail-JEGHRGVA.js.map} +0 -0
  248. /package/dist/{GovernanceTransactionWithdrawTokenSwapFlowDetail-Y44MBQSJ.js.map → GovernanceTransactionWithdrawTokenSwapFlowDetail-IGKD3XFX.js.map} +0 -0
  249. /package/dist/{GovernanceValidatorActionsFlowDetail-KVPO7XYV.js.map → GovernanceValidatorActionsFlowDetail-XFJM4T54.js.map} +0 -0
  250. /package/dist/{HarvestConfig-WMHB3Z4M.js.map → HarvestConfig-MQCRQM6E.js.map} +0 -0
  251. /package/dist/{HarvestFlowDetail-2E6FAG5D.js.map → HarvestFlowDetail-4AGZTR7Z.js.map} +0 -0
  252. /package/dist/{HttpRequestConfig-MSVW46CZ.js.map → HttpRequestConfig-24VT44SK.js.map} +0 -0
  253. /package/dist/{HttpRequestFlowDetail-AHYCCC7Z.js.map → HttpRequestFlowDetail-LGWILJCS.js.map} +0 -0
  254. /package/dist/{IdentityCreateFlowDetail-KKQP5H6J.js.map → IdentityCreateFlowDetail-6UVA3GLT.js.map} +0 -0
  255. /package/dist/{IidCreateFlowDetail-HZ3IBACZ.js.map → IidCreateFlowDetail-6DMLKXSP.js.map} +0 -0
  256. /package/dist/{KycVerifyConfig-MRFKB3RS.js.map → KycVerifyConfig-QKU3GYXH.js.map} +0 -0
  257. /package/dist/{KycVerifyFlowDetail-UL4YW23S.js.map → KycVerifyFlowDetail-MJB5DFB5.js.map} +0 -0
  258. /package/dist/{ListDomainFlowsFlowDetail-NBTEXXR6.js.map → ListDomainFlowsFlowDetail-PDUSV2TD.js.map} +0 -0
  259. /package/dist/{LoadBatchesFlowDetail-6B6EUQUU.js.map → LoadBatchesFlowDetail-SXLSDRVT.js.map} +0 -0
  260. /package/dist/{MatrixDmConfig-VCECTS77.js.map → MatrixDmConfig-XCS2HCGZ.js.map} +0 -0
  261. /package/dist/{MatrixRegisterFlowDetail-Q5GRDCJ3.js.map → MatrixRegisterFlowDetail-7JMBMOTF.js.map} +0 -0
  262. /package/dist/{MemberMultiSelectFlowDetail-EOJ6UIUT.js.map → MemberMultiSelectFlowDetail-DLAKXCRC.js.map} +0 -0
  263. /package/dist/{OracleConfig-QR62IIUE.js.map → OracleConfig-RU6N4JBF.js.map} +0 -0
  264. /package/dist/{OracleConfigureOracleFlowDetail-WJM6LIC2.js.map → OracleConfigureOracleFlowDetail-AET56AV6.js.map} +0 -0
  265. /package/dist/{OracleContractFlowDetail-LQEGQ6CN.js.map → OracleContractFlowDetail-4RWSGCLI.js.map} +0 -0
  266. /package/dist/{OracleDeployFlowDetail-KUPXAFG2.js.map → OracleDeployFlowDetail-2HOKGJEO.js.map} +0 -0
  267. /package/dist/{OracleDeploySetupFlowDetail-MKWUVJWU.js.map → OracleDeploySetupFlowDetail-AOUCBEJK.js.map} +0 -0
  268. /package/dist/{OracleDeployStartFlowDetail-XUKADF5E.js.map → OracleDeployStartFlowDetail-5R5O54VE.js.map} +0 -0
  269. /package/dist/{OracleFlowDetail-ZB4BXPMP.js.map → OracleFlowDetail-REP3CDHK.js.map} +0 -0
  270. /package/dist/{OraclePromptFlowDetail-BJCIRJC7.js.map → OraclePromptFlowDetail-RWGI7Y46.js.map} +0 -0
  271. /package/dist/{OracleStoreConfigFlowDetail-PUDZJ6XK.js.map → OracleStoreConfigFlowDetail-F2E4ZEVA.js.map} +0 -0
  272. /package/dist/{OracleStoreSecretsAndConfigFlowDetail-WWJ5EE65.js.map → OracleStoreSecretsAndConfigFlowDetail-6X4CPXKW.js.map} +0 -0
  273. /package/dist/{OracleStoreSecretsFlowDetail-74KT4D5R.js.map → OracleStoreSecretsFlowDetail-DYPIPYIT.js.map} +0 -0
  274. /package/dist/{ProposalCreateConfig-UKWLNGGT.js.map → ProposalCreateConfig-DRYE2AKJ.js.map} +0 -0
  275. /package/dist/{ProposalCreateFlowDetail-HTA7MM6V.js.map → ProposalCreateFlowDetail-CHIA2XWY.js.map} +0 -0
  276. /package/dist/{ProposalVoteConfig-GQ2EFLLM.js.map → ProposalVoteConfig-7UNWFROZ.js.map} +0 -0
  277. /package/dist/{ProposalVoteFlowDetail-WXYSRQVM.js.map → ProposalVoteFlowDetail-DSMBVP3E.js.map} +0 -0
  278. /package/dist/{ProtocolSelectFlowDetail-M533L2VH.js.map → ProtocolSelectFlowDetail-NTLOLTSO.js.map} +0 -0
  279. /package/dist/{RetireConfig-TTS4O56B.js.map → RetireConfig-BF2DX5IS.js.map} +0 -0
  280. /package/dist/{RetireFlowDetail-5MPYK3Y4.js.map → RetireFlowDetail-LY77O4VE.js.map} +0 -0
  281. /package/dist/{SandboxProvisionFlowDetail-RQV3OVSV.js.map → SandboxProvisionFlowDetail-QPRFK7N3.js.map} +0 -0
  282. /package/dist/{WalletFundConfig-32GHDUYC.js.map → WalletFundConfig-QF2D65SA.js.map} +0 -0
  283. /package/dist/{WalletFundFlowDetail-BVSKFSCJ.js.map → WalletFundFlowDetail-CTWM57AK.js.map} +0 -0
  284. /package/dist/{WalletGenerateAndFundFlowDetail-MLULHQ2V.js.map → WalletGenerateAndFundFlowDetail-TY3HOGEU.js.map} +0 -0
  285. /package/dist/{WalletGenerateFlowDetail-EHYFCON2.js.map → WalletGenerateFlowDetail-F5LNH4VY.js.map} +0 -0
  286. /package/dist/{XeroContactCreateConfig-F46RAJZ3.js.map → XeroContactCreateConfig-GTRMV4MO.js.map} +0 -0
  287. /package/dist/{XeroContactCreateFlowDetail-BXZPZRN6.js.map → XeroContactCreateFlowDetail-4IFZRJOF.js.map} +0 -0
  288. /package/dist/{XeroInvoiceCreateConfig-3C57CRA5.js.map → XeroInvoiceCreateConfig-HVMMNUU4.js.map} +0 -0
  289. /package/dist/{XeroInvoiceCreateFlowDetail-TB5ILGFK.js.map → XeroInvoiceCreateFlowDetail-4UPL55DU.js.map} +0 -0
  290. /package/dist/{XeroInvoiceListConfig-NJL2XCJU.js.map → XeroInvoiceListConfig-IMXZZTNF.js.map} +0 -0
  291. /package/dist/{XeroInvoiceListFlowDetail-SW77EBQJ.js.map → XeroInvoiceListFlowDetail-SUWMEU7K.js.map} +0 -0
  292. /package/dist/{XeroPaymentCreateConfig-36RZJ572.js.map → XeroPaymentCreateConfig-ONPADVHN.js.map} +0 -0
  293. /package/dist/{XeroPaymentCreateFlowDetail-ASEL73SM.js.map → XeroPaymentCreateFlowDetail-52FOC77L.js.map} +0 -0
  294. /package/dist/{chunk-TWPAZA5U.js.map → chunk-3S6HH3LV.js.map} +0 -0
  295. /package/dist/{chunk-BLXL5LNU.js.map → chunk-6332CJVF.js.map} +0 -0
  296. /package/dist/{chunk-YICU2BTW.js.map → chunk-66EWPWA5.js.map} +0 -0
  297. /package/dist/{chunk-YSKMW5N4.js.map → chunk-6OBTZWYM.js.map} +0 -0
  298. /package/dist/{chunk-4SNJX2WR.js.map → chunk-7XB6INJ4.js.map} +0 -0
  299. /package/dist/{chunk-QSUE3ZFB.js.map → chunk-AZGVSR3T.js.map} +0 -0
  300. /package/dist/{chunk-AAUAZ4YK.js.map → chunk-DMWXSWLO.js.map} +0 -0
  301. /package/dist/{chunk-C376YPPE.js.map → chunk-HPHWYDGB.js.map} +0 -0
  302. /package/dist/{chunk-JWC4VVY7.js.map → chunk-JCI46234.js.map} +0 -0
  303. /package/dist/{chunk-ZWBVAYXF.js.map → chunk-KIAAAFZF.js.map} +0 -0
  304. /package/dist/{chunk-MY22PTP4.js.map → chunk-LMQT3VUE.js.map} +0 -0
  305. /package/dist/{chunk-VVXNHTWA.js.map → chunk-M5ELO3A5.js.map} +0 -0
  306. /package/dist/{chunk-RETGBEFM.js.map → chunk-M7XUQCKC.js.map} +0 -0
  307. /package/dist/{chunk-W2GRWAXP.js.map → chunk-MFUWKWMA.js.map} +0 -0
  308. /package/dist/{chunk-I3BKKGB6.js.map → chunk-P365VW4X.js.map} +0 -0
  309. /package/dist/{chunk-TOHRTMHF.js.map → chunk-PCRDF4BQ.js.map} +0 -0
  310. /package/dist/{chunk-W6Z3HNIC.js.map → chunk-PNS4Y2PQ.js.map} +0 -0
  311. /package/dist/{chunk-WKZQA4KR.js.map → chunk-PWPTKUNE.js.map} +0 -0
  312. /package/dist/{chunk-EAMEGHQZ.js.map → chunk-SAOQXHK6.js.map} +0 -0
  313. /package/dist/{chunk-MCKX6WIM.js.map → chunk-SI2AUBY5.js.map} +0 -0
  314. /package/dist/{chunk-CMG6TZKH.js.map → chunk-TGRBWL3B.js.map} +0 -0
  315. /package/dist/{chunk-EVCXBPHP.js.map → chunk-TGTS2R2O.js.map} +0 -0
  316. /package/dist/{chunk-JK6RAKE3.js.map → chunk-UOYPASUI.js.map} +0 -0
  317. /package/dist/{chunk-KRWN6IDZ.js.map → chunk-VD4HSZSN.js.map} +0 -0
  318. /package/dist/{chunk-O365JU7B.js.map → chunk-VOBXFJLM.js.map} +0 -0
  319. /package/dist/{chunk-RRLKIT5M.js.map → chunk-XUJPJRLW.js.map} +0 -0
@@ -15,6 +15,7 @@ import {
15
15
  getBlockType,
16
16
  getDueAt,
17
17
  getFlowAgentMaps,
18
+ isActionTypeDone,
18
19
  isRuntimeRef,
19
20
  parseConditionConfigStrict,
20
21
  parseJsonProp,
@@ -23,13 +24,13 @@ import {
23
24
  readPendingInvocations,
24
25
  readQueuedAgentCommands,
25
26
  updateAgentCommand
26
- } from "./chunk-F6BSA345.js";
27
+ } from "./chunk-MDCOAGIF.js";
27
28
  import {
28
29
  boundRunActionOutput,
29
30
  generateActionManifest,
30
31
  readPendingRunTimelineEvents,
31
32
  retryPendingRunTimelineEvents
32
- } from "./chunk-V2K5S3GW.js";
33
+ } from "./chunk-66XW6TQT.js";
33
34
  import {
34
35
  bindFlowOwnerFromRoom,
35
36
  createDesignPodPortalJourneyPlan,
@@ -37,7 +38,7 @@ import {
37
38
  readFlowOwnerDid,
38
39
  readRoomCreatorUserId,
39
40
  seedDesignPodMethodDefinition
40
- } from "./chunk-KRWN6IDZ.js";
41
+ } from "./chunk-VD4HSZSN.js";
41
42
  import {
42
43
  capabilityPatternCoversCan,
43
44
  collectPhantomLegacyRun,
@@ -53,7 +54,7 @@ import {
53
54
  setMultiRunStorage,
54
55
  sha256Digest,
55
56
  writeActionState
56
- } from "./chunk-QW7LA67J.js";
57
+ } from "./chunk-X5W725D3.js";
57
58
  import {
58
59
  isYMapLike,
59
60
  isYXmlElementLike
@@ -71,482 +72,6 @@ function createUcanRunLifecycleAuthorizer(getService) {
71
72
  };
72
73
  }
73
74
 
74
- // src/core/lib/sharedFlowDocument.ts
75
- import { MatrixCRDTEventTranslator, MatrixProvider, MatrixReader } from "@ixo/matrix-crdt";
76
- import { Direction, Filter } from "matrix-js-sdk";
77
- import * as Y from "yjs";
78
-
79
- // src/core/lib/flowDocumentCache.ts
80
- var DATABASE = "ixo-flow-checkpoints-v1";
81
- var MAX_AGE = 7 * 24 * 60 * 60 * 1e3;
82
- async function identity(client, roomId) {
83
- const token = client.getAccessToken?.();
84
- if (!token || !globalThis.crypto?.subtle || typeof indexedDB === "undefined") return;
85
- const scope = JSON.stringify([client.getHomeserverUrl(), client.getUserId(), roomId]);
86
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${scope}\0${token}`));
87
- const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
88
- return { scope, key };
89
- }
90
- async function database() {
91
- return new Promise((resolve, reject) => {
92
- const request = indexedDB.open(DATABASE, 1);
93
- request.onupgradeneeded = () => request.result.createObjectStore("documents");
94
- request.onsuccess = () => resolve(request.result);
95
- request.onerror = () => reject(request.error);
96
- request.onblocked = () => reject(new Error("Flow cache is blocked"));
97
- });
98
- }
99
- async function readFlowCheckpoint(client, roomId) {
100
- try {
101
- const auth = await identity(client, roomId);
102
- if (!auth) return;
103
- const db = await database();
104
- const record = await new Promise((resolve, reject) => {
105
- const transaction = db.transaction("documents", "readonly");
106
- const request = transaction.objectStore("documents").get(auth.scope);
107
- request.onsuccess = () => resolve(request.result);
108
- request.onerror = () => reject(request.error);
109
- transaction.oncomplete = () => db.close();
110
- transaction.onabort = () => db.close();
111
- });
112
- if (!record || Date.now() - record.savedAt > MAX_AGE) return;
113
- const clear = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(auth.scope) }, auth.key, record.data);
114
- const value = JSON.parse(new TextDecoder().decode(clear));
115
- if (!Array.isArray(value.update) || !value.token) return;
116
- return { update: new Uint8Array(value.update), token: value.token, savedAt: record.savedAt };
117
- } catch {
118
- return;
119
- }
120
- }
121
- async function writeFlowCheckpoint(client, roomId, checkpoint) {
122
- try {
123
- if (checkpoint.update.byteLength > 8 * 1024 * 1024) return;
124
- const auth = await identity(client, roomId);
125
- if (!auth) return;
126
- const iv = crypto.getRandomValues(new Uint8Array(12));
127
- const data = await crypto.subtle.encrypt(
128
- { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(auth.scope) },
129
- auth.key,
130
- new TextEncoder().encode(JSON.stringify({ update: Array.from(checkpoint.update), token: checkpoint.token }))
131
- );
132
- const db = await database();
133
- await new Promise((resolve, reject) => {
134
- const transaction = db.transaction("documents", "readwrite");
135
- const store = transaction.objectStore("documents");
136
- store.put({ iv, data, savedAt: checkpoint.savedAt }, auth.scope);
137
- const request = store.openCursor();
138
- const records = [];
139
- request.onsuccess = () => {
140
- const cursor = request.result;
141
- if (!cursor) {
142
- records.sort((a, b) => b.savedAt - a.savedAt);
143
- for (const record of records.slice(32)) store.delete(record.key);
144
- return;
145
- }
146
- if (Date.now() - cursor.value.savedAt > MAX_AGE) cursor.delete();
147
- else records.push({ key: cursor.key, savedAt: cursor.value.savedAt });
148
- cursor.continue();
149
- };
150
- transaction.oncomplete = () => {
151
- db.close();
152
- resolve();
153
- };
154
- transaction.onerror = () => {
155
- db.close();
156
- reject(transaction.error);
157
- };
158
- transaction.onabort = () => {
159
- db.close();
160
- reject(transaction.error);
161
- };
162
- });
163
- } catch {
164
- return;
165
- }
166
- }
167
-
168
- // src/core/lib/sharedFlowDocument.ts
169
- var sessions = /* @__PURE__ */ new WeakMap();
170
- var RETAIN_MS = 5 * 60 * 1e3;
171
- var activeLoads = 0;
172
- var loadQueue = [];
173
- function withLoadSlot(read, visible) {
174
- return new Promise((resolve, reject) => {
175
- const start = () => {
176
- activeLoads++;
177
- void read().then(resolve, reject).finally(() => {
178
- activeLoads--;
179
- loadQueue.sort((a, b) => Number(b.visible) - Number(a.visible));
180
- loadQueue.shift()?.start();
181
- });
182
- };
183
- if (activeLoads < 4) start();
184
- else loadQueue.push({ visible, start });
185
- });
186
- }
187
- function syntheticSnapshot(update) {
188
- let binary = "";
189
- for (const byte of update) binary += String.fromCharCode(byte);
190
- return { type: "matrix-crdt.doc_snapshot", event_id: "$local-checkpoint", sender: "@local:cache", origin_server_ts: 0, content: { update: btoa(binary) } };
191
- }
192
- function clientWithHistory(client, history) {
193
- let first = true;
194
- return new Proxy(client, {
195
- get(target, property) {
196
- if (property === "createMessagesRequest") {
197
- return async (...args) => {
198
- if (first && !args[1] && args[3] === Direction.Backward) {
199
- first = false;
200
- const response = await history();
201
- if (response) return response;
202
- }
203
- return target.createMessagesRequest(args[0], args[1], 200, args[3], args[4]);
204
- };
205
- }
206
- const value = Reflect.get(target, property);
207
- return typeof value === "function" ? value.bind(target) : value;
208
- }
209
- });
210
- }
211
- async function readFlowDocumentHistory(client, roomId, checkpoint) {
212
- const room = client.getRoom(roomId);
213
- if (checkpoint && Date.now() - checkpoint.savedAt > 30 * 60 * 1e3 && room && !room.currentState.getStateEvents("m.room.encryption", "")) checkpoint = void 0;
214
- if (checkpoint) {
215
- try {
216
- Y.decodeUpdate(checkpoint.update);
217
- } catch {
218
- checkpoint = void 0;
219
- }
220
- }
221
- const translator = new MatrixCRDTEventTranslator();
222
- const filter = new Filter(client.getUserId() ?? void 0);
223
- filter.setDefinition({ room: { timeline: { types: [...translator.readEventTypes, "m.room.encrypted"] } } });
224
- const readerClient = clientWithHistory(client, async () => {
225
- let token = checkpoint?.token;
226
- let initial = checkpoint ? [syntheticSnapshot(checkpoint.update)] : [];
227
- let recent;
228
- if (!token) {
229
- const room2 = client.getRoom(roomId);
230
- if (!room2 || room2.currentState.getStateEvents("m.room.encryption", "")) return;
231
- recent = await client.createMessagesRequest(roomId, "", 200, Direction.Backward, filter);
232
- if (!recent.end || recent.end === recent.start || recent.chunk.some((event) => translator.isAnySnapshotEvent(event))) return recent;
233
- const snapshots = new Filter(client.getUserId() ?? void 0);
234
- snapshots.setDefinition({ room: { timeline: { types: ["matrix-crdt.doc_snapshot", "matrix-crdt.doc_snapshot_v2"] } } });
235
- try {
236
- const page = await client.createMessagesRequest(roomId, "", 1, Direction.Backward, snapshots);
237
- if (!page.chunk.length || !page.end) return recent;
238
- token = page.end;
239
- } catch {
240
- return recent;
241
- }
242
- }
243
- try {
244
- for (; ; ) {
245
- const page = await client.createMessagesRequest(roomId, token, 200, Direction.Forward, filter);
246
- initial.push(...page.chunk);
247
- if (!page.end || page.end === token || page.chunk.length === 0) {
248
- return { chunk: initial.reverse(), start: page.end || token, end: void 0 };
249
- }
250
- token = page.end;
251
- }
252
- } catch {
253
- return recent;
254
- }
255
- });
256
- let reader = new MatrixReader(readerClient, roomId, translator);
257
- try {
258
- let events;
259
- try {
260
- events = await reader.getInitialDocumentUpdateEvents();
261
- } catch {
262
- reader.dispose();
263
- reader = new MatrixReader(
264
- clientWithHistory(client, async () => void 0),
265
- roomId,
266
- translator
267
- );
268
- events = await reader.getInitialDocumentUpdateEvents();
269
- }
270
- if (reader.snapshotDegradations.length) {
271
- reader.dispose();
272
- reader = new MatrixReader(
273
- clientWithHistory(client, async () => void 0),
274
- roomId,
275
- translator
276
- );
277
- events = await reader.getInitialDocumentUpdateEvents();
278
- }
279
- const updates = events.map((event) => translator.getUpdateBytes(event)).filter((update) => !!update);
280
- return { update: updates.length ? Y.mergeUpdates(updates) : Y.encodeStateAsUpdate(new Y.Doc()), token: reader.latestToken };
281
- } finally {
282
- reader.dispose();
283
- }
284
- }
285
- var SharedFlowDocument = class {
286
- constructor(client, roomId) {
287
- this.client = client;
288
- this.roomId = roomId;
289
- this.doc = new Y.Doc();
290
- this.lastAccess = Date.now();
291
- this.status = "disconnected";
292
- this.ready = false;
293
- this.provider = null;
294
- this.listeners = /* @__PURE__ */ new Set();
295
- this.live = /* @__PURE__ */ new Set();
296
- this.attempt = 0;
297
- this.generation = 0;
298
- this.notify = () => {
299
- for (const listener of this.listeners) listener();
300
- };
301
- this.flush = () => {
302
- void this.provider?.waitForFlush().catch(() => void 0);
303
- };
304
- this.reconnect = async () => {
305
- clearTimeout(this.retry);
306
- this.attempt = 0;
307
- await this.stopProvider();
308
- await this.connect();
309
- };
310
- }
311
- watchPageExit(enabled) {
312
- if (typeof window === "undefined") return;
313
- if (enabled) {
314
- window.addEventListener("pagehide", this.flush);
315
- window.addEventListener("beforeunload", this.flush);
316
- } else {
317
- window.removeEventListener("pagehide", this.flush);
318
- window.removeEventListener("beforeunload", this.flush);
319
- }
320
- }
321
- evictIfIdle() {
322
- if (this.listeners.size || this.pending) return false;
323
- this.generation++;
324
- clearTimeout(this.idle);
325
- clearTimeout(this.retry);
326
- clearTimeout(this.stopTimer);
327
- if (sessions.get(this.client)?.get(this.roomId) === this) sessions.get(this.client)?.delete(this.roomId);
328
- void this.stopProvider().finally(() => this.doc.destroy());
329
- return true;
330
- }
331
- subscribe(listener, live = true) {
332
- this.lastAccess = Date.now();
333
- clearTimeout(this.idle);
334
- clearTimeout(this.stopTimer);
335
- this.listeners.add(listener);
336
- if (live) this.live.add(listener);
337
- void this.connect();
338
- return () => {
339
- this.listeners.delete(listener);
340
- this.live.delete(listener);
341
- if (!this.live.size && this.provider)
342
- this.stopTimer = setTimeout(() => {
343
- if (!this.live.size) void this.stopProvider();
344
- }, 1e3);
345
- if (!this.listeners.size) {
346
- clearTimeout(this.retry);
347
- this.idle = setTimeout(() => {
348
- this.evictIfIdle();
349
- }, RETAIN_MS);
350
- this.idle.unref?.();
351
- }
352
- };
353
- }
354
- connect() {
355
- if (this.pending) return this.pending;
356
- if (this.provider || this.ready && !this.live.size && this.checkpoint && Date.now() - this.checkpoint.savedAt < 3e4) return Promise.resolve();
357
- const generation = this.generation;
358
- this.status = "connecting";
359
- this.notify();
360
- this.pending = (async () => {
361
- await this.stopping;
362
- if (!this.checkpoint) {
363
- const membership = this.client.getRoom(this.roomId)?.getMyMembership?.();
364
- if (!membership || membership === "join") this.checkpoint = await readFlowCheckpoint(this.client, this.roomId);
365
- if (generation !== this.generation) return;
366
- if (this.checkpoint) {
367
- try {
368
- Y.decodeUpdate(this.checkpoint.update);
369
- Y.applyUpdate(this.doc, this.checkpoint.update, this);
370
- this.ready = true;
371
- bindFlowOwnerFromRoom(this.doc, this.client, this.roomId);
372
- this.notify();
373
- } catch {
374
- this.checkpoint = void 0;
375
- }
376
- }
377
- }
378
- const result = await withLoadSlot(() => readFlowDocumentHistory(this.client, this.roomId, this.checkpoint), this.live.size > 0);
379
- if (generation !== this.generation) return;
380
- Y.applyUpdate(this.doc, result.update, this);
381
- this.ready = true;
382
- bindFlowOwnerFromRoom(this.doc, this.client, this.roomId);
383
- this.error = void 0;
384
- this.attempt = 0;
385
- if (result.token) this.checkpoint = { update: result.update, token: result.token, savedAt: Date.now() };
386
- this.status = this.live.size ? "connecting" : "connected";
387
- if (this.live.size) {
388
- const providerClient = clientWithHistory(
389
- this.client,
390
- async () => ({
391
- chunk: [syntheticSnapshot(result.update)],
392
- start: result.token,
393
- end: void 0
394
- })
395
- );
396
- const provider = new MatrixProvider(
397
- this.doc,
398
- providerClient,
399
- { type: "id", id: this.roomId },
400
- {
401
- translator: { enableMediaSnapshots: true },
402
- reader: { snapshotInterval: 10 },
403
- writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 },
404
- enableAwareness: true,
405
- enableExperimentalWebrtcSync: true
406
- }
407
- );
408
- this.provider = provider;
409
- this.watchPageExit(true);
410
- provider.onDocumentUnavailable(() => {
411
- if (this.provider !== provider) return;
412
- this.status = "error";
413
- this.error = "Flow document is unavailable";
414
- this.notify();
415
- });
416
- provider.onDocumentAvailable(() => {
417
- if (this.provider !== provider) return;
418
- this.status = "connected";
419
- this.error = void 0;
420
- this.notify();
421
- });
422
- void provider.initialize().catch((error) => {
423
- if (this.provider !== provider) return;
424
- provider.dispose();
425
- this.watchPageExit(false);
426
- this.provider = null;
427
- this.fail(error);
428
- });
429
- }
430
- this.save();
431
- this.notify();
432
- })().catch((error) => {
433
- if (generation === this.generation) this.fail(error);
434
- }).finally(() => {
435
- this.pending = void 0;
436
- });
437
- return this.pending;
438
- }
439
- fail(error) {
440
- const code = error?.errcode;
441
- if (code === "M_FORBIDDEN" || code === "M_UNKNOWN_TOKEN") {
442
- this.ready = false;
443
- this.checkpoint = void 0;
444
- }
445
- this.status = "error";
446
- this.error = error instanceof Error ? error.message : String(error);
447
- this.notify();
448
- clearTimeout(this.retry);
449
- if (this.listeners.size) this.retry = setTimeout(() => void this.connect(), Math.min(5e3 * 2 ** this.attempt++, 3e4));
450
- }
451
- save() {
452
- if (this.checkpoint && this.ready) void writeFlowCheckpoint(this.client, this.roomId, this.checkpoint);
453
- }
454
- async stopProvider() {
455
- const provider = this.provider;
456
- if (!provider) return;
457
- this.save();
458
- this.watchPageExit(false);
459
- this.provider = null;
460
- this.stopping = (async () => {
461
- let timer;
462
- try {
463
- await Promise.race([
464
- provider.waitForFlush(),
465
- new Promise((resolve) => {
466
- timer = setTimeout(resolve, 3e3);
467
- })
468
- ]);
469
- } catch {
470
- return;
471
- } finally {
472
- clearTimeout(timer);
473
- provider.dispose();
474
- }
475
- })();
476
- await this.stopping;
477
- this.stopping = void 0;
478
- }
479
- };
480
- function getSharedFlowDocument(client, roomId) {
481
- let rooms = sessions.get(client);
482
- if (!rooms) {
483
- rooms = /* @__PURE__ */ new Map();
484
- sessions.set(client, rooms);
485
- }
486
- let session = rooms.get(roomId);
487
- if (!session) {
488
- session = new SharedFlowDocument(client, roomId);
489
- rooms.set(roomId, session);
490
- }
491
- session.lastAccess = Date.now();
492
- if (rooms.size > 32) {
493
- for (const candidate of [...rooms.values()].sort((a, b) => a.lastAccess - b.lastAccess)) {
494
- if (rooms.size <= 32) break;
495
- if (candidate !== session && Date.now() - candidate.lastAccess > 1e3) candidate.evictIfIdle();
496
- }
497
- }
498
- return session;
499
- }
500
-
501
- // src/core/lib/flowCompiler/conditions.ts
502
- var OPERATOR_MAP = {
503
- // BaseUcan ConditionRef vocabulary
504
- eq: "equals",
505
- neq: "not_equals",
506
- gt: "greater_than",
507
- lt: "less_than",
508
- in: "contains",
509
- exists: "is_not_empty",
510
- // Friendly camelCase (plugin FlowSpec `is`)
511
- equals: "equals",
512
- notEquals: "not_equals",
513
- greaterThan: "greater_than",
514
- lessThan: "less_than",
515
- isEmpty: "is_empty",
516
- isNotEmpty: "is_not_empty",
517
- // Evaluator vocabulary passthrough
518
- not_equals: "not_equals",
519
- greater_than: "greater_than",
520
- less_than: "less_than",
521
- contains: "contains",
522
- not_contains: "not_contains",
523
- notContains: "not_contains",
524
- is_empty: "is_empty",
525
- is_not_empty: "is_not_empty"
526
- };
527
- function toEvaluatorOperator(operator) {
528
- return OPERATOR_MAP[operator] ?? "equals";
529
- }
530
- function buildBlockConditionsProp(conditions, opts) {
531
- return JSON.stringify({
532
- enabled: opts?.enabled ?? true,
533
- mode: opts?.mode ?? "all_must_pass",
534
- conditions: conditions.map((c, i) => ({
535
- id: `cond_${c.sourceBlockId}_${c.property}_${i}`,
536
- name: c.name ?? `Condition from ${c.sourceBlockId}`,
537
- sourceBlockId: c.sourceBlockId,
538
- sourceBlockType: c.sourceBlockType ?? "action",
539
- rule: {
540
- type: "property_value",
541
- property: c.property,
542
- operator: toEvaluatorOperator(c.operator),
543
- value: c.value
544
- },
545
- effect: c.effect ?? { action: "enable" }
546
- }))
547
- });
548
- }
549
-
550
75
  // src/core/lib/flowCompiler/blockMapping.ts
551
76
  var ICON_DEFAULTS = {
552
77
  "bid/submit": "gavel",
@@ -593,1561 +118,2151 @@ function compileBlockProps(cap, registryType) {
593
118
  }
594
119
  var COMPILED_BLOCK_TYPE = "action";
595
120
 
596
- // src/core/lib/flowCompiler/compiler.ts
597
- function stripActiveScheduleBindings(plan) {
598
- let changed = false;
599
- const capabilities = plan.capabilities.map((cap) => {
600
- if (cap.trigger?.type !== "schedule") return cap;
601
- if (cap.trigger.scheduleRef === void 0 && cap.trigger.scheduleRevision === void 0) return cap;
602
- changed = true;
603
- const { scheduleRef: _ref, scheduleRevision: _rev, ...inactive } = cap.trigger;
604
- return { ...cap, trigger: inactive };
121
+ // src/core/lib/flowCompiler/readFlow.ts
122
+ function readCompiledFlowFromYDoc(yDoc) {
123
+ const flowMeta = yDoc.getMap("qi.flow.meta");
124
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
125
+ const nodes = {};
126
+ flowNodes.forEach((value, nodeId) => {
127
+ if (isYMapLike(value)) {
128
+ nodes[nodeId] = yMapToFlowNode(value);
129
+ }
605
130
  });
606
- return changed ? { ...plan, capabilities } : plan;
607
- }
608
- function compileBaseUcanFlow(plan, registry) {
609
- if (!Array.isArray(plan.capabilities)) {
610
- throw new Error("BaseUcanFlow.capabilities must be an array");
611
- }
612
- const capabilities = plan.capabilities;
613
- if (capabilities.length === 0) {
614
- throw new Error("BaseUcanFlow has no capabilities to compile");
131
+ if (flowNodes.size === 0 && flowMeta.size === 0) {
132
+ return null;
615
133
  }
616
- const actionMap = /* @__PURE__ */ new Map();
617
- for (const cap of capabilities) {
618
- const nodeId = cap.id?.trim();
619
- if (!nodeId) {
620
- throw new Error("Every capability in BaseUcanFlow.capabilities must include a non-empty id.");
621
- }
622
- if (actionMap.has(nodeId)) {
623
- throw new Error(`Duplicate capability id "${nodeId}" in BaseUcanFlow.capabilities.`);
624
- }
625
- const action = registry.getActionByCan(cap.can);
626
- if (!action) {
627
- throw new Error(`Unknown capability "${cap.can}" for node "${nodeId}". Not found in action registry.`);
134
+ const meta = {
135
+ flowId: flowMeta.get("flowId") || "",
136
+ title: flowMeta.get("title") || "",
137
+ goal: flowMeta.get("goal"),
138
+ version: flowMeta.get("version") || "",
139
+ // The room creator, never the doc's editable copy (see flowOwner.ts).
140
+ flowOwnerDid: flowOwnerOf(yDoc),
141
+ flowUri: flowMeta.get("flowUri"),
142
+ compiledAt: flowMeta.get("compiledAt") || "",
143
+ compiledFrom: "BaseUcanFlow"
144
+ };
145
+ const flowEdges = yDoc.getMap("qi.flow.edges");
146
+ const edges = [];
147
+ flowEdges.forEach((value) => {
148
+ if (isYMapLike(value)) {
149
+ edges.push(yMapToEdge(value));
628
150
  }
629
- actionMap.set(nodeId, { action, nodeId, cap });
630
- }
151
+ });
152
+ const flowOrder = yDoc.getArray("qi.flow.order");
153
+ const order = flowOrder.toArray();
154
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
631
155
  const blockIndex = {};
632
- for (const nodeId of actionMap.keys()) {
633
- blockIndex[nodeId] = generateBlockId(nodeId);
156
+ flowBlockIndex.forEach((value, key) => {
157
+ blockIndex[key] = value;
158
+ });
159
+ const blocks = order.filter((nodeId) => nodes[nodeId]).map((nodeId) => {
160
+ const node = nodes[nodeId];
161
+ return {
162
+ id: node.blockId,
163
+ type: COMPILED_BLOCK_TYPE,
164
+ props: { ...node.props }
165
+ };
166
+ });
167
+ return { meta, blocks, nodes, edges, order, blockIndex };
168
+ }
169
+ function yMapToFlowNode(yMap) {
170
+ return {
171
+ id: yMap.get("id") || "",
172
+ blockId: yMap.get("blockId") || "",
173
+ can: yMap.get("can") || "",
174
+ with: yMap.get("with") || "",
175
+ registryType: yMap.get("registryType") || "",
176
+ title: yMap.get("title") || "",
177
+ description: yMap.get("description") || "",
178
+ props: yMap.get("props") || {},
179
+ phase: yMap.get("phase"),
180
+ parallelGroup: yMap.get("parallelGroup"),
181
+ actor: yMap.get("actor")
182
+ };
183
+ }
184
+ function yMapToEdge(yMap) {
185
+ return {
186
+ id: yMap.get("id") || "",
187
+ source: yMap.get("source") || "",
188
+ target: yMap.get("target") || "",
189
+ // Only 'trigger' edges exist. Legacy 'dependency' edges from older
190
+ // Y.Docs (before dependsOn was removed) get coerced — they'll be
191
+ // overwritten on the next compile pass.
192
+ kind: "trigger",
193
+ condition: yMap.get("condition")
194
+ };
195
+ }
196
+
197
+ // src/core/lib/flowCompiler/hydrate.ts
198
+ import * as Y from "yjs";
199
+ var DRAFT_CONTROL_MAP = "qi.flow.draftControl";
200
+ var LEGACY_COMMAND_REVISION_KEY = "legacyCommandRevision";
201
+ function nextDraftRevision(yDoc, current) {
202
+ const currentRevision = Number(current ?? 0);
203
+ const legacyRevision = Number(yDoc.getMap(DRAFT_CONTROL_MAP).get(LEGACY_COMMAND_REVISION_KEY) ?? 0);
204
+ return Math.max(0, Number.isFinite(currentRevision) ? currentRevision : 0, Number.isFinite(legacyRevision) ? legacyRevision : 0) + 1;
205
+ }
206
+ function jsonOutputSchema(fields) {
207
+ if (fields.length === 0) return { type: "object", additionalProperties: true };
208
+ const properties = {};
209
+ for (const field of fields) {
210
+ const [root] = field.path.split(".");
211
+ if (!root) continue;
212
+ properties[root] = field.path.includes(".") ? { type: "object" } : { type: field.type };
634
213
  }
635
- const triggerEdges = [];
636
- for (const [nodeId, { cap, action }] of actionMap) {
637
- const trigger = cap.trigger;
638
- if (!trigger) continue;
639
- if (trigger.type === "block.event") {
640
- if (action.eligibleForEventTrigger !== true) {
641
- throw new Error(
642
- `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.`
643
- );
644
- }
645
- const sourceId = trigger.sourceBlockId?.trim();
646
- const eventName = trigger.eventName?.trim();
647
- if (!sourceId || !eventName) {
648
- throw new Error(`Block "${nodeId}" has a block.event trigger but is missing sourceBlockId or eventName.`);
649
- }
650
- const source = actionMap.get(sourceId);
651
- if (!source) {
652
- throw new Error(`Trigger on block "${nodeId}" references unknown source block "${sourceId}".`);
653
- }
654
- const declaredEvents = getEventsForBlock(source.action, source.cap.nb);
655
- if (declaredEvents.length === 0) {
656
- throw new Error(`Trigger on block "${nodeId}" references event "${eventName}" but source action "${source.action.type}" declares no events.`);
214
+ return { type: "object", properties, additionalProperties: true };
215
+ }
216
+ var ACTION_SAFETY_BY_TYPE = {
217
+ "qi/noop": "pure",
218
+ "qi/data.constant": "pure",
219
+ // Reads a public endpoint and returns the body. No effect to fence.
220
+ "qi/http.fetch": "pure",
221
+ // Calls out and may change the far side, so it is not pure — but the runner
222
+ // makes the call itself, so it is a provider action, not a fenced one. That
223
+ // keeps the `flow/block/execute` grant every flow already holds sufficient.
224
+ "qi/http.request": "provider_idempotent"
225
+ };
226
+ function resolveActionSafety(type, executionOwner) {
227
+ if (executionOwner === "human") return "approval_only";
228
+ return ACTION_SAFETY_BY_TYPE[type] ?? "fenced";
229
+ }
230
+ function executionContract(node) {
231
+ const action = getAction(node.registryType);
232
+ const manifest = generateActionManifest();
233
+ const entry = manifest.actions.find((candidate) => candidate.type === node.registryType);
234
+ if (!action || !entry || !entry.can) return void 0;
235
+ const safety = resolveActionSafety(action.type, action.executionOwner);
236
+ const contract = {
237
+ kind: "qi.action.contract",
238
+ schemaVersion: "1.0",
239
+ type: action.type,
240
+ can: entry.can,
241
+ contractVersion: action.contractVersion,
242
+ manifestDigest: manifest.manifestDigest,
243
+ inputSchema: action.inputSchema ?? { type: "object", additionalProperties: true },
244
+ outputSchema: jsonOutputSchema(entry.outputSchema),
245
+ safety,
246
+ handlerVersion: `${action.type}@${action.contractVersion}`,
247
+ dataClassification: action.sensitiveInputPaths?.length || action.sensitiveOutputPaths?.length ? "confidential" : "shared",
248
+ requiredServices: [...action.requiredServices ?? []],
249
+ idempotency: {
250
+ providerKey: false,
251
+ readback: safety === "fenced" ? "required" : "unavailable",
252
+ compensation: "unavailable"
253
+ },
254
+ contractDigest: entry.contractDigest
255
+ };
256
+ return contract;
257
+ }
258
+ function writeExecutionMeta(yDoc) {
259
+ const meta = yDoc.getMap("qi.flow.meta");
260
+ meta.set(
261
+ "definitionDigest",
262
+ sha256Digest({
263
+ nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
264
+ edges: yDoc.getMap("qi.flow.edges").toJSON(),
265
+ order: yDoc.getArray("qi.flow.order").toArray()
266
+ })
267
+ );
268
+ meta.set("executionSchemaVersion", 3);
269
+ }
270
+ function rebaseStepResource(authored, flowPrefix, stepIds) {
271
+ if (authored === flowPrefix || authored.startsWith(`${flowPrefix}:`)) return void 0;
272
+ for (const stepId of stepIds) {
273
+ if (stepId && authored.endsWith(`:${stepId}`)) return `${flowPrefix}:${stepId}`;
274
+ }
275
+ return void 0;
276
+ }
277
+ function ensureFlowExecutionMetadata(yDoc) {
278
+ if (yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") !== 1) return false;
279
+ let changed = false;
280
+ yDoc.transact(() => {
281
+ const docId = yDoc.getMap("root").get("doc_id");
282
+ const flowPrefix = typeof docId === "string" && docId ? `ixo:flow:${docId}` : void 0;
283
+ for (const [nodeId, value] of yDoc.getMap("qi.flow.nodes").entries()) {
284
+ if (!(value instanceof Y.Map)) continue;
285
+ const registryType = value.get("registryType");
286
+ if (typeof registryType !== "string" || !registryType) continue;
287
+ const authoredResource = value.get("with");
288
+ const rebased = flowPrefix && typeof authoredResource === "string" ? rebaseStepResource(authoredResource, flowPrefix, [String(value.get("id") ?? nodeId), String(value.get("blockId") ?? "")]) : void 0;
289
+ if (rebased) {
290
+ value.set("with", rebased);
291
+ const props = asRecord(value.get("props"));
292
+ if (props && props.with === authoredResource) value.set("props", { ...props, with: rebased });
293
+ changed = true;
657
294
  }
658
- const found = declaredEvents.find((e) => e.name === eventName);
659
- if (!found) {
660
- const declared = declaredEvents.map((e) => e.name).join(", ");
661
- throw new Error(`Trigger on block "${nodeId}" references unknown event "${eventName}" on action type "${source.action.type}". Declared events: [${declared}]`);
295
+ const executionOwner = getAction(registryType)?.executionOwner ?? "agent";
296
+ if (value.get("executionOwner") !== executionOwner) {
297
+ value.set("executionOwner", executionOwner);
298
+ changed = true;
662
299
  }
663
- triggerEdges.push({
664
- id: `${sourceId}~event:${eventName}~>${nodeId}`,
665
- source: sourceId,
666
- target: nodeId,
667
- kind: "trigger"
300
+ const contract = executionContract({
301
+ id: String(value.get("id") ?? nodeId),
302
+ blockId: String(value.get("blockId") ?? ""),
303
+ can: String(value.get("can") ?? ""),
304
+ with: String(value.get("with") ?? ""),
305
+ registryType,
306
+ title: String(value.get("title") ?? ""),
307
+ description: String(value.get("description") ?? ""),
308
+ props: value.get("props") ?? {}
668
309
  });
669
- }
670
- if (trigger.type === "block.event.all") {
671
- if (action.eligibleForEventTrigger !== true) {
672
- throw new Error(`Block "${nodeId}" is configured with a block.event.all trigger, but its action type "${action.type}" is not marked eligibleForEventTrigger.`);
673
- }
674
- const sources = trigger.sources || [];
675
- if (sources.length === 0) {
676
- throw new Error(`Block "${nodeId}" has a block.event.all trigger but no sources configured.`);
677
- }
678
- for (const src of sources) {
679
- const srcId = src.sourceBlockId?.trim();
680
- const evtName = src.eventName?.trim();
681
- if (!srcId || !evtName) {
682
- throw new Error(`Block "${nodeId}" has a block.event.all source with missing sourceBlockId or eventName.`);
683
- }
684
- const sourceEntry = actionMap.get(srcId);
685
- if (!sourceEntry) {
686
- throw new Error(`Barrier trigger on block "${nodeId}" references unknown source block "${srcId}".`);
687
- }
688
- const declaredEvents = getEventsForBlock(sourceEntry.action, sourceEntry.cap.nb);
689
- const found = declaredEvents.find((e) => e.name === evtName);
690
- if (!found) {
691
- const declared = declaredEvents.map((e) => e.name).join(", ");
692
- throw new Error(`Barrier trigger on block "${nodeId}" references unknown event "${evtName}" on action type "${sourceEntry.action.type}". Declared events: [${declared}]`);
693
- }
694
- if (!src.alias?.trim()) {
695
- throw new Error(`Barrier trigger on block "${nodeId}" has a source (${srcId}/${evtName}) with no alias.`);
696
- }
697
- triggerEdges.push({
698
- id: `${srcId}~event:${evtName}~>${nodeId}`,
699
- source: srcId,
700
- target: nodeId,
701
- kind: "trigger"
702
- });
703
- }
704
- }
705
- if (trigger.type === "schedule") {
706
- if (action.eligibleForTimeTrigger !== true) {
707
- throw new Error(
708
- `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.`
709
- );
710
- }
711
- if (trigger.sourceBlockId || trigger.sources || trigger.eventName) {
712
- throw new Error(
713
- `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.`
714
- );
715
- }
716
- if (trigger.scheduleRevision !== void 0 && (!Number.isInteger(trigger.scheduleRevision) || trigger.scheduleRevision < 1)) {
717
- throw new Error(`Block "${nodeId}" has a schedule trigger with an invalid scheduleRevision (must be an integer >= 1).`);
310
+ if (contract && JSON.stringify(value.get("actionContract")) !== JSON.stringify(contract)) {
311
+ value.set("actionContract", contract);
312
+ changed = true;
718
313
  }
719
314
  }
720
- if (trigger.type === "block.event" || trigger.type === "block.event.all") {
721
- const refs = collectOutputRefs(cap.nb || {});
722
- for (const ref of refs) {
723
- const parsed = parseOutputRef(ref);
724
- if (!parsed) continue;
725
- if (!actionMap.has(parsed.nodeId)) {
726
- throw new Error(`Listener "${nodeId}" references output of unknown block "${parsed.nodeId}" via ref "${ref}".`);
727
- }
728
- }
315
+ const meta = yDoc.getMap("qi.flow.meta");
316
+ if (changed || typeof meta.get("definitionDigest") !== "string" || meta.get("executionSchemaVersion") !== 3) {
317
+ meta.set("draftRevision", nextDraftRevision(yDoc, meta.get("draftRevision")));
318
+ writeExecutionMeta(yDoc);
319
+ meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
320
+ changed = true;
729
321
  }
322
+ });
323
+ return changed;
324
+ }
325
+ function adoptLegacyFlowDocument(yDoc) {
326
+ const adopted = adoptDraftShape(yDoc);
327
+ const stamped = ensureFlowExecutionMetadata(yDoc);
328
+ return adopted || stamped;
329
+ }
330
+ function legacyPropsByBlockId(yDoc) {
331
+ const byBlockId = /* @__PURE__ */ new Map();
332
+ collectLegacyBlockProps(yDoc.getXmlFragment("document"), byBlockId);
333
+ return byBlockId;
334
+ }
335
+ function asRecord(value) {
336
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
337
+ }
338
+ function collectLegacyBlockProps(parent, out) {
339
+ for (let index = 0; index < parent.length; index += 1) {
340
+ const child = parent.get(index);
341
+ if (!(child instanceof Y.XmlElement)) continue;
342
+ if (child.nodeName === "blockContainer") readContainerProps(child, out);
343
+ collectLegacyBlockProps(child, out);
730
344
  }
731
- const edges = [...triggerEdges];
732
- detectTriggerCycles(triggerEdges);
733
- const order = Array.from(actionMap.keys());
734
- const blocks = [];
735
- const nodes = {};
736
- for (const nodeId of order) {
737
- const { action, cap } = actionMap.get(nodeId);
738
- const blockId = blockIndex[nodeId];
739
- const props = compileBlockProps(cap, action.type);
740
- if (cap.condition) {
741
- props.conditions = compileCondition(cap.condition, blockIndex);
742
- }
743
- if (cap.trigger) {
744
- props.trigger = compileTrigger(cap.trigger, blockIndex);
345
+ }
346
+ function readContainerProps(container, out) {
347
+ const attrs = asRecord(container.getAttribute("attrs"));
348
+ const directId = container.getAttribute("id");
349
+ const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
350
+ if (!blockId) return;
351
+ const props = {};
352
+ const addAll = (source) => {
353
+ for (const [key, value] of Object.entries(source ?? {})) {
354
+ if (typeof value === "string" && value !== "") props[key] = value;
745
355
  }
746
- props.triggerMode = cap.trigger?.type || "manual";
747
- blocks.push({
748
- id: blockId,
749
- type: COMPILED_BLOCK_TYPE,
750
- props
751
- });
752
- nodes[nodeId] = {
753
- id: nodeId,
754
- blockId,
755
- can: cap.can,
756
- with: cap.with,
757
- registryType: action.type,
758
- title: cap.title || cap.can,
759
- description: cap.description || "",
760
- props,
761
- phase: cap.phase,
762
- parallelGroup: cap.parallelGroup,
763
- actor: cap.actor
764
- };
765
- }
766
- return {
767
- meta: {
768
- flowId: plan.flowId,
769
- title: plan.title,
770
- goal: plan.goal,
771
- version: plan.version,
772
- flowOwnerDid: plan.meta?.rootIssuer || "",
773
- flowUri: plan.meta?.flowUri,
774
- compiledAt: (/* @__PURE__ */ new Date()).toISOString(),
775
- compiledFrom: "BaseUcanFlow"
776
- },
777
- blocks,
778
- nodes,
779
- edges,
780
- order,
781
- blockIndex
782
356
  };
357
+ addAll(asRecord(attrs?.props));
358
+ const content = container.get(0);
359
+ if (content instanceof Y.XmlElement && content.nodeName !== "blockGroup") addAll(content.getAttributes());
360
+ const textColor = container.getAttribute("textColor");
361
+ if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
362
+ const backgroundColor = container.getAttribute("backgroundColor");
363
+ if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
364
+ if (Object.keys(props).length > 0) out.set(blockId, props);
783
365
  }
784
- function generateBlockId(nodeId) {
785
- return `flow_block_${nodeId}`;
366
+ function adoptDraftShape(yDoc) {
367
+ const meta = yDoc.getMap("qi.flow.meta");
368
+ if (meta.get("draftSchemaVersion") === 1) return false;
369
+ const nodes = yDoc.getMap("qi.flow.nodes");
370
+ if (nodes.size === 0) return false;
371
+ const propsByBlockId = legacyPropsByBlockId(yDoc);
372
+ yDoc.transact(() => {
373
+ for (const value of nodes.values()) {
374
+ if (!(value instanceof Y.Map)) continue;
375
+ const existing = value.get("props");
376
+ if (existing && typeof existing === "object" && Object.keys(existing).length > 0) continue;
377
+ const blockId = value.get("blockId");
378
+ const props = typeof blockId === "string" ? propsByBlockId.get(blockId) : void 0;
379
+ if (props && Object.keys(props).length > 0) value.set("props", { ...props });
380
+ }
381
+ meta.set("draftSchemaVersion", 1);
382
+ });
383
+ return true;
786
384
  }
787
- function compileCondition(condition, blockIndex) {
788
- const sourceBlockId = blockIndex[condition.sourceId];
789
- if (!sourceBlockId) {
790
- throw new Error(`Condition references unknown source "${condition.sourceId}".`);
791
- }
792
- const conditionConfig = {
793
- enabled: true,
794
- mode: "all_must_pass",
795
- conditions: [
796
- {
797
- id: `cond_${condition.sourceId}_${condition.field}`,
798
- name: `Condition from ${condition.sourceId}`,
799
- sourceBlockId,
800
- sourceBlockType: COMPILED_BLOCK_TYPE,
801
- rule: {
802
- type: "property_value",
803
- property: condition.field,
804
- // Map the BaseUcan ConditionRef operator (eq/neq/…) onto the FE evaluator's
805
- // vocabulary (equals/not_equals/…). Writing it verbatim is the historical bug
806
- // that made compiler-authored conditions silently never evaluate.
807
- operator: toEvaluatorOperator(condition.operator),
808
- value: condition.value
809
- },
810
- effect: condition.effect || { action: "enable" }
385
+ function hydrateYDocFromCompiledFlow(yDoc, compiled) {
386
+ yDoc.transact(() => {
387
+ const flowMeta = yDoc.getMap("qi.flow.meta");
388
+ for (const [key, value] of Object.entries(compiled.meta)) {
389
+ if (value !== void 0) {
390
+ flowMeta.set(key, value);
811
391
  }
812
- ]
813
- };
814
- return JSON.stringify(conditionConfig);
392
+ }
393
+ const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
394
+ flowMeta.set("draftSchemaVersion", 1);
395
+ flowMeta.set("draftRevision", draftRevision);
396
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
397
+ for (const [nodeId, node] of Object.entries(compiled.nodes)) {
398
+ flowNodes.set(nodeId, createYMapFromNode(node));
399
+ }
400
+ const flowEdges = yDoc.getMap("qi.flow.edges");
401
+ for (const edge of compiled.edges) {
402
+ const yEdge = new Y.Map();
403
+ yEdge.set("id", edge.id);
404
+ yEdge.set("source", edge.source);
405
+ yEdge.set("target", edge.target);
406
+ yEdge.set("kind", edge.kind);
407
+ if (edge.condition) yEdge.set("condition", edge.condition);
408
+ flowEdges.set(edge.id, yEdge);
409
+ }
410
+ const flowOrder = yDoc.getArray("qi.flow.order");
411
+ for (const nodeId of compiled.order) {
412
+ flowOrder.push([nodeId]);
413
+ }
414
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
415
+ for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
416
+ flowBlockIndex.set(nodeId, blockId);
417
+ }
418
+ writeExecutionMeta(yDoc);
419
+ });
815
420
  }
816
- function compileTrigger(trigger, blockIndex) {
817
- if (trigger.type === "block.event" && trigger.sourceBlockId) {
818
- return JSON.stringify({ ...trigger, sourceBlockId: blockIndex[trigger.sourceBlockId.trim()] });
819
- }
820
- if (trigger.type === "block.event.all" && trigger.sources) {
821
- return JSON.stringify({
822
- ...trigger,
823
- sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: blockIndex[src.sourceBlockId.trim()] }))
824
- });
825
- }
826
- return JSON.stringify(trigger);
421
+ function clearFlowState(yDoc) {
422
+ yDoc.transact(() => {
423
+ const flowMeta = yDoc.getMap("qi.flow.meta");
424
+ flowMeta.forEach((_, key) => flowMeta.delete(key));
425
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
426
+ flowNodes.forEach((_, key) => flowNodes.delete(key));
427
+ const flowEdges = yDoc.getMap("qi.flow.edges");
428
+ flowEdges.forEach((_, key) => flowEdges.delete(key));
429
+ const flowOrder = yDoc.getArray("qi.flow.order");
430
+ if (flowOrder.length > 0) {
431
+ flowOrder.delete(0, flowOrder.length);
432
+ }
433
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
434
+ flowBlockIndex.forEach((_, key) => flowBlockIndex.delete(key));
435
+ });
827
436
  }
828
- function collectOutputRefs(value) {
829
- const refs = [];
830
- walk(value);
831
- return refs;
832
- function walk(v) {
833
- if (isRuntimeRef(v)) {
834
- const r = v.$ref;
835
- if (!r.startsWith("trigger.")) refs.push(r);
836
- return;
437
+ function hydrateYDocFromMergeResult(yDoc, mergeResult) {
438
+ const { merged, added, replaced } = mergeResult;
439
+ yDoc.transact(() => {
440
+ const flowMeta = yDoc.getMap("qi.flow.meta");
441
+ for (const [key, value] of Object.entries(merged.meta)) {
442
+ if (value !== void 0) {
443
+ flowMeta.set(key, value);
444
+ }
837
445
  }
838
- if (Array.isArray(v)) {
839
- for (const item of v) walk(item);
840
- return;
446
+ const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
447
+ flowMeta.set("draftSchemaVersion", 1);
448
+ flowMeta.set("draftRevision", draftRevision);
449
+ const flowNodes = yDoc.getMap("qi.flow.nodes");
450
+ for (const nodeId of replaced) {
451
+ flowNodes.delete(nodeId);
452
+ flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
841
453
  }
842
- if (v !== null && typeof v === "object") {
843
- for (const inner of Object.values(v)) walk(inner);
454
+ for (const nodeId of added) {
455
+ flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
844
456
  }
845
- }
457
+ const flowEdges = yDoc.getMap("qi.flow.edges");
458
+ flowEdges.forEach((_, key) => flowEdges.delete(key));
459
+ for (const edge of merged.edges) {
460
+ const yEdge = new Y.Map();
461
+ yEdge.set("id", edge.id);
462
+ yEdge.set("source", edge.source);
463
+ yEdge.set("target", edge.target);
464
+ yEdge.set("kind", edge.kind);
465
+ if (edge.condition) yEdge.set("condition", edge.condition);
466
+ flowEdges.set(edge.id, yEdge);
467
+ }
468
+ const flowOrder = yDoc.getArray("qi.flow.order");
469
+ if (flowOrder.length > 0) {
470
+ flowOrder.delete(0, flowOrder.length);
471
+ }
472
+ for (const nodeId of merged.order) {
473
+ flowOrder.push([nodeId]);
474
+ }
475
+ const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
476
+ for (const nodeId of [...added, ...replaced]) {
477
+ flowBlockIndex.set(nodeId, merged.blockIndex[nodeId]);
478
+ }
479
+ writeExecutionMeta(yDoc);
480
+ });
846
481
  }
847
- function parseOutputRef(ref) {
848
- const outputIndex = ref.indexOf(".output.");
849
- if (outputIndex === -1) return null;
850
- return {
851
- nodeId: ref.slice(0, outputIndex),
852
- fieldPath: ref.slice(outputIndex + ".output.".length)
853
- };
482
+ function initializeRuntime(yDoc, compiled, runId) {
483
+ const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
484
+ if (!resolvedRunId) return;
485
+ yDoc.transact(() => {
486
+ for (const nodeId of compiled.order) {
487
+ const blockId = compiled.blockIndex[nodeId];
488
+ if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
489
+ }
490
+ });
854
491
  }
855
- function detectTriggerCycles(triggerEdges) {
856
- if (triggerEdges.length === 0) return;
857
- const adjacency = /* @__PURE__ */ new Map();
858
- const allNodes = /* @__PURE__ */ new Set();
859
- for (const edge of triggerEdges) {
860
- if (!adjacency.has(edge.source)) adjacency.set(edge.source, []);
861
- adjacency.get(edge.source).push(edge.target);
862
- allNodes.add(edge.source);
863
- allNodes.add(edge.target);
864
- }
865
- const WHITE = 0;
866
- const GRAY = 1;
867
- const BLACK = 2;
868
- const color = /* @__PURE__ */ new Map();
869
- for (const id of allNodes) color.set(id, WHITE);
870
- const path = [];
871
- const visit = (node) => {
872
- color.set(node, GRAY);
873
- path.push(node);
874
- for (const next of adjacency.get(node) || []) {
875
- if (color.get(next) === GRAY) {
876
- const start = path.indexOf(next);
877
- const cycle = path.slice(start).concat(next).join(" \u2192 ");
878
- throw new Error(`Trigger cycle detected: ${cycle}. Block.event triggers must form a DAG; remove one of the trigger declarations to break the cycle.`);
879
- }
880
- if (color.get(next) === WHITE) {
881
- visit(next);
882
- }
492
+ function initializeRuntimeForNodes(yDoc, compiled, nodeIds, runId) {
493
+ const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
494
+ if (!resolvedRunId) return;
495
+ yDoc.transact(() => {
496
+ for (const nodeId of nodeIds) {
497
+ const blockId = compiled.blockIndex[nodeId];
498
+ if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
883
499
  }
884
- path.pop();
885
- color.set(node, BLACK);
886
- };
887
- for (const id of allNodes) {
888
- if (color.get(id) === WHITE) visit(id);
889
- }
500
+ });
501
+ }
502
+ function createYMapFromNode(node) {
503
+ const yNode = new Y.Map();
504
+ yNode.set("id", node.id);
505
+ yNode.set("blockId", node.blockId);
506
+ yNode.set("can", node.can);
507
+ yNode.set("with", node.with);
508
+ yNode.set("registryType", node.registryType);
509
+ yNode.set("executionOwner", getAction(node.registryType)?.executionOwner ?? "agent");
510
+ yNode.set("title", node.title);
511
+ yNode.set("description", node.description);
512
+ yNode.set("props", { ...node.props });
513
+ const contract = executionContract(node);
514
+ if (contract) yNode.set("actionContract", contract);
515
+ if (node.phase) yNode.set("phase", node.phase);
516
+ if (node.parallelGroup) yNode.set("parallelGroup", node.parallelGroup);
517
+ if (node.actor) yNode.set("actor", node.actor);
518
+ return yNode;
890
519
  }
891
520
 
892
- // src/core/lib/flowCompiler/hydrate.ts
521
+ // src/core/lib/flowCompiler/documentFragment.ts
893
522
  import * as Y2 from "yjs";
894
- var DRAFT_CONTROL_MAP = "qi.flow.draftControl";
895
- var LEGACY_COMMAND_REVISION_KEY = "legacyCommandRevision";
896
- function nextDraftRevision(yDoc, current) {
897
- const currentRevision = Number(current ?? 0);
898
- const legacyRevision = Number(yDoc.getMap(DRAFT_CONTROL_MAP).get(LEGACY_COMMAND_REVISION_KEY) ?? 0);
899
- return Math.max(0, Number.isFinite(currentRevision) ? currentRevision : 0, Number.isFinite(legacyRevision) ? legacyRevision : 0) + 1;
523
+ function writeCompiledBlocksToFragment(fragment, blocks) {
524
+ const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
525
+ for (const block of blocks) {
526
+ appendBlockToGroup(documentBlockGroup, block);
527
+ }
900
528
  }
901
- function jsonOutputSchema(fields) {
902
- if (fields.length === 0) return { type: "object", additionalProperties: true };
903
- const properties = {};
904
- for (const field of fields) {
905
- const [root] = field.path.split(".");
906
- if (!root) continue;
907
- properties[root] = field.path.includes(".") ? { type: "object" } : { type: field.type };
529
+ function insertCompiledBlockIntoFragment(fragment, block, beforeBlockId) {
530
+ const blockGroup = getOrCreateDocumentBlockGroup(fragment);
531
+ if (beforeBlockId) {
532
+ for (let index = 0; index < blockGroup.length; index += 1) {
533
+ const candidate = blockGroup.get(index);
534
+ if (isYXmlElementLike(candidate) && candidate.getAttribute("id") === beforeBlockId) {
535
+ blockGroup.insert(index, [createBlockContainer(block)]);
536
+ return;
537
+ }
538
+ }
908
539
  }
909
- return { type: "object", properties, additionalProperties: true };
540
+ appendBlockToGroup(blockGroup, block);
910
541
  }
911
- var ACTION_SAFETY_BY_TYPE = {
912
- "qi/noop": "pure",
913
- "qi/data.constant": "pure",
914
- // Reads a public endpoint and returns the body. No effect to fence.
915
- "qi/http.fetch": "pure",
916
- // Calls out and may change the far side, so it is not pure — but the runner
917
- // makes the call itself, so it is a provider action, not a fenced one. That
918
- // keeps the `flow/block/execute` grant every flow already holds sufficient.
919
- "qi/http.request": "provider_idempotent"
920
- };
921
- function resolveActionSafety(type, executionOwner) {
922
- if (executionOwner === "human") return "approval_only";
923
- return ACTION_SAFETY_BY_TYPE[type] ?? "fenced";
542
+ function removeAllFlowBlocks(fragment) {
543
+ const blockGroup = getExistingBlockGroup(fragment);
544
+ if (!blockGroup) return;
545
+ while (blockGroup.length > 0) {
546
+ blockGroup.delete(0, 1);
547
+ }
924
548
  }
925
- function executionContract(node) {
926
- const action = getAction(node.registryType);
927
- const manifest = generateActionManifest();
928
- const entry = manifest.actions.find((candidate) => candidate.type === node.registryType);
929
- if (!action || !entry || !entry.can) return void 0;
930
- const safety = resolveActionSafety(action.type, action.executionOwner);
931
- const contract = {
932
- kind: "qi.action.contract",
933
- schemaVersion: "1.0",
934
- type: action.type,
935
- can: entry.can,
936
- contractVersion: action.contractVersion,
937
- manifestDigest: manifest.manifestDigest,
938
- inputSchema: action.inputSchema ?? { type: "object", additionalProperties: true },
939
- outputSchema: jsonOutputSchema(entry.outputSchema),
940
- safety,
941
- handlerVersion: `${action.type}@${action.contractVersion}`,
942
- dataClassification: action.sensitiveInputPaths?.length || action.sensitiveOutputPaths?.length ? "confidential" : "shared",
943
- requiredServices: [...action.requiredServices ?? []],
944
- idempotency: {
945
- providerKey: false,
946
- readback: safety === "fenced" ? "required" : "unavailable",
947
- compensation: "unavailable"
948
- },
949
- contractDigest: entry.contractDigest
950
- };
951
- return contract;
549
+ function removeBlockFromFragment(fragment, blockId) {
550
+ const blockGroup = getExistingBlockGroup(fragment);
551
+ if (!blockGroup) return false;
552
+ for (let i = 0; i < blockGroup.length; i++) {
553
+ const container = blockGroup.get(i);
554
+ if (isYXmlElementLike(container) && container.getAttribute("id") === blockId) {
555
+ blockGroup.delete(i, 1);
556
+ return true;
557
+ }
558
+ }
559
+ return false;
952
560
  }
953
- function writeExecutionMeta(yDoc) {
954
- const meta = yDoc.getMap("qi.flow.meta");
955
- meta.set(
956
- "definitionDigest",
957
- sha256Digest({
958
- nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
959
- edges: yDoc.getMap("qi.flow.edges").toJSON(),
960
- order: yDoc.getArray("qi.flow.order").toArray()
961
- })
962
- );
963
- meta.set("executionSchemaVersion", 3);
561
+ function replaceBlockInFragment(fragment, block) {
562
+ const blockGroup = getExistingBlockGroup(fragment);
563
+ if (!blockGroup) return false;
564
+ for (let i = 0; i < blockGroup.length; i++) {
565
+ const container = blockGroup.get(i);
566
+ if (isYXmlElementLike(container) && container.getAttribute("id") === block.id) {
567
+ blockGroup.delete(i, 1);
568
+ const newContainer = createBlockContainer(block);
569
+ blockGroup.insert(i, [newContainer]);
570
+ return true;
571
+ }
572
+ }
573
+ return false;
964
574
  }
965
- function rebaseStepResource(authored, flowPrefix, stepIds) {
966
- if (authored === flowPrefix || authored.startsWith(`${flowPrefix}:`)) return void 0;
967
- for (const stepId of stepIds) {
968
- if (stepId && authored.endsWith(`:${stepId}`)) return `${flowPrefix}:${stepId}`;
575
+ function swapBlocksInFragment(fragment, idA, idB) {
576
+ const blockGroup = getExistingBlockGroup(fragment);
577
+ if (!blockGroup) return false;
578
+ let ia = -1;
579
+ let ib = -1;
580
+ for (let i = 0; i < blockGroup.length; i++) {
581
+ const container = blockGroup.get(i);
582
+ if (isYXmlElementLike(container)) {
583
+ const id = container.getAttribute("id");
584
+ if (id === idA) ia = i;
585
+ else if (id === idB) ib = i;
586
+ }
969
587
  }
970
- return void 0;
588
+ if (ia < 0 || ib < 0 || ia === ib) return false;
589
+ const lo = Math.min(ia, ib);
590
+ const hi = Math.max(ia, ib);
591
+ const loClone = blockGroup.get(lo).clone();
592
+ const hiClone = blockGroup.get(hi).clone();
593
+ blockGroup.delete(hi, 1);
594
+ blockGroup.insert(hi, [loClone]);
595
+ blockGroup.delete(lo, 1);
596
+ blockGroup.insert(lo, [hiClone]);
597
+ return true;
971
598
  }
972
- function ensureFlowExecutionMetadata(yDoc) {
973
- if (yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") !== 1) return false;
974
- let changed = false;
975
- yDoc.transact(() => {
976
- const docId = yDoc.getMap("root").get("doc_id");
977
- const flowPrefix = typeof docId === "string" && docId ? `ixo:flow:${docId}` : void 0;
978
- for (const [nodeId, value] of yDoc.getMap("qi.flow.nodes").entries()) {
979
- if (!(value instanceof Y2.Map)) continue;
980
- const registryType = value.get("registryType");
981
- if (typeof registryType !== "string" || !registryType) continue;
982
- const authoredResource = value.get("with");
983
- const rebased = flowPrefix && typeof authoredResource === "string" ? rebaseStepResource(authoredResource, flowPrefix, [String(value.get("id") ?? nodeId), String(value.get("blockId") ?? "")]) : void 0;
984
- if (rebased) {
985
- value.set("with", rebased);
986
- const props = asRecord(value.get("props"));
987
- if (props && props.with === authoredResource) value.set("props", { ...props, with: rebased });
988
- changed = true;
989
- }
990
- const executionOwner = getAction(registryType)?.executionOwner ?? "agent";
991
- if (value.get("executionOwner") !== executionOwner) {
992
- value.set("executionOwner", executionOwner);
993
- changed = true;
994
- }
995
- const contract = executionContract({
996
- id: String(value.get("id") ?? nodeId),
997
- blockId: String(value.get("blockId") ?? ""),
998
- can: String(value.get("can") ?? ""),
999
- with: String(value.get("with") ?? ""),
1000
- registryType,
1001
- title: String(value.get("title") ?? ""),
1002
- description: String(value.get("description") ?? ""),
1003
- props: value.get("props") ?? {}
1004
- });
1005
- if (contract && JSON.stringify(value.get("actionContract")) !== JSON.stringify(contract)) {
1006
- value.set("actionContract", contract);
1007
- changed = true;
599
+ function applyMergeResultToFragment(fragment, mergeResult) {
600
+ const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
601
+ const blockByNodeId = /* @__PURE__ */ new Map();
602
+ for (const block of mergeResult.merged.blocks) {
603
+ for (const [nodeId, blockId] of Object.entries(mergeResult.merged.blockIndex)) {
604
+ if (blockId === block.id) {
605
+ blockByNodeId.set(nodeId, block);
606
+ break;
1008
607
  }
1009
608
  }
1010
- const meta = yDoc.getMap("qi.flow.meta");
1011
- if (changed || typeof meta.get("definitionDigest") !== "string" || meta.get("executionSchemaVersion") !== 3) {
1012
- meta.set("draftRevision", nextDraftRevision(yDoc, meta.get("draftRevision")));
1013
- writeExecutionMeta(yDoc);
1014
- meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
1015
- changed = true;
609
+ }
610
+ for (const nodeId of mergeResult.replaced) {
611
+ const block = blockByNodeId.get(nodeId);
612
+ if (block) {
613
+ replaceBlockInFragment(fragment, block);
1016
614
  }
1017
- });
1018
- return changed;
615
+ }
616
+ for (const nodeId of mergeResult.added) {
617
+ const block = blockByNodeId.get(nodeId);
618
+ if (block) {
619
+ appendBlockToGroup(documentBlockGroup, block);
620
+ }
621
+ }
1019
622
  }
1020
- function adoptLegacyFlowDocument(yDoc) {
1021
- const adopted = adoptDraftShape(yDoc);
1022
- const stamped = ensureFlowExecutionMetadata(yDoc);
1023
- return adopted || stamped;
623
+ function readBlocksFromFragment(fragment) {
624
+ const blockGroup = getExistingBlockGroup(fragment);
625
+ if (!blockGroup) return [];
626
+ const blocks = [];
627
+ for (let i = 0; i < blockGroup.length; i++) {
628
+ const container = blockGroup.get(i);
629
+ if (!isYXmlElementLike(container) || container.nodeName !== "blockContainer") continue;
630
+ const id = container.getAttribute("id");
631
+ if (typeof id !== "string" || id.length === 0) continue;
632
+ const content = container.get(0);
633
+ if (!isYXmlElementLike(content)) continue;
634
+ const props = { ...content.getAttributes() };
635
+ const textColor = container.getAttribute("textColor");
636
+ if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
637
+ const backgroundColor = container.getAttribute("backgroundColor");
638
+ if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
639
+ blocks.push({ id, type: content.nodeName, props });
640
+ }
641
+ return blocks;
1024
642
  }
1025
- function legacyPropsByBlockId(yDoc) {
1026
- const byBlockId = /* @__PURE__ */ new Map();
1027
- collectLegacyBlockProps(yDoc.getXmlFragment("document"), byBlockId);
1028
- return byBlockId;
643
+ function createBlockContainer(block) {
644
+ const blockContainer = new Y2.XmlElement("blockContainer");
645
+ const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;
646
+ blockContainer.setAttribute("id", block.id);
647
+ blockContainer.setAttribute("textColor", rawTextColor || "default");
648
+ blockContainer.setAttribute("backgroundColor", rawBackgroundColor || "default");
649
+ const blockContent = new Y2.XmlElement(block.type);
650
+ for (const [key, value] of Object.entries(contentProps)) {
651
+ if (value !== "") {
652
+ blockContent.setAttribute(key, value);
653
+ }
654
+ }
655
+ blockContainer.insert(0, [blockContent]);
656
+ return blockContainer;
1029
657
  }
1030
- function asRecord(value) {
1031
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
658
+ function appendBlockToGroup(blockGroup, block) {
659
+ const container = createBlockContainer(block);
660
+ blockGroup.insert(blockGroup.length, [container]);
1032
661
  }
1033
- function collectLegacyBlockProps(parent, out) {
1034
- for (let index = 0; index < parent.length; index += 1) {
1035
- const child = parent.get(index);
1036
- if (!(child instanceof Y2.XmlElement)) continue;
1037
- if (child.nodeName === "blockContainer") readContainerProps(child, out);
1038
- collectLegacyBlockProps(child, out);
662
+ function getOrCreateDocumentBlockGroup(fragment) {
663
+ if (fragment.length === 0) {
664
+ const blockGroup = new Y2.XmlElement("blockGroup");
665
+ fragment.insert(0, [blockGroup]);
666
+ return blockGroup;
667
+ }
668
+ if (fragment.length === 1) {
669
+ const rootNode = fragment.get(0);
670
+ if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
671
+ return rootNode;
672
+ }
1039
673
  }
674
+ throw new Error("Unexpected BlockNote document shape in XmlFragment. Expected a single top-level blockGroup node.");
1040
675
  }
1041
- function readContainerProps(container, out) {
1042
- const attrs = asRecord(container.getAttribute("attrs"));
1043
- const directId = container.getAttribute("id");
1044
- const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
1045
- if (!blockId) return;
1046
- const props = {};
1047
- const addAll = (source) => {
1048
- for (const [key, value] of Object.entries(source ?? {})) {
1049
- if (typeof value === "string" && value !== "") props[key] = value;
676
+ function getExistingBlockGroup(fragment) {
677
+ if (fragment.length === 0) return null;
678
+ if (fragment.length === 1) {
679
+ const rootNode = fragment.get(0);
680
+ if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
681
+ return rootNode;
1050
682
  }
683
+ }
684
+ return null;
685
+ }
686
+
687
+ // src/core/lib/flowCompiler/authoring.ts
688
+ function readFlowDocument(yDoc, runId) {
689
+ const compiled = readCompiledFlowFromYDoc(yDoc);
690
+ if (!compiled) return null;
691
+ const propsByBlockId = /* @__PURE__ */ new Map();
692
+ for (const block of readBlocksFromFragment(yDoc.getXmlFragment("document"))) {
693
+ propsByBlockId.set(block.id, block.props);
694
+ }
695
+ const resolvedRunId = resolveRunIdForRead(yDoc, runId);
696
+ const nodePropsAreAuthoritative = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
697
+ const nodes = compiled.order.filter((nodeId) => compiled.nodes[nodeId]).map((nodeId) => {
698
+ const node = compiled.nodes[nodeId];
699
+ const projectedProps = propsByBlockId.get(node.blockId) ?? {};
700
+ const props = nodePropsAreAuthoritative && Object.keys(node.props ?? {}).length > 0 ? { ...node.props } : projectedProps;
701
+ const runtime = resolvedRunId ? readActionState(yDoc, resolvedRunId, node.blockId) : {};
702
+ return {
703
+ nodeId,
704
+ blockId: node.blockId,
705
+ can: node.can,
706
+ with: node.with,
707
+ title: props.title ?? node.title,
708
+ description: props.description ?? node.description,
709
+ props,
710
+ runtime
711
+ };
712
+ });
713
+ return {
714
+ meta: compiled.meta,
715
+ order: compiled.order,
716
+ edges: compiled.edges,
717
+ blockIndex: compiled.blockIndex,
718
+ nodes
1051
719
  };
1052
- addAll(asRecord(attrs?.props));
1053
- const content = container.get(0);
1054
- if (content instanceof Y2.XmlElement && content.nodeName !== "blockGroup") addAll(content.getAttributes());
1055
- const textColor = container.getAttribute("textColor");
1056
- if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
1057
- const backgroundColor = container.getAttribute("backgroundColor");
1058
- if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
1059
- if (Object.keys(props).length > 0) out.set(blockId, props);
1060
720
  }
1061
- function adoptDraftShape(yDoc) {
1062
- const meta = yDoc.getMap("qi.flow.meta");
1063
- if (meta.get("draftSchemaVersion") === 1) return false;
1064
- const nodes = yDoc.getMap("qi.flow.nodes");
1065
- if (nodes.size === 0) return false;
1066
- const propsByBlockId = legacyPropsByBlockId(yDoc);
721
+ function addFlowNode(yDoc, opts) {
722
+ const action = getAction(opts.type);
723
+ if (!action) return null;
724
+ const nodeId = opts.nodeId ?? `node_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
725
+ const blockId = opts.blockId ?? `flow_block_${nodeId}`;
726
+ if (yDoc.getMap("qi.flow.nodes").has(nodeId) || [...yDoc.getMap("qi.flow.blockIndex").values()].includes(blockId)) return null;
727
+ const flowId = yDoc.getMap("qi.flow.meta").get("flowId") || "";
728
+ const withUri = flowId ? `ixo:flow:${flowId}:${nodeId}` : `ixo:flow:${nodeId}`;
729
+ const can = action.can ?? "";
730
+ const title = opts.title || can || action.type;
731
+ const cap = { id: nodeId, can, with: withUri, title, nb: {} };
732
+ const props = { ...compileBlockProps(cap, action.type), triggerMode: "manual", ...opts.props ?? {} };
733
+ const node = {
734
+ id: nodeId,
735
+ blockId,
736
+ can,
737
+ with: withUri,
738
+ registryType: action.type,
739
+ title,
740
+ description: "",
741
+ props
742
+ };
1067
743
  yDoc.transact(() => {
1068
- for (const value of nodes.values()) {
1069
- if (!(value instanceof Y2.Map)) continue;
1070
- const existing = value.get("props");
1071
- if (existing && typeof existing === "object" && Object.keys(existing).length > 0) continue;
1072
- const blockId = value.get("blockId");
1073
- const props = typeof blockId === "string" ? propsByBlockId.get(blockId) : void 0;
1074
- if (props && Object.keys(props).length > 0) value.set("props", { ...props });
744
+ if (opts.beforeBlockId) insertCompiledBlockIntoFragment(yDoc.getXmlFragment("document"), { id: blockId, type: COMPILED_BLOCK_TYPE, props }, opts.beforeBlockId);
745
+ else writeCompiledBlocksToFragment(yDoc.getXmlFragment("document"), [{ id: blockId, type: COMPILED_BLOCK_TYPE, props }]);
746
+ yDoc.getMap("qi.flow.nodes").set(nodeId, createYMapFromNode(node));
747
+ yDoc.getMap("qi.flow.blockIndex").set(nodeId, blockId);
748
+ const order = yDoc.getArray("qi.flow.order");
749
+ const beforeNodeId = opts.beforeBlockId ? findNodeIdForBlock(yDoc, opts.beforeBlockId) : void 0;
750
+ const beforeIdx = beforeNodeId ? order.toArray().indexOf(beforeNodeId) : -1;
751
+ if (beforeIdx >= 0) {
752
+ order.insert(beforeIdx, [nodeId]);
753
+ } else if (opts.afterNodeId) {
754
+ const idx = order.toArray().indexOf(opts.afterNodeId);
755
+ if (idx >= 0) order.insert(idx + 1, [nodeId]);
756
+ else order.push([nodeId]);
757
+ } else {
758
+ order.push([nodeId]);
1075
759
  }
1076
- meta.set("draftSchemaVersion", 1);
760
+ advanceDraftRevision(yDoc);
1077
761
  });
1078
- return true;
762
+ return { nodeId, blockId };
1079
763
  }
1080
- function hydrateYDocFromCompiledFlow(yDoc, compiled) {
764
+ function setBlockProps(yDoc, blockId, partial) {
765
+ const fragment = yDoc.getXmlFragment("document");
766
+ const existing = readBlocksFromFragment(fragment).find((b) => b.id === blockId);
767
+ if (!existing) return false;
768
+ const nodeId = findNodeIdForBlock(yDoc, blockId);
769
+ const node = nodeId ? yDoc.getMap("qi.flow.nodes").get(nodeId) : void 0;
770
+ const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
771
+ const canonicalProps = isYMapLike(node) ? node.get("props") : void 0;
772
+ const baseline = isVNextDraft && canonicalProps ? canonicalProps : existing.props;
773
+ const merged = { ...baseline, ...partial };
774
+ let ok = false;
1081
775
  yDoc.transact(() => {
1082
- const flowMeta = yDoc.getMap("qi.flow.meta");
1083
- for (const [key, value] of Object.entries(compiled.meta)) {
1084
- if (value !== void 0) {
1085
- flowMeta.set(key, value);
776
+ ok = replaceBlockInFragment(fragment, { id: blockId, type: existing.type, props: merged });
777
+ if (isYMapLike(node)) {
778
+ node.set("props", { ...merged });
779
+ if ("title" in partial) node.set("title", merged.title ?? "");
780
+ if ("description" in partial) node.set("description", merged.description ?? "");
781
+ if ("authorisedActors" in partial || "parentCapability" in partial) {
782
+ const actor = actorFromProps(merged);
783
+ if (actor) node.set("actor", actor);
784
+ else node.delete("actor");
1086
785
  }
1087
786
  }
1088
- const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
1089
- flowMeta.set("draftSchemaVersion", 1);
1090
- flowMeta.set("draftRevision", draftRevision);
1091
- const flowNodes = yDoc.getMap("qi.flow.nodes");
1092
- for (const [nodeId, node] of Object.entries(compiled.nodes)) {
1093
- flowNodes.set(nodeId, createYMapFromNode(node));
1094
- }
1095
- const flowEdges = yDoc.getMap("qi.flow.edges");
1096
- for (const edge of compiled.edges) {
1097
- const yEdge = new Y2.Map();
1098
- yEdge.set("id", edge.id);
1099
- yEdge.set("source", edge.source);
1100
- yEdge.set("target", edge.target);
1101
- yEdge.set("kind", edge.kind);
1102
- if (edge.condition) yEdge.set("condition", edge.condition);
1103
- flowEdges.set(edge.id, yEdge);
1104
- }
1105
- const flowOrder = yDoc.getArray("qi.flow.order");
1106
- for (const nodeId of compiled.order) {
1107
- flowOrder.push([nodeId]);
1108
- }
1109
- const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1110
- for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
1111
- flowBlockIndex.set(nodeId, blockId);
1112
- }
1113
- writeExecutionMeta(yDoc);
787
+ advanceDraftRevision(yDoc);
1114
788
  });
789
+ return ok;
1115
790
  }
1116
- function clearFlowState(yDoc) {
791
+ function syncFlowNodePropsFromProjection(yDoc, blockId, partial, legacyBaseline = {}) {
792
+ const nodeId = findNodeIdForBlock(yDoc, blockId);
793
+ if (!nodeId) return false;
794
+ const node = yDoc.getMap("qi.flow.nodes").get(nodeId);
795
+ if (!isYMapLike(node)) return false;
796
+ const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
797
+ const projectedBaseline = readBlocksFromFragment(yDoc.getXmlFragment("document")).find((block) => block.id === blockId)?.props;
798
+ const nodeProps = node.get("props");
799
+ const baseline = isVNextDraft ? nodeProps ?? legacyBaseline : projectedBaseline ?? legacyBaseline;
800
+ if (!isVNextDraft && !nodeProps && Object.keys(baseline).length === 0) return false;
1117
801
  yDoc.transact(() => {
1118
- const flowMeta = yDoc.getMap("qi.flow.meta");
1119
- flowMeta.forEach((_, key) => flowMeta.delete(key));
1120
- const flowNodes = yDoc.getMap("qi.flow.nodes");
1121
- flowNodes.forEach((_, key) => flowNodes.delete(key));
1122
- const flowEdges = yDoc.getMap("qi.flow.edges");
1123
- flowEdges.forEach((_, key) => flowEdges.delete(key));
1124
- const flowOrder = yDoc.getArray("qi.flow.order");
1125
- if (flowOrder.length > 0) {
1126
- flowOrder.delete(0, flowOrder.length);
802
+ const merged = { ...baseline, ...partial };
803
+ node.set("props", merged);
804
+ if ("title" in partial) node.set("title", merged.title ?? "");
805
+ if ("description" in partial) node.set("description", merged.description ?? "");
806
+ if ("authorisedActors" in partial || "parentCapability" in partial) {
807
+ const actor = actorFromProps(merged);
808
+ if (actor) node.set("actor", actor);
809
+ else node.delete("actor");
1127
810
  }
1128
- const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1129
- flowBlockIndex.forEach((_, key) => flowBlockIndex.delete(key));
811
+ if (isVNextDraft) advanceDraftRevision(yDoc);
1130
812
  });
813
+ return true;
1131
814
  }
1132
- function hydrateYDocFromMergeResult(yDoc, mergeResult) {
1133
- const { merged, added, replaced } = mergeResult;
815
+ function auditFlowProjections(yDoc) {
816
+ const projected = new Map(readBlocksFromFragment(yDoc.getXmlFragment("document")).map((block) => [block.id, block.props]));
817
+ const drift = [];
818
+ yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
819
+ if (!isYMapLike(value)) return;
820
+ const blockId = String(value.get("blockId") ?? "");
821
+ const canonical = value.get("props") ?? {};
822
+ const projection = projected.get(blockId);
823
+ if (!projection) drift.push({ nodeId, blockId, kind: "missing_block" });
824
+ else if (stableProps(canonical) !== stableProps(projection)) drift.push({ nodeId, blockId, kind: "props_mismatch" });
825
+ });
826
+ return drift.sort((left, right) => left.nodeId.localeCompare(right.nodeId));
827
+ }
828
+ function repairFlowProjections(yDoc) {
829
+ const before = auditFlowProjections(yDoc);
830
+ if (before.length === 0) return before;
831
+ const fragment = yDoc.getXmlFragment("document");
832
+ const projected = new Map(readBlocksFromFragment(fragment).map((block) => [block.id, block]));
833
+ const orderedNodeIds = yDoc.getArray("qi.flow.order").toArray();
1134
834
  yDoc.transact(() => {
1135
- const flowMeta = yDoc.getMap("qi.flow.meta");
1136
- for (const [key, value] of Object.entries(merged.meta)) {
1137
- if (value !== void 0) {
1138
- flowMeta.set(key, value);
835
+ for (const item of before) {
836
+ const node = yDoc.getMap("qi.flow.nodes").get(item.nodeId);
837
+ if (!isYMapLike(node)) continue;
838
+ const props = node.get("props") ?? {};
839
+ const block = projected.get(item.blockId);
840
+ if (block) {
841
+ replaceBlockInFragment(fragment, { ...block, props });
842
+ continue;
1139
843
  }
844
+ const nodeIndex = orderedNodeIds.indexOf(item.nodeId);
845
+ const nextProjectedBlockId = orderedNodeIds.slice(nodeIndex + 1).find((candidateNodeId) => {
846
+ const candidate = yDoc.getMap("qi.flow.nodes").get(candidateNodeId);
847
+ if (!isYMapLike(candidate)) return false;
848
+ return projected.has(String(candidate.get("blockId") ?? ""));
849
+ });
850
+ const nextNode = nextProjectedBlockId ? yDoc.getMap("qi.flow.nodes").get(nextProjectedBlockId) : void 0;
851
+ const beforeBlockId = isYMapLike(nextNode) ? String(nextNode.get("blockId") ?? "") : void 0;
852
+ insertCompiledBlockIntoFragment(fragment, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props }, beforeBlockId);
853
+ projected.set(item.blockId, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props });
1140
854
  }
1141
- const draftRevision = nextDraftRevision(yDoc, flowMeta.get("draftRevision"));
1142
- flowMeta.set("draftSchemaVersion", 1);
1143
- flowMeta.set("draftRevision", draftRevision);
1144
- const flowNodes = yDoc.getMap("qi.flow.nodes");
1145
- for (const nodeId of replaced) {
1146
- flowNodes.delete(nodeId);
1147
- flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
1148
- }
1149
- for (const nodeId of added) {
1150
- flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));
1151
- }
1152
- const flowEdges = yDoc.getMap("qi.flow.edges");
1153
- flowEdges.forEach((_, key) => flowEdges.delete(key));
1154
- for (const edge of merged.edges) {
1155
- const yEdge = new Y2.Map();
1156
- yEdge.set("id", edge.id);
1157
- yEdge.set("source", edge.source);
1158
- yEdge.set("target", edge.target);
1159
- yEdge.set("kind", edge.kind);
1160
- if (edge.condition) yEdge.set("condition", edge.condition);
1161
- flowEdges.set(edge.id, yEdge);
855
+ yDoc.getMap("qi.flow.projections").set("document", {
856
+ draftRevision: Number(yDoc.getMap("qi.flow.meta").get("draftRevision") ?? 0),
857
+ repairedAt: (/* @__PURE__ */ new Date()).toISOString()
858
+ });
859
+ });
860
+ return before;
861
+ }
862
+ function removeFlowNode(yDoc, nodeId, runId) {
863
+ const doc = readFlowDocument(yDoc, resolveRunIdForRead(yDoc, runId));
864
+ if (!doc) return { ok: false, referencedBy: [] };
865
+ const target = doc.nodes.find((n) => n.nodeId === nodeId);
866
+ if (!target) return { ok: false, referencedBy: [] };
867
+ const referencedBy = doc.nodes.filter((n) => n.nodeId !== nodeId && nodeReferences(n, nodeId, target.blockId)).map((n) => n.nodeId);
868
+ if (referencedBy.length > 0) return { ok: false, referencedBy };
869
+ const blockId = target.blockId;
870
+ yDoc.transact(() => {
871
+ removeBlockFromFragment(yDoc.getXmlFragment("document"), blockId);
872
+ yDoc.getMap("qi.flow.nodes").delete(nodeId);
873
+ yDoc.getMap("qi.flow.blockIndex").delete(nodeId);
874
+ const order = yDoc.getArray("qi.flow.order");
875
+ const idx = order.toArray().indexOf(nodeId);
876
+ if (idx >= 0) order.delete(idx, 1);
877
+ const edges = yDoc.getMap("qi.flow.edges");
878
+ for (const key of [...edges.keys()]) {
879
+ const e = edges.get(key);
880
+ if (isYMapLike(e) && (e.get("source") === nodeId || e.get("target") === nodeId)) edges.delete(key);
1162
881
  }
1163
- const flowOrder = yDoc.getArray("qi.flow.order");
1164
- if (flowOrder.length > 0) {
1165
- flowOrder.delete(0, flowOrder.length);
882
+ advanceDraftRevision(yDoc);
883
+ });
884
+ return { ok: true };
885
+ }
886
+ function reorderFlowNodes(yDoc, order) {
887
+ const orderArr = yDoc.getArray("qi.flow.order");
888
+ const current = orderArr.toArray();
889
+ if (order.length !== current.length) return false;
890
+ if (new Set(order).size !== order.length) return false;
891
+ const currentSet = new Set(current);
892
+ if (!order.every((id) => currentSet.has(id))) return false;
893
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
894
+ const fragment = yDoc.getXmlFragment("document");
895
+ yDoc.transact(() => {
896
+ orderArr.delete(0, orderArr.length);
897
+ orderArr.push(order);
898
+ if (!fragmentHasContentBlocks(fragment)) {
899
+ const blocks = readBlocksFromFragment(fragment);
900
+ const byId = new Map(blocks.map((b) => [b.id, b]));
901
+ const orderedIds = order.map((nid) => blockIndex.get(nid)).filter((id) => !!id);
902
+ const ordered = orderedIds.map((id) => byId.get(id)).filter((b) => !!b);
903
+ const extras = blocks.filter((b) => !orderedIds.includes(b.id));
904
+ removeAllFlowBlocks(fragment);
905
+ writeCompiledBlocksToFragment(fragment, [...ordered, ...extras]);
1166
906
  }
1167
- for (const nodeId of merged.order) {
1168
- flowOrder.push([nodeId]);
907
+ advanceDraftRevision(yDoc);
908
+ });
909
+ return true;
910
+ }
911
+ function swapFlowBlocks(yDoc, blockIdA, blockIdB) {
912
+ const fragment = yDoc.getXmlFragment("document");
913
+ let ok = false;
914
+ yDoc.transact(() => {
915
+ ok = swapBlocksInFragment(fragment, blockIdA, blockIdB);
916
+ if (!ok) return;
917
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
918
+ let nodeA;
919
+ let nodeB;
920
+ for (const [nodeId, bId] of blockIndex.entries()) {
921
+ if (bId === blockIdA) nodeA = nodeId;
922
+ else if (bId === blockIdB) nodeB = nodeId;
1169
923
  }
1170
- const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1171
- for (const nodeId of [...added, ...replaced]) {
1172
- flowBlockIndex.set(nodeId, merged.blockIndex[nodeId]);
924
+ if (nodeA && nodeB) {
925
+ const order = yDoc.getArray("qi.flow.order");
926
+ const arr = order.toArray();
927
+ const ia = arr.indexOf(nodeA);
928
+ const ib = arr.indexOf(nodeB);
929
+ if (ia >= 0 && ib >= 0) {
930
+ [arr[ia], arr[ib]] = [arr[ib], arr[ia]];
931
+ order.delete(0, order.length);
932
+ order.push(arr);
933
+ }
1173
934
  }
1174
- writeExecutionMeta(yDoc);
935
+ advanceDraftRevision(yDoc);
1175
936
  });
937
+ return ok;
1176
938
  }
1177
- function initializeRuntime(yDoc, compiled, runId) {
1178
- const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
1179
- if (!resolvedRunId) return;
1180
- yDoc.transact(() => {
1181
- for (const nodeId of compiled.order) {
1182
- const blockId = compiled.blockIndex[nodeId];
1183
- if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
1184
- }
1185
- });
939
+ function updateNodeRuntime(yDoc, blockId, partial, runId) {
940
+ writeActionState(yDoc, resolveRunIdForExecution(yDoc, runId), blockId, partial);
1186
941
  }
1187
- function initializeRuntimeForNodes(yDoc, compiled, nodeIds, runId) {
1188
- const resolvedRunId = runId ?? resolveActiveRunId(yDoc);
1189
- if (!resolvedRunId) return;
1190
- yDoc.transact(() => {
1191
- for (const nodeId of nodeIds) {
1192
- const blockId = compiled.blockIndex[nodeId];
1193
- if (blockId) resetActionState(yDoc, resolvedRunId, blockId);
1194
- }
1195
- });
942
+ function resetStepRuntime(yDoc, blockId, runId) {
943
+ updateNodeRuntime(yDoc, blockId, { state: "idle", error: void 0, output: {} }, runId);
1196
944
  }
1197
- function createYMapFromNode(node) {
1198
- const yNode = new Y2.Map();
1199
- yNode.set("id", node.id);
1200
- yNode.set("blockId", node.blockId);
1201
- yNode.set("can", node.can);
1202
- yNode.set("with", node.with);
1203
- yNode.set("registryType", node.registryType);
1204
- yNode.set("executionOwner", getAction(node.registryType)?.executionOwner ?? "agent");
1205
- yNode.set("title", node.title);
1206
- yNode.set("description", node.description);
1207
- yNode.set("props", { ...node.props });
1208
- const contract = executionContract(node);
1209
- if (contract) yNode.set("actionContract", contract);
1210
- if (node.phase) yNode.set("phase", node.phase);
1211
- if (node.parallelGroup) yNode.set("parallelGroup", node.parallelGroup);
1212
- if (node.actor) yNode.set("actor", node.actor);
1213
- return yNode;
945
+ function setFormAnswers(yDoc, blockId, answers, runId) {
946
+ const resolvedRunId = resolveRunIdForExecution(yDoc, runId);
947
+ const base = readActionState(yDoc, resolvedRunId, blockId);
948
+ const output = base.output && typeof base.output === "object" ? base.output : {};
949
+ const form = output.form && typeof output.form === "object" ? output.form : {};
950
+ writeActionState(yDoc, resolvedRunId, blockId, { output: { ...output, form: { ...form, answers: JSON.stringify(answers) } } });
1214
951
  }
1215
-
1216
- // src/core/lib/flowCompiler/documentFragment.ts
1217
- import * as Y3 from "yjs";
1218
- function writeCompiledBlocksToFragment(fragment, blocks) {
1219
- const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
1220
- for (const block of blocks) {
1221
- appendBlockToGroup(documentBlockGroup, block);
952
+ function safeParseJson(value, fallback) {
953
+ if (typeof value !== "string" || value.length === 0) return fallback;
954
+ try {
955
+ return JSON.parse(value);
956
+ } catch {
957
+ return fallback;
1222
958
  }
1223
959
  }
1224
- function insertCompiledBlockIntoFragment(fragment, block, beforeBlockId) {
1225
- const blockGroup = getOrCreateDocumentBlockGroup(fragment);
1226
- if (beforeBlockId) {
1227
- for (let index = 0; index < blockGroup.length; index += 1) {
1228
- const candidate = blockGroup.get(index);
1229
- if (isYXmlElementLike(candidate) && candidate.getAttribute("id") === beforeBlockId) {
1230
- blockGroup.insert(index, [createBlockContainer(block)]);
1231
- return;
1232
- }
1233
- }
1234
- }
1235
- appendBlockToGroup(blockGroup, block);
960
+ function advanceDraftRevision(yDoc) {
961
+ const meta = yDoc.getMap("qi.flow.meta");
962
+ const current = Number(meta.get("draftRevision") ?? 0);
963
+ if (meta.get("draftSchemaVersion") !== 1) return current;
964
+ const next = current + 1;
965
+ meta.set("draftRevision", next);
966
+ meta.set(
967
+ "definitionDigest",
968
+ sha256Digest({
969
+ nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
970
+ edges: yDoc.getMap("qi.flow.edges").toJSON(),
971
+ order: yDoc.getArray("qi.flow.order").toArray()
972
+ })
973
+ );
974
+ meta.set("executionSchemaVersion", 3);
975
+ meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
976
+ return next;
1236
977
  }
1237
- function removeAllFlowBlocks(fragment) {
1238
- const blockGroup = getExistingBlockGroup(fragment);
1239
- if (!blockGroup) return;
1240
- while (blockGroup.length > 0) {
1241
- blockGroup.delete(0, 1);
1242
- }
978
+ function stableProps(props) {
979
+ return JSON.stringify(
980
+ Object.fromEntries(
981
+ Object.entries(props).filter(([, value]) => value !== "").sort(([left], [right]) => left.localeCompare(right))
982
+ )
983
+ );
1243
984
  }
1244
- function removeBlockFromFragment(fragment, blockId) {
1245
- const blockGroup = getExistingBlockGroup(fragment);
1246
- if (!blockGroup) return false;
1247
- for (let i = 0; i < blockGroup.length; i++) {
1248
- const container = blockGroup.get(i);
1249
- if (isYXmlElementLike(container) && container.getAttribute("id") === blockId) {
1250
- blockGroup.delete(i, 1);
1251
- return true;
1252
- }
985
+ function findNodeIdForBlock(yDoc, blockId) {
986
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
987
+ for (const [nodeId, bId] of blockIndex.entries()) {
988
+ if (bId === blockId) return nodeId;
1253
989
  }
1254
- return false;
990
+ return void 0;
1255
991
  }
1256
- function replaceBlockInFragment(fragment, block) {
1257
- const blockGroup = getExistingBlockGroup(fragment);
1258
- if (!blockGroup) return false;
1259
- for (let i = 0; i < blockGroup.length; i++) {
1260
- const container = blockGroup.get(i);
1261
- if (isYXmlElementLike(container) && container.getAttribute("id") === block.id) {
1262
- blockGroup.delete(i, 1);
1263
- const newContainer = createBlockContainer(block);
1264
- blockGroup.insert(i, [newContainer]);
1265
- return true;
1266
- }
1267
- }
992
+ function actorFromProps(props) {
993
+ const authorisedActors = safeParseJson(props.authorisedActors, void 0);
994
+ const parentCapability = props.parentCapability && props.parentCapability.length > 0 ? props.parentCapability : void 0;
995
+ const hasActors = Array.isArray(authorisedActors) && authorisedActors.length > 0;
996
+ if (!hasActors && !parentCapability) return void 0;
997
+ const actor = {};
998
+ if (hasActors) actor.authorisedActors = authorisedActors;
999
+ if (parentCapability) actor.parentCapability = parentCapability;
1000
+ return actor;
1001
+ }
1002
+ function nodeReferences(node, nodeId, blockId) {
1003
+ const trigger = safeParseJson(node.props.trigger, void 0);
1004
+ if (trigger?.sourceBlockId === nodeId || trigger?.sourceBlockId === blockId) return true;
1005
+ if (Array.isArray(trigger?.sources) && trigger.sources.some((s) => s?.sourceBlockId === nodeId || s?.sourceBlockId === blockId)) return true;
1006
+ const cond = safeParseJson(node.props.conditions, void 0);
1007
+ if (Array.isArray(cond?.conditions) && cond.conditions.some((c) => c?.sourceBlockId === blockId)) return true;
1008
+ const inputs = typeof node.props.inputs === "string" ? node.props.inputs : "";
1009
+ if (inputs.includes(`${nodeId}.output`)) return true;
1268
1010
  return false;
1269
1011
  }
1270
- function swapBlocksInFragment(fragment, idA, idB) {
1271
- const blockGroup = getExistingBlockGroup(fragment);
1272
- if (!blockGroup) return false;
1273
- let ia = -1;
1274
- let ib = -1;
1275
- for (let i = 0; i < blockGroup.length; i++) {
1276
- const container = blockGroup.get(i);
1277
- if (isYXmlElementLike(container)) {
1278
- const id = container.getAttribute("id");
1279
- if (id === idA) ia = i;
1280
- else if (id === idB) ib = i;
1281
- }
1012
+ function fragmentHasContentBlocks(fragment) {
1013
+ if (fragment.length === 0) return false;
1014
+ const root = fragment.get(0);
1015
+ if (!isYXmlElementLike(root) || root.nodeName !== "blockGroup") return false;
1016
+ for (let i = 0; i < root.length; i++) {
1017
+ const container = root.get(i);
1018
+ if (!isYXmlElementLike(container)) continue;
1019
+ const content = container.get(0);
1020
+ if (isYXmlElementLike(content) && content.length > 0) return true;
1282
1021
  }
1283
- if (ia < 0 || ib < 0 || ia === ib) return false;
1284
- const lo = Math.min(ia, ib);
1285
- const hi = Math.max(ia, ib);
1286
- const loClone = blockGroup.get(lo).clone();
1287
- const hiClone = blockGroup.get(hi).clone();
1288
- blockGroup.delete(hi, 1);
1289
- blockGroup.insert(hi, [loClone]);
1290
- blockGroup.delete(lo, 1);
1291
- blockGroup.insert(lo, [hiClone]);
1292
- return true;
1022
+ return false;
1293
1023
  }
1294
- function applyMergeResultToFragment(fragment, mergeResult) {
1295
- const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
1296
- const blockByNodeId = /* @__PURE__ */ new Map();
1297
- for (const block of mergeResult.merged.blocks) {
1298
- for (const [nodeId, blockId] of Object.entries(mergeResult.merged.blockIndex)) {
1299
- if (blockId === block.id) {
1300
- blockByNodeId.set(nodeId, block);
1301
- break;
1024
+
1025
+ // src/core/lib/flowCompiler/stepListMigration.ts
1026
+ import * as Y3 from "yjs";
1027
+ function actionBlocksInOrder(yDoc) {
1028
+ const propsByBlockId = legacyPropsByBlockId(yDoc);
1029
+ const blocks = [];
1030
+ const walk = (parent) => {
1031
+ for (let index = 0; index < parent.length; index += 1) {
1032
+ const child = parent.get(index);
1033
+ if (!(child instanceof Y3.XmlElement)) continue;
1034
+ if (child.nodeName === "blockContainer") {
1035
+ const content = child.get(0);
1036
+ const attrs = child.getAttribute("attrs");
1037
+ const directId = child.getAttribute("id");
1038
+ const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
1039
+ if (blockId && content instanceof Y3.XmlElement && content.nodeName === COMPILED_BLOCK_TYPE) {
1040
+ blocks.push({ blockId, props: propsByBlockId.get(blockId) ?? {} });
1041
+ }
1302
1042
  }
1043
+ walk(child);
1303
1044
  }
1304
- }
1305
- for (const nodeId of mergeResult.replaced) {
1306
- const block = blockByNodeId.get(nodeId);
1307
- if (block) {
1308
- replaceBlockInFragment(fragment, block);
1309
- }
1310
- }
1311
- for (const nodeId of mergeResult.added) {
1312
- const block = blockByNodeId.get(nodeId);
1313
- if (block) {
1314
- appendBlockToGroup(documentBlockGroup, block);
1315
- }
1316
- }
1317
- }
1318
- function readBlocksFromFragment(fragment) {
1319
- const blockGroup = getExistingBlockGroup(fragment);
1320
- if (!blockGroup) return [];
1321
- const blocks = [];
1322
- for (let i = 0; i < blockGroup.length; i++) {
1323
- const container = blockGroup.get(i);
1324
- if (!isYXmlElementLike(container) || container.nodeName !== "blockContainer") continue;
1325
- const id = container.getAttribute("id");
1326
- if (typeof id !== "string" || id.length === 0) continue;
1327
- const content = container.get(0);
1328
- if (!isYXmlElementLike(content)) continue;
1329
- const props = { ...content.getAttributes() };
1330
- const textColor = container.getAttribute("textColor");
1331
- if (typeof textColor === "string" && textColor !== "default") props.textColor = textColor;
1332
- const backgroundColor = container.getAttribute("backgroundColor");
1333
- if (typeof backgroundColor === "string" && backgroundColor !== "default") props.backgroundColor = backgroundColor;
1334
- blocks.push({ id, type: content.nodeName, props });
1335
- }
1045
+ };
1046
+ walk(yDoc.getXmlFragment("document"));
1336
1047
  return blocks;
1337
1048
  }
1338
- function createBlockContainer(block) {
1339
- const blockContainer = new Y3.XmlElement("blockContainer");
1340
- const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;
1341
- blockContainer.setAttribute("id", block.id);
1342
- blockContainer.setAttribute("textColor", rawTextColor || "default");
1343
- blockContainer.setAttribute("backgroundColor", rawBackgroundColor || "default");
1344
- const blockContent = new Y3.XmlElement(block.type);
1345
- for (const [key, value] of Object.entries(contentProps)) {
1346
- if (value !== "") {
1347
- blockContent.setAttribute(key, value);
1049
+ function listedBlockIds(yDoc) {
1050
+ const listed = /* @__PURE__ */ new Set();
1051
+ yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
1052
+ listed.add(nodeId);
1053
+ const blockId = value instanceof Y3.Map ? value.get("blockId") : void 0;
1054
+ if (typeof blockId === "string" && blockId) listed.add(blockId);
1055
+ });
1056
+ yDoc.getMap("qi.flow.blockIndex").forEach((blockId) => listed.add(blockId));
1057
+ return listed;
1058
+ }
1059
+ function governedByStepList(yDoc) {
1060
+ return yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1 || yDoc.getMap("qi.flow.nodes").size === 0;
1061
+ }
1062
+ function findUnlistedActionBlocks(yDoc) {
1063
+ if (!governedByStepList(yDoc)) return [];
1064
+ const listed = listedBlockIds(yDoc);
1065
+ return actionBlocksInOrder(yDoc).filter((block) => !listed.has(block.blockId)).map((block) => {
1066
+ const actionType = block.props.actionType ?? "";
1067
+ return { blockId: block.blockId, actionType, known: Boolean(actionType && getAction(actionType)) };
1068
+ });
1069
+ }
1070
+ function flowSegment(yDoc) {
1071
+ const docId = yDoc.getMap("root").get("doc_id");
1072
+ if (typeof docId === "string" && docId) return `ixo:flow:${docId}`;
1073
+ const flowId = yDoc.getMap("qi.flow.meta").get("flowId");
1074
+ return typeof flowId === "string" && flowId ? `ixo:flow:${flowId}` : "ixo:flow";
1075
+ }
1076
+ function addUnlistedSteps(yDoc) {
1077
+ const unlisted = findUnlistedActionBlocks(yDoc).filter((block) => block.known);
1078
+ if (unlisted.length === 0) return [];
1079
+ const blocks = actionBlocksInOrder(yDoc);
1080
+ const propsByBlockId = new Map(blocks.map((block) => [block.blockId, block.props]));
1081
+ const flowPrefix = flowSegment(yDoc);
1082
+ const added = [];
1083
+ yDoc.transact(() => {
1084
+ const nodes = yDoc.getMap("qi.flow.nodes");
1085
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
1086
+ for (const { blockId, actionType } of unlisted) {
1087
+ const action = getAction(actionType);
1088
+ if (!action) continue;
1089
+ const props = propsByBlockId.get(blockId) ?? {};
1090
+ const resource = `${flowPrefix}:${blockId}`;
1091
+ const node = {
1092
+ id: blockId,
1093
+ blockId,
1094
+ can: action.can ?? "",
1095
+ with: resource,
1096
+ registryType: action.type,
1097
+ title: props.title || action.can || action.type,
1098
+ description: props.description ?? "",
1099
+ props: { ...props, with: resource }
1100
+ };
1101
+ nodes.set(blockId, createYMapFromNode(node));
1102
+ blockIndex.set(blockId, blockId);
1103
+ added.push(blockId);
1348
1104
  }
1349
- }
1350
- blockContainer.insert(0, [blockContent]);
1351
- return blockContainer;
1105
+ const order = yDoc.getArray("qi.flow.order");
1106
+ if (order.length > 0) {
1107
+ const nodeIdByBlock = /* @__PURE__ */ new Map();
1108
+ nodes.forEach((value, nodeId) => {
1109
+ const blockId = value instanceof Y3.Map ? value.get("blockId") : void 0;
1110
+ nodeIdByBlock.set(typeof blockId === "string" && blockId ? blockId : nodeId, nodeId);
1111
+ });
1112
+ for (const blockId of added) {
1113
+ const position = blocks.findIndex((block) => block.blockId === blockId);
1114
+ let insertAt = 0;
1115
+ for (let previous = position - 1; previous >= 0; previous -= 1) {
1116
+ const previousNode = nodeIdByBlock.get(blocks[previous].blockId);
1117
+ const index = previousNode ? order.toArray().indexOf(previousNode) : -1;
1118
+ if (index >= 0) {
1119
+ insertAt = index + 1;
1120
+ break;
1121
+ }
1122
+ }
1123
+ order.insert(insertAt, [blockId]);
1124
+ }
1125
+ }
1126
+ const meta = yDoc.getMap("qi.flow.meta");
1127
+ if (meta.get("draftSchemaVersion") !== 1) meta.set("draftSchemaVersion", 1);
1128
+ meta.delete("definitionDigest");
1129
+ ensureFlowExecutionMetadata(yDoc);
1130
+ }, "step-list-migration");
1131
+ return added;
1132
+ }
1133
+
1134
+ // src/core/lib/sharedFlowDocument.ts
1135
+ import { MatrixCRDTEventTranslator, MatrixProvider, MatrixReader } from "@ixo/matrix-crdt";
1136
+ import { Direction, Filter } from "matrix-js-sdk";
1137
+ import * as Y4 from "yjs";
1138
+
1139
+ // src/core/lib/flowDocumentCache.ts
1140
+ var DATABASE = "ixo-flow-checkpoints-v1";
1141
+ var MAX_AGE = 7 * 24 * 60 * 60 * 1e3;
1142
+ async function identity(client, roomId) {
1143
+ const token = client.getAccessToken?.();
1144
+ if (!token || !globalThis.crypto?.subtle || typeof indexedDB === "undefined") return;
1145
+ const scope = JSON.stringify([client.getHomeserverUrl(), client.getUserId(), roomId]);
1146
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${scope}\0${token}`));
1147
+ const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
1148
+ return { scope, key };
1352
1149
  }
1353
- function appendBlockToGroup(blockGroup, block) {
1354
- const container = createBlockContainer(block);
1355
- blockGroup.insert(blockGroup.length, [container]);
1150
+ async function database() {
1151
+ return new Promise((resolve, reject) => {
1152
+ const request = indexedDB.open(DATABASE, 1);
1153
+ request.onupgradeneeded = () => request.result.createObjectStore("documents");
1154
+ request.onsuccess = () => resolve(request.result);
1155
+ request.onerror = () => reject(request.error);
1156
+ request.onblocked = () => reject(new Error("Flow cache is blocked"));
1157
+ });
1356
1158
  }
1357
- function getOrCreateDocumentBlockGroup(fragment) {
1358
- if (fragment.length === 0) {
1359
- const blockGroup = new Y3.XmlElement("blockGroup");
1360
- fragment.insert(0, [blockGroup]);
1361
- return blockGroup;
1362
- }
1363
- if (fragment.length === 1) {
1364
- const rootNode = fragment.get(0);
1365
- if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
1366
- return rootNode;
1367
- }
1159
+ async function readFlowCheckpoint(client, roomId) {
1160
+ try {
1161
+ const auth = await identity(client, roomId);
1162
+ if (!auth) return;
1163
+ const db = await database();
1164
+ const record = await new Promise((resolve, reject) => {
1165
+ const transaction = db.transaction("documents", "readonly");
1166
+ const request = transaction.objectStore("documents").get(auth.scope);
1167
+ request.onsuccess = () => resolve(request.result);
1168
+ request.onerror = () => reject(request.error);
1169
+ transaction.oncomplete = () => db.close();
1170
+ transaction.onabort = () => db.close();
1171
+ });
1172
+ if (!record || Date.now() - record.savedAt > MAX_AGE) return;
1173
+ const clear = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(auth.scope) }, auth.key, record.data);
1174
+ const value = JSON.parse(new TextDecoder().decode(clear));
1175
+ if (!Array.isArray(value.update) || !value.token) return;
1176
+ return { update: new Uint8Array(value.update), token: value.token, savedAt: record.savedAt };
1177
+ } catch {
1178
+ return;
1368
1179
  }
1369
- throw new Error("Unexpected BlockNote document shape in XmlFragment. Expected a single top-level blockGroup node.");
1370
1180
  }
1371
- function getExistingBlockGroup(fragment) {
1372
- if (fragment.length === 0) return null;
1373
- if (fragment.length === 1) {
1374
- const rootNode = fragment.get(0);
1375
- if (isYXmlElementLike(rootNode) && rootNode.nodeName === "blockGroup") {
1376
- return rootNode;
1377
- }
1181
+ async function writeFlowCheckpoint(client, roomId, checkpoint) {
1182
+ try {
1183
+ if (checkpoint.update.byteLength > 8 * 1024 * 1024) return;
1184
+ const auth = await identity(client, roomId);
1185
+ if (!auth) return;
1186
+ const iv = crypto.getRandomValues(new Uint8Array(12));
1187
+ const data = await crypto.subtle.encrypt(
1188
+ { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(auth.scope) },
1189
+ auth.key,
1190
+ new TextEncoder().encode(JSON.stringify({ update: Array.from(checkpoint.update), token: checkpoint.token }))
1191
+ );
1192
+ const db = await database();
1193
+ await new Promise((resolve, reject) => {
1194
+ const transaction = db.transaction("documents", "readwrite");
1195
+ const store = transaction.objectStore("documents");
1196
+ store.put({ iv, data, savedAt: checkpoint.savedAt }, auth.scope);
1197
+ const request = store.openCursor();
1198
+ const records = [];
1199
+ request.onsuccess = () => {
1200
+ const cursor = request.result;
1201
+ if (!cursor) {
1202
+ records.sort((a, b) => b.savedAt - a.savedAt);
1203
+ for (const record of records.slice(32)) store.delete(record.key);
1204
+ return;
1205
+ }
1206
+ if (Date.now() - cursor.value.savedAt > MAX_AGE) cursor.delete();
1207
+ else records.push({ key: cursor.key, savedAt: cursor.value.savedAt });
1208
+ cursor.continue();
1209
+ };
1210
+ transaction.oncomplete = () => {
1211
+ db.close();
1212
+ resolve();
1213
+ };
1214
+ transaction.onerror = () => {
1215
+ db.close();
1216
+ reject(transaction.error);
1217
+ };
1218
+ transaction.onabort = () => {
1219
+ db.close();
1220
+ reject(transaction.error);
1221
+ };
1222
+ });
1223
+ } catch {
1224
+ return;
1378
1225
  }
1379
- return null;
1380
1226
  }
1381
1227
 
1382
- // src/core/lib/flowCompiler/readFlow.ts
1383
- function readCompiledFlowFromYDoc(yDoc) {
1384
- const flowMeta = yDoc.getMap("qi.flow.meta");
1385
- const flowNodes = yDoc.getMap("qi.flow.nodes");
1386
- const nodes = {};
1387
- flowNodes.forEach((value, nodeId) => {
1388
- if (isYMapLike(value)) {
1389
- nodes[nodeId] = yMapToFlowNode(value);
1390
- }
1391
- });
1392
- if (flowNodes.size === 0 && flowMeta.size === 0) {
1393
- return null;
1394
- }
1395
- const meta = {
1396
- flowId: flowMeta.get("flowId") || "",
1397
- title: flowMeta.get("title") || "",
1398
- goal: flowMeta.get("goal"),
1399
- version: flowMeta.get("version") || "",
1400
- // The room creator, never the doc's editable copy (see flowOwner.ts).
1401
- flowOwnerDid: flowOwnerOf(yDoc),
1402
- flowUri: flowMeta.get("flowUri"),
1403
- compiledAt: flowMeta.get("compiledAt") || "",
1404
- compiledFrom: "BaseUcanFlow"
1405
- };
1406
- const flowEdges = yDoc.getMap("qi.flow.edges");
1407
- const edges = [];
1408
- flowEdges.forEach((value) => {
1409
- if (isYMapLike(value)) {
1410
- edges.push(yMapToEdge(value));
1411
- }
1412
- });
1413
- const flowOrder = yDoc.getArray("qi.flow.order");
1414
- const order = flowOrder.toArray();
1415
- const flowBlockIndex = yDoc.getMap("qi.flow.blockIndex");
1416
- const blockIndex = {};
1417
- flowBlockIndex.forEach((value, key) => {
1418
- blockIndex[key] = value;
1419
- });
1420
- const blocks = order.filter((nodeId) => nodes[nodeId]).map((nodeId) => {
1421
- const node = nodes[nodeId];
1422
- return {
1423
- id: node.blockId,
1424
- type: COMPILED_BLOCK_TYPE,
1425
- props: { ...node.props }
1228
+ // src/core/lib/sharedFlowDocument.ts
1229
+ var sessions = /* @__PURE__ */ new WeakMap();
1230
+ var RETAIN_MS = 5 * 60 * 1e3;
1231
+ var activeLoads = 0;
1232
+ var loadQueue = [];
1233
+ function withLoadSlot(read, visible) {
1234
+ return new Promise((resolve, reject) => {
1235
+ const start = () => {
1236
+ activeLoads++;
1237
+ void read().then(resolve, reject).finally(() => {
1238
+ activeLoads--;
1239
+ loadQueue.sort((a, b) => Number(b.visible) - Number(a.visible));
1240
+ loadQueue.shift()?.start();
1241
+ });
1426
1242
  };
1243
+ if (activeLoads < 4) start();
1244
+ else loadQueue.push({ visible, start });
1427
1245
  });
1428
- return { meta, blocks, nodes, edges, order, blockIndex };
1429
- }
1430
- function yMapToFlowNode(yMap) {
1431
- return {
1432
- id: yMap.get("id") || "",
1433
- blockId: yMap.get("blockId") || "",
1434
- can: yMap.get("can") || "",
1435
- with: yMap.get("with") || "",
1436
- registryType: yMap.get("registryType") || "",
1437
- title: yMap.get("title") || "",
1438
- description: yMap.get("description") || "",
1439
- props: yMap.get("props") || {},
1440
- phase: yMap.get("phase"),
1441
- parallelGroup: yMap.get("parallelGroup"),
1442
- actor: yMap.get("actor")
1443
- };
1444
1246
  }
1445
- function yMapToEdge(yMap) {
1446
- return {
1447
- id: yMap.get("id") || "",
1448
- source: yMap.get("source") || "",
1449
- target: yMap.get("target") || "",
1450
- // Only 'trigger' edges exist. Legacy 'dependency' edges from older
1451
- // Y.Docs (before dependsOn was removed) get coerced — they'll be
1452
- // overwritten on the next compile pass.
1453
- kind: "trigger",
1454
- condition: yMap.get("condition")
1455
- };
1247
+ function syntheticSnapshot(update) {
1248
+ let binary = "";
1249
+ for (const byte of update) binary += String.fromCharCode(byte);
1250
+ return { type: "matrix-crdt.doc_snapshot", event_id: "$local-checkpoint", sender: "@local:cache", origin_server_ts: 0, content: { update: btoa(binary) } };
1456
1251
  }
1457
-
1458
- // src/core/lib/flowCompiler/mergeFlows.ts
1459
- function mergeCompiledFlows(existing, incoming, strategy) {
1460
- const added = [];
1461
- const replaced = [];
1462
- const kept = [];
1463
- const mergedNodes = {};
1464
- const mergedBlockIndex = {};
1465
- for (const [nodeId, node] of Object.entries(existing.nodes)) {
1466
- mergedNodes[nodeId] = node;
1467
- mergedBlockIndex[nodeId] = existing.blockIndex[nodeId];
1468
- }
1469
- for (const [nodeId, node] of Object.entries(incoming.nodes)) {
1470
- if (mergedNodes[nodeId]) {
1471
- if (strategy === "patch") {
1472
- mergedNodes[nodeId] = node;
1473
- mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1474
- replaced.push(nodeId);
1475
- } else {
1476
- kept.push(nodeId);
1252
+ function clientWithHistory(client, history) {
1253
+ let first = true;
1254
+ return new Proxy(client, {
1255
+ get(target, property) {
1256
+ if (property === "createMessagesRequest") {
1257
+ return async (...args) => {
1258
+ if (first && !args[1] && args[3] === Direction.Backward) {
1259
+ first = false;
1260
+ const response = await history();
1261
+ if (response) return response;
1262
+ }
1263
+ return target.createMessagesRequest(args[0], args[1], 200, args[3], args[4]);
1264
+ };
1477
1265
  }
1478
- } else {
1479
- mergedNodes[nodeId] = node;
1480
- mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1481
- added.push(nodeId);
1482
- }
1483
- }
1484
- for (const nodeId of Object.keys(existing.nodes)) {
1485
- if (!replaced.includes(nodeId)) {
1486
- kept.push(nodeId);
1487
- }
1488
- }
1489
- const edgeMap = /* @__PURE__ */ new Map();
1490
- for (const edge of [...existing.edges, ...incoming.edges]) {
1491
- if (mergedNodes[edge.source] && mergedNodes[edge.target]) {
1492
- edgeMap.set(edge.id, edge);
1493
- }
1494
- }
1495
- const edges = Array.from(edgeMap.values());
1496
- const order = Object.keys(mergedNodes);
1497
- const blocks = order.map((nodeId) => {
1498
- const node = mergedNodes[nodeId];
1499
- return {
1500
- id: node.blockId,
1501
- type: COMPILED_BLOCK_TYPE,
1502
- props: { ...node.props }
1503
- };
1266
+ const value = Reflect.get(target, property);
1267
+ return typeof value === "function" ? value.bind(target) : value;
1268
+ }
1504
1269
  });
1505
- const meta = {
1506
- ...incoming.meta,
1507
- flowId: existing.meta.flowId,
1508
- compiledAt: (/* @__PURE__ */ new Date()).toISOString()
1509
- };
1510
- return {
1511
- merged: { meta, blocks, nodes: mergedNodes, edges, order, blockIndex: mergedBlockIndex },
1512
- added,
1513
- replaced,
1514
- kept
1515
- };
1516
1270
  }
1517
-
1518
- // src/core/lib/flowCompiler/decompile.ts
1519
- function decompileToBaseUcanFlow(compiled) {
1520
- const nodeIdByBlockId = {};
1521
- for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
1522
- nodeIdByBlockId[blockId] = nodeId;
1271
+ async function readFlowDocumentHistory(client, roomId, checkpoint) {
1272
+ const room = client.getRoom(roomId);
1273
+ if (checkpoint && Date.now() - checkpoint.savedAt > 30 * 60 * 1e3 && room && !room.currentState.getStateEvents("m.room.encryption", "")) checkpoint = void 0;
1274
+ if (checkpoint) {
1275
+ try {
1276
+ Y4.decodeUpdate(checkpoint.update);
1277
+ } catch {
1278
+ checkpoint = void 0;
1279
+ }
1523
1280
  }
1524
- const capabilities = compiled.order.map((nodeId) => {
1525
- const node = compiled.nodes[nodeId];
1526
- return nodeToCapability(node, nodeIdByBlockId);
1527
- });
1528
- return {
1529
- kind: "qi.flow.base-ucan",
1530
- version: "1.0",
1531
- flowId: compiled.meta.flowId,
1532
- title: compiled.meta.title,
1533
- goal: compiled.meta.goal,
1534
- meta: {
1535
- rootIssuer: compiled.meta.flowOwnerDid || void 0,
1536
- flowUri: compiled.meta.flowUri
1537
- },
1538
- capabilities
1539
- };
1540
- }
1541
- function nodeToCapability(node, nodeIdByBlockId) {
1542
- const cap = {
1543
- id: node.id,
1544
- can: node.can,
1545
- with: node.with
1546
- };
1547
- if (node.props.inputs) {
1281
+ const translator = new MatrixCRDTEventTranslator();
1282
+ const filter = new Filter(client.getUserId() ?? void 0);
1283
+ filter.setDefinition({ room: { timeline: { types: [...translator.readEventTypes, "m.room.encrypted"] } } });
1284
+ const readerClient = clientWithHistory(client, async () => {
1285
+ let token = checkpoint?.token;
1286
+ let initial = checkpoint ? [syntheticSnapshot(checkpoint.update)] : [];
1287
+ let recent;
1288
+ if (!token) {
1289
+ const room2 = client.getRoom(roomId);
1290
+ if (!room2 || room2.currentState.getStateEvents("m.room.encryption", "")) return;
1291
+ recent = await client.createMessagesRequest(roomId, "", 200, Direction.Backward, filter);
1292
+ if (!recent.end || recent.end === recent.start || recent.chunk.some((event) => translator.isAnySnapshotEvent(event))) return recent;
1293
+ const snapshots = new Filter(client.getUserId() ?? void 0);
1294
+ snapshots.setDefinition({ room: { timeline: { types: ["matrix-crdt.doc_snapshot", "matrix-crdt.doc_snapshot_v2"] } } });
1295
+ try {
1296
+ const page = await client.createMessagesRequest(roomId, "", 1, Direction.Backward, snapshots);
1297
+ if (!page.chunk.length || !page.end) return recent;
1298
+ token = page.end;
1299
+ } catch {
1300
+ return recent;
1301
+ }
1302
+ }
1548
1303
  try {
1549
- const nb = JSON.parse(node.props.inputs);
1550
- if (nb && typeof nb === "object" && Object.keys(nb).length > 0) {
1551
- cap.nb = nb;
1304
+ for (; ; ) {
1305
+ const page = await client.createMessagesRequest(roomId, token, 200, Direction.Forward, filter);
1306
+ initial.push(...page.chunk);
1307
+ if (!page.end || page.end === token || page.chunk.length === 0) {
1308
+ return { chunk: initial.reverse(), start: page.end || token, end: void 0 };
1309
+ }
1310
+ token = page.end;
1552
1311
  }
1553
1312
  } catch {
1313
+ return recent;
1314
+ }
1315
+ });
1316
+ let reader = new MatrixReader(readerClient, roomId, translator);
1317
+ try {
1318
+ let events;
1319
+ try {
1320
+ events = await reader.getInitialDocumentUpdateEvents();
1321
+ } catch {
1322
+ reader.dispose();
1323
+ reader = new MatrixReader(
1324
+ clientWithHistory(client, async () => void 0),
1325
+ roomId,
1326
+ translator
1327
+ );
1328
+ events = await reader.getInitialDocumentUpdateEvents();
1329
+ }
1330
+ if (reader.snapshotDegradations.length) {
1331
+ reader.dispose();
1332
+ reader = new MatrixReader(
1333
+ clientWithHistory(client, async () => void 0),
1334
+ roomId,
1335
+ translator
1336
+ );
1337
+ events = await reader.getInitialDocumentUpdateEvents();
1554
1338
  }
1339
+ const updates = events.map((event) => translator.getUpdateBytes(event)).filter((update) => !!update);
1340
+ return { update: updates.length ? Y4.mergeUpdates(updates) : Y4.encodeStateAsUpdate(new Y4.Doc()), token: reader.latestToken };
1341
+ } finally {
1342
+ reader.dispose();
1555
1343
  }
1556
- if (node.parallelGroup) {
1557
- cap.parallelGroup = node.parallelGroup;
1344
+ }
1345
+ var SharedFlowDocument = class {
1346
+ constructor(client, roomId) {
1347
+ this.client = client;
1348
+ this.roomId = roomId;
1349
+ this.doc = new Y4.Doc();
1350
+ this.lastAccess = Date.now();
1351
+ this.status = "disconnected";
1352
+ this.ready = false;
1353
+ this.provider = null;
1354
+ this.listeners = /* @__PURE__ */ new Set();
1355
+ this.live = /* @__PURE__ */ new Set();
1356
+ this.attempt = 0;
1357
+ this.generation = 0;
1358
+ this.notify = () => {
1359
+ for (const listener of this.listeners) listener();
1360
+ };
1361
+ this.flush = () => {
1362
+ void this.provider?.waitForFlush().catch(() => void 0);
1363
+ };
1364
+ this.reconnect = async () => {
1365
+ clearTimeout(this.retry);
1366
+ this.attempt = 0;
1367
+ await this.stopProvider();
1368
+ await this.connect();
1369
+ };
1558
1370
  }
1559
- if (node.phase) {
1560
- cap.phase = node.phase;
1371
+ watchPageExit(enabled) {
1372
+ if (typeof window === "undefined") return;
1373
+ if (enabled) {
1374
+ window.addEventListener("pagehide", this.flush);
1375
+ window.addEventListener("beforeunload", this.flush);
1376
+ } else {
1377
+ window.removeEventListener("pagehide", this.flush);
1378
+ window.removeEventListener("beforeunload", this.flush);
1379
+ }
1561
1380
  }
1562
- if (node.actor) {
1563
- cap.actor = { ...node.actor };
1381
+ evictIfIdle() {
1382
+ if (this.listeners.size || this.pending) return false;
1383
+ this.generation++;
1384
+ clearTimeout(this.idle);
1385
+ clearTimeout(this.retry);
1386
+ clearTimeout(this.stopTimer);
1387
+ if (sessions.get(this.client)?.get(this.roomId) === this) sessions.get(this.client)?.delete(this.roomId);
1388
+ void this.stopProvider().finally(() => this.doc.destroy());
1389
+ return true;
1564
1390
  }
1565
- const ttl = {};
1566
- if (node.props.ttlAbsoluteDueDate) ttl.absoluteDueDate = node.props.ttlAbsoluteDueDate;
1567
- if (node.props.ttlFromEnablement) ttl.fromEnablement = node.props.ttlFromEnablement;
1568
- if (node.props.ttlFromCommitment) ttl.fromCommitment = node.props.ttlFromCommitment;
1569
- if (Object.keys(ttl).length > 0) {
1570
- cap.ttl = ttl;
1391
+ subscribe(listener, live = true) {
1392
+ this.lastAccess = Date.now();
1393
+ clearTimeout(this.idle);
1394
+ clearTimeout(this.stopTimer);
1395
+ this.listeners.add(listener);
1396
+ if (live) this.live.add(listener);
1397
+ void this.connect();
1398
+ return () => {
1399
+ this.listeners.delete(listener);
1400
+ this.live.delete(listener);
1401
+ if (!this.live.size && this.provider)
1402
+ this.stopTimer = setTimeout(() => {
1403
+ if (!this.live.size) void this.stopProvider();
1404
+ }, 1e3);
1405
+ if (!this.listeners.size) {
1406
+ clearTimeout(this.retry);
1407
+ this.idle = setTimeout(() => {
1408
+ this.evictIfIdle();
1409
+ }, RETAIN_MS);
1410
+ this.idle.unref?.();
1411
+ }
1412
+ };
1571
1413
  }
1572
- if (typeof node.props.trigger === "string" && node.props.trigger.length > 0) {
1573
- try {
1574
- const trigger = JSON.parse(node.props.trigger);
1575
- if (trigger && typeof trigger === "object" && typeof trigger.type === "string") {
1576
- cap.trigger = triggerToNodeIds(trigger, nodeIdByBlockId);
1414
+ connect() {
1415
+ if (this.pending) return this.pending;
1416
+ if (this.provider || this.ready && !this.live.size && this.checkpoint && Date.now() - this.checkpoint.savedAt < 3e4) return Promise.resolve();
1417
+ const generation = this.generation;
1418
+ this.status = "connecting";
1419
+ this.notify();
1420
+ this.pending = (async () => {
1421
+ await this.stopping;
1422
+ if (!this.checkpoint) {
1423
+ const membership = this.client.getRoom(this.roomId)?.getMyMembership?.();
1424
+ if (!membership || membership === "join") this.checkpoint = await readFlowCheckpoint(this.client, this.roomId);
1425
+ if (generation !== this.generation) return;
1426
+ if (this.checkpoint) {
1427
+ try {
1428
+ Y4.decodeUpdate(this.checkpoint.update);
1429
+ Y4.applyUpdate(this.doc, this.checkpoint.update, this);
1430
+ this.ready = true;
1431
+ bindFlowOwnerFromRoom(this.doc, this.client, this.roomId);
1432
+ this.notify();
1433
+ } catch {
1434
+ this.checkpoint = void 0;
1435
+ }
1436
+ }
1437
+ }
1438
+ const result = await withLoadSlot(() => readFlowDocumentHistory(this.client, this.roomId, this.checkpoint), this.live.size > 0);
1439
+ if (generation !== this.generation) return;
1440
+ Y4.applyUpdate(this.doc, result.update, this);
1441
+ this.ready = true;
1442
+ bindFlowOwnerFromRoom(this.doc, this.client, this.roomId);
1443
+ this.error = void 0;
1444
+ this.attempt = 0;
1445
+ if (result.token) this.checkpoint = { update: result.update, token: result.token, savedAt: Date.now() };
1446
+ this.status = this.live.size ? "connecting" : "connected";
1447
+ if (this.live.size) {
1448
+ const providerClient = clientWithHistory(
1449
+ this.client,
1450
+ async () => ({
1451
+ chunk: [syntheticSnapshot(result.update)],
1452
+ start: result.token,
1453
+ end: void 0
1454
+ })
1455
+ );
1456
+ const provider = new MatrixProvider(
1457
+ this.doc,
1458
+ providerClient,
1459
+ { type: "id", id: this.roomId },
1460
+ {
1461
+ translator: { enableMediaSnapshots: true },
1462
+ reader: { snapshotInterval: 10 },
1463
+ writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 },
1464
+ enableAwareness: true,
1465
+ enableExperimentalWebrtcSync: true
1466
+ }
1467
+ );
1468
+ this.provider = provider;
1469
+ this.watchPageExit(true);
1470
+ provider.onDocumentUnavailable(() => {
1471
+ if (this.provider !== provider) return;
1472
+ this.status = "error";
1473
+ this.error = "Flow document is unavailable";
1474
+ this.notify();
1475
+ });
1476
+ provider.onDocumentAvailable(() => {
1477
+ if (this.provider !== provider) return;
1478
+ this.status = "connected";
1479
+ this.error = void 0;
1480
+ this.notify();
1481
+ });
1482
+ void provider.initialize().catch((error) => {
1483
+ if (this.provider !== provider) return;
1484
+ provider.dispose();
1485
+ this.watchPageExit(false);
1486
+ this.provider = null;
1487
+ this.fail(error);
1488
+ });
1577
1489
  }
1578
- } catch {
1490
+ this.save();
1491
+ this.notify();
1492
+ })().catch((error) => {
1493
+ if (generation === this.generation) this.fail(error);
1494
+ }).finally(() => {
1495
+ this.pending = void 0;
1496
+ });
1497
+ return this.pending;
1498
+ }
1499
+ fail(error) {
1500
+ const code = error?.errcode;
1501
+ if (code === "M_FORBIDDEN" || code === "M_UNKNOWN_TOKEN") {
1502
+ this.ready = false;
1503
+ this.checkpoint = void 0;
1579
1504
  }
1505
+ this.status = "error";
1506
+ this.error = error instanceof Error ? error.message : String(error);
1507
+ this.notify();
1508
+ clearTimeout(this.retry);
1509
+ if (this.listeners.size) this.retry = setTimeout(() => void this.connect(), Math.min(5e3 * 2 ** this.attempt++, 3e4));
1580
1510
  }
1581
- if (node.title && node.title !== node.can) {
1582
- cap.title = node.title;
1511
+ save() {
1512
+ if (this.checkpoint && this.ready) void writeFlowCheckpoint(this.client, this.roomId, this.checkpoint);
1583
1513
  }
1584
- if (node.description) {
1585
- cap.description = node.description;
1514
+ async stopProvider() {
1515
+ const provider = this.provider;
1516
+ if (!provider) return;
1517
+ this.save();
1518
+ this.watchPageExit(false);
1519
+ this.provider = null;
1520
+ this.stopping = (async () => {
1521
+ let timer;
1522
+ try {
1523
+ await Promise.race([
1524
+ provider.waitForFlush(),
1525
+ new Promise((resolve) => {
1526
+ timer = setTimeout(resolve, 3e3);
1527
+ })
1528
+ ]);
1529
+ } catch {
1530
+ return;
1531
+ } finally {
1532
+ clearTimeout(timer);
1533
+ provider.dispose();
1534
+ }
1535
+ })();
1536
+ await this.stopping;
1537
+ this.stopping = void 0;
1586
1538
  }
1587
- if (node.props.icon) {
1588
- cap.icon = node.props.icon;
1539
+ };
1540
+ function getSharedFlowDocument(client, roomId) {
1541
+ let rooms = sessions.get(client);
1542
+ if (!rooms) {
1543
+ rooms = /* @__PURE__ */ new Map();
1544
+ sessions.set(client, rooms);
1589
1545
  }
1590
- return cap;
1591
- }
1592
- function triggerToNodeIds(trigger, nodeIdByBlockId) {
1593
- if (trigger.type === "block.event" && trigger.sourceBlockId) {
1594
- return { ...trigger, sourceBlockId: nodeIdByBlockId[trigger.sourceBlockId] ?? trigger.sourceBlockId };
1546
+ let session = rooms.get(roomId);
1547
+ if (!session) {
1548
+ session = new SharedFlowDocument(client, roomId);
1549
+ rooms.set(roomId, session);
1595
1550
  }
1596
- if (trigger.type === "block.event.all" && trigger.sources) {
1597
- return {
1598
- ...trigger,
1599
- sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: nodeIdByBlockId[src.sourceBlockId] ?? src.sourceBlockId }))
1600
- };
1551
+ session.lastAccess = Date.now();
1552
+ if (rooms.size > 32) {
1553
+ for (const candidate of [...rooms.values()].sort((a, b) => a.lastAccess - b.lastAccess)) {
1554
+ if (rooms.size <= 32) break;
1555
+ if (candidate !== session && Date.now() - candidate.lastAccess > 1e3) candidate.evictIfIdle();
1556
+ }
1601
1557
  }
1602
- return trigger;
1558
+ return session;
1603
1559
  }
1604
1560
 
1605
- // src/core/lib/flowIdentity.ts
1606
- var FLOW_IDENTITY_EVENT_TYPE = "ixo.qi.flow.identity";
1607
- function readFlowIdentityDocId(client, roomId) {
1608
- if (!client || !roomId || typeof client.getRoom !== "function") return "";
1609
- const creator = readRoomCreatorUserId(client, roomId);
1610
- if (!creator) return "";
1611
- const event = client.getRoom(roomId)?.currentState?.getStateEvents?.(FLOW_IDENTITY_EVENT_TYPE, "");
1612
- if (!event || event.getSender() !== creator) return "";
1613
- const content = event.getContent?.();
1614
- return typeof content?.docId === "string" ? content.docId : "";
1561
+ // src/core/lib/flowCompiler/conditions.ts
1562
+ var OPERATOR_MAP = {
1563
+ // BaseUcan ConditionRef vocabulary
1564
+ eq: "equals",
1565
+ neq: "not_equals",
1566
+ gt: "greater_than",
1567
+ lt: "less_than",
1568
+ in: "contains",
1569
+ exists: "is_not_empty",
1570
+ // Friendly camelCase (plugin FlowSpec `is`)
1571
+ equals: "equals",
1572
+ notEquals: "not_equals",
1573
+ greaterThan: "greater_than",
1574
+ lessThan: "less_than",
1575
+ isEmpty: "is_empty",
1576
+ isNotEmpty: "is_not_empty",
1577
+ // Evaluator vocabulary passthrough
1578
+ not_equals: "not_equals",
1579
+ greater_than: "greater_than",
1580
+ less_than: "less_than",
1581
+ contains: "contains",
1582
+ not_contains: "not_contains",
1583
+ notContains: "not_contains",
1584
+ is_empty: "is_empty",
1585
+ is_not_empty: "is_not_empty"
1586
+ };
1587
+ function toEvaluatorOperator(operator) {
1588
+ return OPERATOR_MAP[operator] ?? "equals";
1615
1589
  }
1616
- async function writeFlowIdentity(client, roomId, docId, options = {}) {
1617
- if (!client || !roomId || !docId) return "no-owner";
1618
- if (!readFlowOwnerDid(client, roomId)) return "no-owner";
1619
- const creator = readRoomCreatorUserId(client, roomId);
1620
- if (!creator || client.getUserId?.() !== creator) return "not-creator";
1621
- const existing = readFlowIdentityDocId(client, roomId);
1622
- if (existing === docId) return "already-bound";
1623
- if (existing && !options.overwrite) return "bound-to-another-doc";
1624
- const content = { docId };
1625
- await client.sendStateEvent(roomId, FLOW_IDENTITY_EVENT_TYPE, content, "");
1626
- return "written";
1590
+ function buildBlockConditionsProp(conditions, opts) {
1591
+ return JSON.stringify({
1592
+ enabled: opts?.enabled ?? true,
1593
+ mode: opts?.mode ?? "all_must_pass",
1594
+ conditions: conditions.map((c, i) => ({
1595
+ id: `cond_${c.sourceBlockId}_${c.property}_${i}`,
1596
+ name: c.name ?? `Condition from ${c.sourceBlockId}`,
1597
+ sourceBlockId: c.sourceBlockId,
1598
+ sourceBlockType: c.sourceBlockType ?? "action",
1599
+ rule: {
1600
+ type: "property_value",
1601
+ property: c.property,
1602
+ operator: toEvaluatorOperator(c.operator),
1603
+ value: c.value
1604
+ },
1605
+ effect: c.effect ?? { action: "enable" }
1606
+ }))
1607
+ });
1627
1608
  }
1628
1609
 
1629
- // src/core/lib/flowCompiler/setup.ts
1630
- import * as Y4 from "yjs";
1631
- import { MatrixProvider as MatrixProvider2 } from "@ixo/matrix-crdt";
1632
- async function readFlowAsBaseUcan(options) {
1633
- const { roomId, matrixClient } = options;
1634
- const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: false });
1635
- try {
1636
- const compiled = readCompiledFlowFromYDoc(yDoc);
1637
- if (!compiled) return null;
1638
- const plan = decompileToBaseUcanFlow(compiled);
1639
- return { plan, compiled, roomId };
1640
- } finally {
1641
- provider.dispose();
1642
- yDoc.destroy();
1643
- }
1644
- }
1645
- function readFlowFromEditor(editor) {
1646
- const yDoc = editor._yDoc;
1647
- if (!yDoc) return null;
1648
- const compiled = readCompiledFlowFromYDoc(yDoc);
1649
- if (!compiled) return null;
1650
- const plan = decompileToBaseUcanFlow(compiled);
1651
- const roomId = editor.getRoomId?.() || "";
1652
- return { plan, compiled, roomId };
1653
- }
1654
- var activeEditor = null;
1655
- function setActiveEditor(editor) {
1656
- activeEditor = editor;
1657
- }
1658
- function getActiveEditor() {
1659
- return activeEditor;
1610
+ // src/core/lib/flowCompiler/compiler.ts
1611
+ function stripActiveScheduleBindings(plan) {
1612
+ let changed = false;
1613
+ const capabilities = plan.capabilities.map((cap) => {
1614
+ if (cap.trigger?.type !== "schedule") return cap;
1615
+ if (cap.trigger.scheduleRef === void 0 && cap.trigger.scheduleRevision === void 0) return cap;
1616
+ changed = true;
1617
+ const { scheduleRef: _ref, scheduleRevision: _rev, ...inactive } = cap.trigger;
1618
+ return { ...cap, trigger: inactive };
1619
+ });
1620
+ return changed ? { ...plan, capabilities } : plan;
1660
1621
  }
1661
- function readFlow() {
1662
- if (!activeEditor) {
1663
- console.warn("[readFlow] No active editor registered. Did the editor finish mounting?");
1664
- return null;
1622
+ function compileBaseUcanFlow(plan, registry) {
1623
+ if (!Array.isArray(plan.capabilities)) {
1624
+ throw new Error("BaseUcanFlow.capabilities must be an array");
1665
1625
  }
1666
- return readFlowFromEditor(activeEditor);
1667
- }
1668
- async function setupFlowFromBaseUcan(options) {
1669
- const { plan: rawPlan, roomId, matrixClient, creatorDid, docId, templateId, strategy = "full" } = options;
1670
- const identified = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: docId || roomId };
1671
- const plan = templateId ? stripActiveScheduleBindings(identified) : identified;
1672
- const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
1673
- const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
1674
- let finalCompiled;
1675
- try {
1676
- finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, docId, templateId, strategy });
1677
- await provider.waitForFlush();
1678
- await bindRoomIdentity(matrixClient, roomId, yDoc);
1679
- } finally {
1680
- provider.dispose();
1681
- yDoc.destroy();
1626
+ const capabilities = plan.capabilities;
1627
+ if (capabilities.length === 0) {
1628
+ throw new Error("BaseUcanFlow has no capabilities to compile");
1682
1629
  }
1683
- return {
1684
- compiled: finalCompiled,
1685
- roomId,
1686
- flowId: plan.flowId
1687
- };
1688
- }
1689
- async function seedDesignPodTemplateFlow(options) {
1690
- const { methodId, roomId, matrixClient, creatorDid } = options;
1691
- const rawPlan = createDesignPodPortalJourneyPlan(methodId);
1692
- const plan = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: roomId };
1693
- const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
1694
- const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
1695
- let finalCompiled;
1696
- try {
1697
- finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, strategy: "full" });
1698
- seedDesignPodMethodDefinition(yDoc, methodId);
1699
- await provider.waitForFlush();
1700
- await bindRoomIdentity(matrixClient, roomId, yDoc);
1701
- } finally {
1702
- provider.dispose();
1703
- yDoc.destroy();
1630
+ const actionMap = /* @__PURE__ */ new Map();
1631
+ for (const cap of capabilities) {
1632
+ const nodeId = cap.id?.trim();
1633
+ if (!nodeId) {
1634
+ throw new Error("Every capability in BaseUcanFlow.capabilities must include a non-empty id.");
1635
+ }
1636
+ if (actionMap.has(nodeId)) {
1637
+ throw new Error(`Duplicate capability id "${nodeId}" in BaseUcanFlow.capabilities.`);
1638
+ }
1639
+ const action = registry.getActionByCan(cap.can);
1640
+ if (!action) {
1641
+ throw new Error(`Unknown capability "${cap.can}" for node "${nodeId}". Not found in action registry.`);
1642
+ }
1643
+ actionMap.set(nodeId, { action, nodeId, cap });
1704
1644
  }
1705
- return { compiled: finalCompiled, roomId, flowId: plan.flowId };
1706
- }
1707
- function applyFlowPlanToYDoc(yDoc, options) {
1708
- const { plan, incomingCompiled, creatorDid, docId, templateId, strategy, runId } = options;
1709
- const root = yDoc.getMap("root");
1710
- const fragment = yDoc.getXmlFragment("document");
1711
- const existingFlow = readCompiledFlowFromYDoc(yDoc);
1712
- if (strategy === "full") {
1713
- if (existingFlow) {
1714
- clearFlowState(yDoc);
1715
- removeAllFlowBlocks(fragment);
1645
+ const blockIndex = {};
1646
+ for (const nodeId of actionMap.keys()) {
1647
+ blockIndex[nodeId] = generateBlockId(nodeId);
1648
+ }
1649
+ const triggerEdges = [];
1650
+ for (const [nodeId, { cap, action }] of actionMap) {
1651
+ const trigger = cap.trigger;
1652
+ if (!trigger) continue;
1653
+ if (trigger.type === "block.event") {
1654
+ if (action.eligibleForEventTrigger !== true) {
1655
+ throw new Error(
1656
+ `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.`
1657
+ );
1658
+ }
1659
+ const sourceId = trigger.sourceBlockId?.trim();
1660
+ const eventName = trigger.eventName?.trim();
1661
+ if (!sourceId || !eventName) {
1662
+ throw new Error(`Block "${nodeId}" has a block.event trigger but is missing sourceBlockId or eventName.`);
1663
+ }
1664
+ const source = actionMap.get(sourceId);
1665
+ if (!source) {
1666
+ throw new Error(`Trigger on block "${nodeId}" references unknown source block "${sourceId}".`);
1667
+ }
1668
+ const declaredEvents = getEventsForBlock(source.action, source.cap.nb);
1669
+ if (declaredEvents.length === 0) {
1670
+ throw new Error(`Trigger on block "${nodeId}" references event "${eventName}" but source action "${source.action.type}" declares no events.`);
1671
+ }
1672
+ const found = declaredEvents.find((e) => e.name === eventName);
1673
+ if (!found) {
1674
+ const declared = declaredEvents.map((e) => e.name).join(", ");
1675
+ throw new Error(`Trigger on block "${nodeId}" references unknown event "${eventName}" on action type "${source.action.type}". Declared events: [${declared}]`);
1676
+ }
1677
+ triggerEdges.push({
1678
+ id: `${sourceId}~event:${eventName}~>${nodeId}`,
1679
+ source: sourceId,
1680
+ target: nodeId,
1681
+ kind: "trigger"
1682
+ });
1716
1683
  }
1717
- setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
1718
- hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
1719
- if (!existingFlow) {
1720
- initializeRuntime(yDoc, incomingCompiled, runId);
1684
+ if (trigger.type === "block.event.all") {
1685
+ if (action.eligibleForEventTrigger !== true) {
1686
+ throw new Error(`Block "${nodeId}" is configured with a block.event.all trigger, but its action type "${action.type}" is not marked eligibleForEventTrigger.`);
1687
+ }
1688
+ const sources = trigger.sources || [];
1689
+ if (sources.length === 0) {
1690
+ throw new Error(`Block "${nodeId}" has a block.event.all trigger but no sources configured.`);
1691
+ }
1692
+ for (const src of sources) {
1693
+ const srcId = src.sourceBlockId?.trim();
1694
+ const evtName = src.eventName?.trim();
1695
+ if (!srcId || !evtName) {
1696
+ throw new Error(`Block "${nodeId}" has a block.event.all source with missing sourceBlockId or eventName.`);
1697
+ }
1698
+ const sourceEntry = actionMap.get(srcId);
1699
+ if (!sourceEntry) {
1700
+ throw new Error(`Barrier trigger on block "${nodeId}" references unknown source block "${srcId}".`);
1701
+ }
1702
+ const declaredEvents = getEventsForBlock(sourceEntry.action, sourceEntry.cap.nb);
1703
+ const found = declaredEvents.find((e) => e.name === evtName);
1704
+ if (!found) {
1705
+ const declared = declaredEvents.map((e) => e.name).join(", ");
1706
+ throw new Error(`Barrier trigger on block "${nodeId}" references unknown event "${evtName}" on action type "${sourceEntry.action.type}". Declared events: [${declared}]`);
1707
+ }
1708
+ if (!src.alias?.trim()) {
1709
+ throw new Error(`Barrier trigger on block "${nodeId}" has a source (${srcId}/${evtName}) with no alias.`);
1710
+ }
1711
+ triggerEdges.push({
1712
+ id: `${srcId}~event:${evtName}~>${nodeId}`,
1713
+ source: srcId,
1714
+ target: nodeId,
1715
+ kind: "trigger"
1716
+ });
1717
+ }
1718
+ }
1719
+ if (trigger.type === "schedule") {
1720
+ if (action.eligibleForTimeTrigger !== true) {
1721
+ throw new Error(
1722
+ `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.`
1723
+ );
1724
+ }
1725
+ if (trigger.sourceBlockId || trigger.sources || trigger.eventName) {
1726
+ throw new Error(
1727
+ `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.`
1728
+ );
1729
+ }
1730
+ if (trigger.scheduleRevision !== void 0 && (!Number.isInteger(trigger.scheduleRevision) || trigger.scheduleRevision < 1)) {
1731
+ throw new Error(`Block "${nodeId}" has a schedule trigger with an invalid scheduleRevision (must be an integer >= 1).`);
1732
+ }
1733
+ }
1734
+ if (trigger.type === "block.event" || trigger.type === "block.event.all") {
1735
+ const refs = collectOutputRefs(cap.nb || {});
1736
+ for (const ref of refs) {
1737
+ const parsed = parseOutputRef(ref);
1738
+ if (!parsed) continue;
1739
+ if (!actionMap.has(parsed.nodeId)) {
1740
+ throw new Error(`Listener "${nodeId}" references output of unknown block "${parsed.nodeId}" via ref "${ref}".`);
1741
+ }
1742
+ }
1721
1743
  }
1722
- yDoc.transact(() => {
1723
- writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
1724
- });
1725
- return incomingCompiled;
1726
1744
  }
1727
- if (!existingFlow) {
1728
- setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
1729
- hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
1730
- initializeRuntime(yDoc, incomingCompiled, runId);
1731
- yDoc.transact(() => {
1732
- writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
1745
+ const edges = [...triggerEdges];
1746
+ detectTriggerCycles(triggerEdges);
1747
+ const order = Array.from(actionMap.keys());
1748
+ const blocks = [];
1749
+ const nodes = {};
1750
+ for (const nodeId of order) {
1751
+ const { action, cap } = actionMap.get(nodeId);
1752
+ const blockId = blockIndex[nodeId];
1753
+ const props = compileBlockProps(cap, action.type);
1754
+ if (cap.condition) {
1755
+ props.conditions = compileCondition(cap.condition, blockIndex);
1756
+ }
1757
+ if (cap.trigger) {
1758
+ props.trigger = compileTrigger(cap.trigger, blockIndex);
1759
+ }
1760
+ props.triggerMode = cap.trigger?.type || "manual";
1761
+ blocks.push({
1762
+ id: blockId,
1763
+ type: COMPILED_BLOCK_TYPE,
1764
+ props
1733
1765
  });
1734
- return incomingCompiled;
1766
+ nodes[nodeId] = {
1767
+ id: nodeId,
1768
+ blockId,
1769
+ can: cap.can,
1770
+ with: cap.with,
1771
+ registryType: action.type,
1772
+ title: cap.title || cap.can,
1773
+ description: cap.description || "",
1774
+ props,
1775
+ phase: cap.phase,
1776
+ parallelGroup: cap.parallelGroup,
1777
+ actor: cap.actor
1778
+ };
1735
1779
  }
1736
- const mergeResult = mergeCompiledFlows(existingFlow, incomingCompiled, strategy);
1737
- hydrateYDocFromMergeResult(yDoc, mergeResult);
1738
- const nodesToInit = [...mergeResult.added, ...mergeResult.replaced];
1739
- initializeRuntimeForNodes(yDoc, mergeResult.merged, nodesToInit, runId);
1740
- yDoc.transact(() => {
1741
- applyMergeResultToFragment(fragment, mergeResult);
1742
- });
1743
- return mergeResult.merged;
1780
+ return {
1781
+ meta: {
1782
+ flowId: plan.flowId,
1783
+ title: plan.title,
1784
+ goal: plan.goal,
1785
+ version: plan.version,
1786
+ flowOwnerDid: plan.meta?.rootIssuer || "",
1787
+ flowUri: plan.meta?.flowUri,
1788
+ compiledAt: (/* @__PURE__ */ new Date()).toISOString(),
1789
+ compiledFrom: "BaseUcanFlow"
1790
+ },
1791
+ blocks,
1792
+ nodes,
1793
+ edges,
1794
+ order,
1795
+ blockIndex
1796
+ };
1744
1797
  }
1745
- async function connectToRoom(roomId, matrixClient, options) {
1746
- const yDoc = new Y4.Doc();
1747
- const client = matrixClient;
1748
- client.canSupportVoip = false;
1749
- client.clientOpts = { lazyLoadMembers: true };
1750
- const provider = new MatrixProvider2(
1751
- yDoc,
1752
- client,
1753
- { type: "id", id: roomId },
1754
- {
1755
- translator: {
1756
- updateEventType: "matrix-crdt.doc_update",
1757
- snapshotEventType: "matrix-crdt.doc_snapshot",
1758
- enableMediaSnapshots: true
1759
- },
1760
- enableExperimentalWebrtcSync: false,
1761
- enableAwareness: false,
1762
- reader: { snapshotInterval: 10 },
1763
- writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 }
1764
- }
1765
- );
1766
- await new Promise((resolve, reject) => {
1767
- const timeout = setTimeout(() => {
1768
- reject(new Error(`Timed out connecting to room ${roomId}`));
1769
- }, 3e4);
1770
- provider.onDocumentAvailable(() => {
1771
- clearTimeout(timeout);
1772
- resolve();
1773
- });
1774
- provider.onDocumentUnavailable(() => {
1775
- clearTimeout(timeout);
1776
- reject(new Error(`Room ${roomId} is unavailable`));
1777
- });
1778
- provider.initialize().catch((err) => {
1779
- clearTimeout(timeout);
1780
- reject(err);
1781
- });
1782
- });
1783
- if (options.adoptRuns && provider.canWrite) {
1784
- collectPhantomLegacyRun(yDoc);
1798
+ function generateBlockId(nodeId) {
1799
+ return `flow_block_${nodeId}`;
1800
+ }
1801
+ function compileCondition(condition, blockIndex) {
1802
+ const sourceBlockId = blockIndex[condition.sourceId];
1803
+ if (!sourceBlockId) {
1804
+ throw new Error(`Condition references unknown source "${condition.sourceId}".`);
1785
1805
  }
1786
- bindFlowOwnerFromRoom(yDoc, client, roomId);
1787
- return { yDoc, provider };
1806
+ const conditionConfig = {
1807
+ enabled: true,
1808
+ mode: "all_must_pass",
1809
+ conditions: [
1810
+ {
1811
+ id: `cond_${condition.sourceId}_${condition.field}`,
1812
+ name: `Condition from ${condition.sourceId}`,
1813
+ sourceBlockId,
1814
+ sourceBlockType: COMPILED_BLOCK_TYPE,
1815
+ rule: {
1816
+ type: "property_value",
1817
+ property: condition.field,
1818
+ // Map the BaseUcan ConditionRef operator (eq/neq/…) onto the FE evaluator's
1819
+ // vocabulary (equals/not_equals/…). Writing it verbatim is the historical bug
1820
+ // that made compiler-authored conditions silently never evaluate.
1821
+ operator: toEvaluatorOperator(condition.operator),
1822
+ value: condition.value
1823
+ },
1824
+ effect: condition.effect || { action: "enable" }
1825
+ }
1826
+ ]
1827
+ };
1828
+ return JSON.stringify(conditionConfig);
1788
1829
  }
1789
- async function bindRoomIdentity(matrixClient, roomId, yDoc) {
1790
- const docId = yDoc.getMap("root").get("doc_id");
1791
- if (typeof docId !== "string" || !docId) return;
1792
- try {
1793
- await writeFlowIdentity(matrixClient, roomId, docId);
1794
- } catch (error) {
1795
- console.warn("Could not write the flow identity event:", error);
1830
+ function compileTrigger(trigger, blockIndex) {
1831
+ if (trigger.type === "block.event" && trigger.sourceBlockId) {
1832
+ return JSON.stringify({ ...trigger, sourceBlockId: blockIndex[trigger.sourceBlockId.trim()] });
1833
+ }
1834
+ if (trigger.type === "block.event.all" && trigger.sources) {
1835
+ return JSON.stringify({
1836
+ ...trigger,
1837
+ sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: blockIndex[src.sourceBlockId.trim()] }))
1838
+ });
1796
1839
  }
1840
+ return JSON.stringify(trigger);
1797
1841
  }
1798
- function setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId) {
1799
- yDoc.transact(() => {
1800
- if (!root.get("@context")) root.set("@context", "https://ixo.world/flow/0.3");
1801
- if (!root.get("_type")) root.set("_type", "ixo.flow.crdt");
1802
- if (!root.get("schema_version")) root.set("schema_version", "0.3");
1803
- if (!root.get("doc_id")) root.set("doc_id", docId || plan.flowId);
1804
- if (!root.get("createdAt")) root.set("createdAt", (/* @__PURE__ */ new Date()).toISOString());
1805
- if (!root.get("createdBy")) root.set("createdBy", creatorDid);
1806
- const roomCreator = flowOwnerOf(yDoc);
1807
- if (roomCreator) root.set("flowOwnerDid", roomCreator);
1808
- else if (!root.get("flowOwnerDid")) root.set("flowOwnerDid", creatorDid);
1809
- if (!hasLegacyRuntimeHistory(yDoc)) setMultiRunStorage(yDoc);
1810
- if (templateId && !root.get("source_template_id")) {
1811
- root.set("source_template_id", templateId);
1842
+ function collectOutputRefs(value) {
1843
+ const refs = [];
1844
+ walk(value);
1845
+ return refs;
1846
+ function walk(v) {
1847
+ if (isRuntimeRef(v)) {
1848
+ const r = v.$ref;
1849
+ if (!r.startsWith("trigger.")) refs.push(r);
1850
+ return;
1812
1851
  }
1813
- const titleText = yDoc.getText("title");
1814
- if (titleText.length === 0 && plan.title) {
1815
- titleText.insert(0, plan.title);
1852
+ if (Array.isArray(v)) {
1853
+ for (const item of v) walk(item);
1854
+ return;
1855
+ }
1856
+ if (v !== null && typeof v === "object") {
1857
+ for (const inner of Object.values(v)) walk(inner);
1816
1858
  }
1817
- });
1818
- }
1819
-
1820
- // src/core/lib/flowCompiler/authoring.ts
1821
- function readFlowDocument(yDoc, runId) {
1822
- const compiled = readCompiledFlowFromYDoc(yDoc);
1823
- if (!compiled) return null;
1824
- const propsByBlockId = /* @__PURE__ */ new Map();
1825
- for (const block of readBlocksFromFragment(yDoc.getXmlFragment("document"))) {
1826
- propsByBlockId.set(block.id, block.props);
1827
1859
  }
1828
- const resolvedRunId = resolveRunIdForRead(yDoc, runId);
1829
- const nodePropsAreAuthoritative = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1830
- const nodes = compiled.order.filter((nodeId) => compiled.nodes[nodeId]).map((nodeId) => {
1831
- const node = compiled.nodes[nodeId];
1832
- const projectedProps = propsByBlockId.get(node.blockId) ?? {};
1833
- const props = nodePropsAreAuthoritative && Object.keys(node.props ?? {}).length > 0 ? { ...node.props } : projectedProps;
1834
- const runtime = resolvedRunId ? readActionState(yDoc, resolvedRunId, node.blockId) : {};
1835
- return {
1836
- nodeId,
1837
- blockId: node.blockId,
1838
- can: node.can,
1839
- with: node.with,
1840
- title: props.title ?? node.title,
1841
- description: props.description ?? node.description,
1842
- props,
1843
- runtime
1844
- };
1845
- });
1846
- return {
1847
- meta: compiled.meta,
1848
- order: compiled.order,
1849
- edges: compiled.edges,
1850
- blockIndex: compiled.blockIndex,
1851
- nodes
1852
- };
1853
1860
  }
1854
- function addFlowNode(yDoc, opts) {
1855
- const action = getAction(opts.type);
1856
- if (!action) return null;
1857
- const nodeId = opts.nodeId ?? `node_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1858
- const blockId = opts.blockId ?? `flow_block_${nodeId}`;
1859
- if (yDoc.getMap("qi.flow.nodes").has(nodeId) || [...yDoc.getMap("qi.flow.blockIndex").values()].includes(blockId)) return null;
1860
- const flowId = yDoc.getMap("qi.flow.meta").get("flowId") || "";
1861
- const withUri = flowId ? `ixo:flow:${flowId}:${nodeId}` : `ixo:flow:${nodeId}`;
1862
- const can = action.can ?? "";
1863
- const title = opts.title || can || action.type;
1864
- const cap = { id: nodeId, can, with: withUri, title, nb: {} };
1865
- const props = { ...compileBlockProps(cap, action.type), triggerMode: "manual", ...opts.props ?? {} };
1866
- const node = {
1867
- id: nodeId,
1868
- blockId,
1869
- can,
1870
- with: withUri,
1871
- registryType: action.type,
1872
- title,
1873
- description: "",
1874
- props
1861
+ function parseOutputRef(ref) {
1862
+ const outputIndex = ref.indexOf(".output.");
1863
+ if (outputIndex === -1) return null;
1864
+ return {
1865
+ nodeId: ref.slice(0, outputIndex),
1866
+ fieldPath: ref.slice(outputIndex + ".output.".length)
1875
1867
  };
1876
- yDoc.transact(() => {
1877
- writeCompiledBlocksToFragment(yDoc.getXmlFragment("document"), [{ id: blockId, type: COMPILED_BLOCK_TYPE, props }]);
1878
- yDoc.getMap("qi.flow.nodes").set(nodeId, createYMapFromNode(node));
1879
- yDoc.getMap("qi.flow.blockIndex").set(nodeId, blockId);
1880
- const order = yDoc.getArray("qi.flow.order");
1881
- if (opts.afterNodeId) {
1882
- const idx = order.toArray().indexOf(opts.afterNodeId);
1883
- if (idx >= 0) order.insert(idx + 1, [nodeId]);
1884
- else order.push([nodeId]);
1885
- } else {
1886
- order.push([nodeId]);
1887
- }
1888
- advanceDraftRevision(yDoc);
1889
- });
1890
- return { nodeId, blockId };
1891
1868
  }
1892
- function setBlockProps(yDoc, blockId, partial) {
1893
- const fragment = yDoc.getXmlFragment("document");
1894
- const existing = readBlocksFromFragment(fragment).find((b) => b.id === blockId);
1895
- if (!existing) return false;
1896
- const nodeId = findNodeIdForBlock(yDoc, blockId);
1897
- const node = nodeId ? yDoc.getMap("qi.flow.nodes").get(nodeId) : void 0;
1898
- const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1899
- const canonicalProps = isYMapLike(node) ? node.get("props") : void 0;
1900
- const baseline = isVNextDraft && canonicalProps ? canonicalProps : existing.props;
1901
- const merged = { ...baseline, ...partial };
1902
- let ok = false;
1903
- yDoc.transact(() => {
1904
- ok = replaceBlockInFragment(fragment, { id: blockId, type: existing.type, props: merged });
1905
- if (isYMapLike(node)) {
1906
- node.set("props", { ...merged });
1907
- if ("title" in partial) node.set("title", merged.title ?? "");
1908
- if ("description" in partial) node.set("description", merged.description ?? "");
1909
- if ("authorisedActors" in partial || "parentCapability" in partial) {
1910
- const actor = actorFromProps(merged);
1911
- if (actor) node.set("actor", actor);
1912
- else node.delete("actor");
1869
+ function detectTriggerCycles(triggerEdges) {
1870
+ if (triggerEdges.length === 0) return;
1871
+ const adjacency = /* @__PURE__ */ new Map();
1872
+ const allNodes = /* @__PURE__ */ new Set();
1873
+ for (const edge of triggerEdges) {
1874
+ if (!adjacency.has(edge.source)) adjacency.set(edge.source, []);
1875
+ adjacency.get(edge.source).push(edge.target);
1876
+ allNodes.add(edge.source);
1877
+ allNodes.add(edge.target);
1878
+ }
1879
+ const WHITE = 0;
1880
+ const GRAY = 1;
1881
+ const BLACK = 2;
1882
+ const color = /* @__PURE__ */ new Map();
1883
+ for (const id of allNodes) color.set(id, WHITE);
1884
+ const path = [];
1885
+ const visit = (node) => {
1886
+ color.set(node, GRAY);
1887
+ path.push(node);
1888
+ for (const next of adjacency.get(node) || []) {
1889
+ if (color.get(next) === GRAY) {
1890
+ const start = path.indexOf(next);
1891
+ const cycle = path.slice(start).concat(next).join(" \u2192 ");
1892
+ throw new Error(`Trigger cycle detected: ${cycle}. Block.event triggers must form a DAG; remove one of the trigger declarations to break the cycle.`);
1893
+ }
1894
+ if (color.get(next) === WHITE) {
1895
+ visit(next);
1913
1896
  }
1914
1897
  }
1915
- advanceDraftRevision(yDoc);
1916
- });
1917
- return ok;
1918
- }
1919
- function syncFlowNodePropsFromProjection(yDoc, blockId, partial, legacyBaseline = {}) {
1920
- const nodeId = findNodeIdForBlock(yDoc, blockId);
1921
- if (!nodeId) return false;
1922
- const node = yDoc.getMap("qi.flow.nodes").get(nodeId);
1923
- if (!isYMapLike(node)) return false;
1924
- const isVNextDraft = yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1;
1925
- const projectedBaseline = readBlocksFromFragment(yDoc.getXmlFragment("document")).find((block) => block.id === blockId)?.props;
1926
- const nodeProps = node.get("props");
1927
- const baseline = isVNextDraft ? nodeProps ?? legacyBaseline : projectedBaseline ?? legacyBaseline;
1928
- if (!isVNextDraft && !nodeProps && Object.keys(baseline).length === 0) return false;
1929
- yDoc.transact(() => {
1930
- const merged = { ...baseline, ...partial };
1931
- node.set("props", merged);
1932
- if ("title" in partial) node.set("title", merged.title ?? "");
1933
- if ("description" in partial) node.set("description", merged.description ?? "");
1934
- if ("authorisedActors" in partial || "parentCapability" in partial) {
1935
- const actor = actorFromProps(merged);
1936
- if (actor) node.set("actor", actor);
1937
- else node.delete("actor");
1938
- }
1939
- if (isVNextDraft) advanceDraftRevision(yDoc);
1940
- });
1941
- return true;
1942
- }
1943
- function auditFlowProjections(yDoc) {
1944
- const projected = new Map(readBlocksFromFragment(yDoc.getXmlFragment("document")).map((block) => [block.id, block.props]));
1945
- const drift = [];
1946
- yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
1947
- if (!isYMapLike(value)) return;
1948
- const blockId = String(value.get("blockId") ?? "");
1949
- const canonical = value.get("props") ?? {};
1950
- const projection = projected.get(blockId);
1951
- if (!projection) drift.push({ nodeId, blockId, kind: "missing_block" });
1952
- else if (stableProps(canonical) !== stableProps(projection)) drift.push({ nodeId, blockId, kind: "props_mismatch" });
1953
- });
1954
- return drift.sort((left, right) => left.nodeId.localeCompare(right.nodeId));
1898
+ path.pop();
1899
+ color.set(node, BLACK);
1900
+ };
1901
+ for (const id of allNodes) {
1902
+ if (color.get(id) === WHITE) visit(id);
1903
+ }
1955
1904
  }
1956
- function repairFlowProjections(yDoc) {
1957
- const before = auditFlowProjections(yDoc);
1958
- if (before.length === 0) return before;
1959
- const fragment = yDoc.getXmlFragment("document");
1960
- const projected = new Map(readBlocksFromFragment(fragment).map((block) => [block.id, block]));
1961
- const orderedNodeIds = yDoc.getArray("qi.flow.order").toArray();
1962
- yDoc.transact(() => {
1963
- for (const item of before) {
1964
- const node = yDoc.getMap("qi.flow.nodes").get(item.nodeId);
1965
- if (!isYMapLike(node)) continue;
1966
- const props = node.get("props") ?? {};
1967
- const block = projected.get(item.blockId);
1968
- if (block) {
1969
- replaceBlockInFragment(fragment, { ...block, props });
1970
- continue;
1971
- }
1972
- const nodeIndex = orderedNodeIds.indexOf(item.nodeId);
1973
- const nextProjectedBlockId = orderedNodeIds.slice(nodeIndex + 1).find((candidateNodeId) => {
1974
- const candidate = yDoc.getMap("qi.flow.nodes").get(candidateNodeId);
1975
- if (!isYMapLike(candidate)) return false;
1976
- return projected.has(String(candidate.get("blockId") ?? ""));
1977
- });
1978
- const nextNode = nextProjectedBlockId ? yDoc.getMap("qi.flow.nodes").get(nextProjectedBlockId) : void 0;
1979
- const beforeBlockId = isYMapLike(nextNode) ? String(nextNode.get("blockId") ?? "") : void 0;
1980
- insertCompiledBlockIntoFragment(fragment, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props }, beforeBlockId);
1981
- projected.set(item.blockId, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props });
1905
+
1906
+ // src/core/lib/flowCompiler/mergeFlows.ts
1907
+ function mergeCompiledFlows(existing, incoming, strategy) {
1908
+ const added = [];
1909
+ const replaced = [];
1910
+ const kept = [];
1911
+ const mergedNodes = {};
1912
+ const mergedBlockIndex = {};
1913
+ for (const [nodeId, node] of Object.entries(existing.nodes)) {
1914
+ mergedNodes[nodeId] = node;
1915
+ mergedBlockIndex[nodeId] = existing.blockIndex[nodeId];
1916
+ }
1917
+ for (const [nodeId, node] of Object.entries(incoming.nodes)) {
1918
+ if (mergedNodes[nodeId]) {
1919
+ if (strategy === "patch") {
1920
+ mergedNodes[nodeId] = node;
1921
+ mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1922
+ replaced.push(nodeId);
1923
+ } else {
1924
+ kept.push(nodeId);
1925
+ }
1926
+ } else {
1927
+ mergedNodes[nodeId] = node;
1928
+ mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];
1929
+ added.push(nodeId);
1982
1930
  }
1983
- yDoc.getMap("qi.flow.projections").set("document", {
1984
- draftRevision: Number(yDoc.getMap("qi.flow.meta").get("draftRevision") ?? 0),
1985
- repairedAt: (/* @__PURE__ */ new Date()).toISOString()
1986
- });
1987
- });
1988
- return before;
1989
- }
1990
- function removeFlowNode(yDoc, nodeId, runId) {
1991
- const doc = readFlowDocument(yDoc, resolveRunIdForRead(yDoc, runId));
1992
- if (!doc) return { ok: false, referencedBy: [] };
1993
- const target = doc.nodes.find((n) => n.nodeId === nodeId);
1994
- if (!target) return { ok: false, referencedBy: [] };
1995
- const referencedBy = doc.nodes.filter((n) => n.nodeId !== nodeId && nodeReferences(n, nodeId, target.blockId)).map((n) => n.nodeId);
1996
- if (referencedBy.length > 0) return { ok: false, referencedBy };
1997
- const blockId = target.blockId;
1998
- yDoc.transact(() => {
1999
- removeBlockFromFragment(yDoc.getXmlFragment("document"), blockId);
2000
- yDoc.getMap("qi.flow.nodes").delete(nodeId);
2001
- yDoc.getMap("qi.flow.blockIndex").delete(nodeId);
2002
- const order = yDoc.getArray("qi.flow.order");
2003
- const idx = order.toArray().indexOf(nodeId);
2004
- if (idx >= 0) order.delete(idx, 1);
2005
- const edges = yDoc.getMap("qi.flow.edges");
2006
- for (const key of [...edges.keys()]) {
2007
- const e = edges.get(key);
2008
- if (isYMapLike(e) && (e.get("source") === nodeId || e.get("target") === nodeId)) edges.delete(key);
1931
+ }
1932
+ for (const nodeId of Object.keys(existing.nodes)) {
1933
+ if (!replaced.includes(nodeId)) {
1934
+ kept.push(nodeId);
2009
1935
  }
2010
- advanceDraftRevision(yDoc);
1936
+ }
1937
+ const edgeMap = /* @__PURE__ */ new Map();
1938
+ for (const edge of [...existing.edges, ...incoming.edges]) {
1939
+ if (mergedNodes[edge.source] && mergedNodes[edge.target]) {
1940
+ edgeMap.set(edge.id, edge);
1941
+ }
1942
+ }
1943
+ const edges = Array.from(edgeMap.values());
1944
+ const order = Object.keys(mergedNodes);
1945
+ const blocks = order.map((nodeId) => {
1946
+ const node = mergedNodes[nodeId];
1947
+ return {
1948
+ id: node.blockId,
1949
+ type: COMPILED_BLOCK_TYPE,
1950
+ props: { ...node.props }
1951
+ };
2011
1952
  });
2012
- return { ok: true };
1953
+ const meta = {
1954
+ ...incoming.meta,
1955
+ flowId: existing.meta.flowId,
1956
+ compiledAt: (/* @__PURE__ */ new Date()).toISOString()
1957
+ };
1958
+ return {
1959
+ merged: { meta, blocks, nodes: mergedNodes, edges, order, blockIndex: mergedBlockIndex },
1960
+ added,
1961
+ replaced,
1962
+ kept
1963
+ };
2013
1964
  }
2014
- function reorderFlowNodes(yDoc, order) {
2015
- const orderArr = yDoc.getArray("qi.flow.order");
2016
- const current = orderArr.toArray();
2017
- if (order.length !== current.length) return false;
2018
- if (new Set(order).size !== order.length) return false;
2019
- const currentSet = new Set(current);
2020
- if (!order.every((id) => currentSet.has(id))) return false;
2021
- const blockIndex = yDoc.getMap("qi.flow.blockIndex");
2022
- const fragment = yDoc.getXmlFragment("document");
2023
- yDoc.transact(() => {
2024
- orderArr.delete(0, orderArr.length);
2025
- orderArr.push(order);
2026
- if (!fragmentHasContentBlocks(fragment)) {
2027
- const blocks = readBlocksFromFragment(fragment);
2028
- const byId = new Map(blocks.map((b) => [b.id, b]));
2029
- const orderedIds = order.map((nid) => blockIndex.get(nid)).filter((id) => !!id);
2030
- const ordered = orderedIds.map((id) => byId.get(id)).filter((b) => !!b);
2031
- const extras = blocks.filter((b) => !orderedIds.includes(b.id));
2032
- removeAllFlowBlocks(fragment);
2033
- writeCompiledBlocksToFragment(fragment, [...ordered, ...extras]);
2034
- }
2035
- advanceDraftRevision(yDoc);
1965
+
1966
+ // src/core/lib/flowCompiler/decompile.ts
1967
+ function decompileToBaseUcanFlow(compiled) {
1968
+ const nodeIdByBlockId = {};
1969
+ for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {
1970
+ nodeIdByBlockId[blockId] = nodeId;
1971
+ }
1972
+ const capabilities = compiled.order.map((nodeId) => {
1973
+ const node = compiled.nodes[nodeId];
1974
+ return nodeToCapability(node, nodeIdByBlockId);
2036
1975
  });
2037
- return true;
1976
+ return {
1977
+ kind: "qi.flow.base-ucan",
1978
+ version: "1.0",
1979
+ flowId: compiled.meta.flowId,
1980
+ title: compiled.meta.title,
1981
+ goal: compiled.meta.goal,
1982
+ meta: {
1983
+ rootIssuer: compiled.meta.flowOwnerDid || void 0,
1984
+ flowUri: compiled.meta.flowUri
1985
+ },
1986
+ capabilities
1987
+ };
2038
1988
  }
2039
- function swapFlowBlocks(yDoc, blockIdA, blockIdB) {
2040
- const fragment = yDoc.getXmlFragment("document");
2041
- let ok = false;
2042
- yDoc.transact(() => {
2043
- ok = swapBlocksInFragment(fragment, blockIdA, blockIdB);
2044
- if (!ok) return;
2045
- const blockIndex = yDoc.getMap("qi.flow.blockIndex");
2046
- let nodeA;
2047
- let nodeB;
2048
- for (const [nodeId, bId] of blockIndex.entries()) {
2049
- if (bId === blockIdA) nodeA = nodeId;
2050
- else if (bId === blockIdB) nodeB = nodeId;
1989
+ function nodeToCapability(node, nodeIdByBlockId) {
1990
+ const cap = {
1991
+ id: node.id,
1992
+ can: node.can,
1993
+ with: node.with
1994
+ };
1995
+ if (node.props.inputs) {
1996
+ try {
1997
+ const nb = JSON.parse(node.props.inputs);
1998
+ if (nb && typeof nb === "object" && Object.keys(nb).length > 0) {
1999
+ cap.nb = nb;
2000
+ }
2001
+ } catch {
2051
2002
  }
2052
- if (nodeA && nodeB) {
2053
- const order = yDoc.getArray("qi.flow.order");
2054
- const arr = order.toArray();
2055
- const ia = arr.indexOf(nodeA);
2056
- const ib = arr.indexOf(nodeB);
2057
- if (ia >= 0 && ib >= 0) {
2058
- [arr[ia], arr[ib]] = [arr[ib], arr[ia]];
2059
- order.delete(0, order.length);
2060
- order.push(arr);
2003
+ }
2004
+ if (node.parallelGroup) {
2005
+ cap.parallelGroup = node.parallelGroup;
2006
+ }
2007
+ if (node.phase) {
2008
+ cap.phase = node.phase;
2009
+ }
2010
+ if (node.actor) {
2011
+ cap.actor = { ...node.actor };
2012
+ }
2013
+ const ttl = {};
2014
+ if (node.props.ttlAbsoluteDueDate) ttl.absoluteDueDate = node.props.ttlAbsoluteDueDate;
2015
+ if (node.props.ttlFromEnablement) ttl.fromEnablement = node.props.ttlFromEnablement;
2016
+ if (node.props.ttlFromCommitment) ttl.fromCommitment = node.props.ttlFromCommitment;
2017
+ if (Object.keys(ttl).length > 0) {
2018
+ cap.ttl = ttl;
2019
+ }
2020
+ if (typeof node.props.trigger === "string" && node.props.trigger.length > 0) {
2021
+ try {
2022
+ const trigger = JSON.parse(node.props.trigger);
2023
+ if (trigger && typeof trigger === "object" && typeof trigger.type === "string") {
2024
+ cap.trigger = triggerToNodeIds(trigger, nodeIdByBlockId);
2061
2025
  }
2026
+ } catch {
2062
2027
  }
2063
- advanceDraftRevision(yDoc);
2064
- });
2065
- return ok;
2028
+ }
2029
+ if (node.title && node.title !== node.can) {
2030
+ cap.title = node.title;
2031
+ }
2032
+ if (node.description) {
2033
+ cap.description = node.description;
2034
+ }
2035
+ if (node.props.icon) {
2036
+ cap.icon = node.props.icon;
2037
+ }
2038
+ return cap;
2066
2039
  }
2067
- function updateNodeRuntime(yDoc, blockId, partial, runId) {
2068
- writeActionState(yDoc, resolveRunIdForExecution(yDoc, runId), blockId, partial);
2040
+ function triggerToNodeIds(trigger, nodeIdByBlockId) {
2041
+ if (trigger.type === "block.event" && trigger.sourceBlockId) {
2042
+ return { ...trigger, sourceBlockId: nodeIdByBlockId[trigger.sourceBlockId] ?? trigger.sourceBlockId };
2043
+ }
2044
+ if (trigger.type === "block.event.all" && trigger.sources) {
2045
+ return {
2046
+ ...trigger,
2047
+ sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: nodeIdByBlockId[src.sourceBlockId] ?? src.sourceBlockId }))
2048
+ };
2049
+ }
2050
+ return trigger;
2051
+ }
2052
+
2053
+ // src/core/lib/flowIdentity.ts
2054
+ var FLOW_IDENTITY_EVENT_TYPE = "ixo.qi.flow.identity";
2055
+ function readFlowIdentityDocId(client, roomId) {
2056
+ if (!client || !roomId || typeof client.getRoom !== "function") return "";
2057
+ const creator = readRoomCreatorUserId(client, roomId);
2058
+ if (!creator) return "";
2059
+ const event = client.getRoom(roomId)?.currentState?.getStateEvents?.(FLOW_IDENTITY_EVENT_TYPE, "");
2060
+ if (!event || event.getSender() !== creator) return "";
2061
+ const content = event.getContent?.();
2062
+ return typeof content?.docId === "string" ? content.docId : "";
2063
+ }
2064
+ async function writeFlowIdentity(client, roomId, docId, options = {}) {
2065
+ if (!client || !roomId || !docId) return "no-owner";
2066
+ if (!readFlowOwnerDid(client, roomId)) return "no-owner";
2067
+ const creator = readRoomCreatorUserId(client, roomId);
2068
+ if (!creator || client.getUserId?.() !== creator) return "not-creator";
2069
+ const existing = readFlowIdentityDocId(client, roomId);
2070
+ if (existing === docId) return "already-bound";
2071
+ if (existing && !options.overwrite) return "bound-to-another-doc";
2072
+ const content = { docId };
2073
+ await client.sendStateEvent(roomId, FLOW_IDENTITY_EVENT_TYPE, content, "");
2074
+ return "written";
2075
+ }
2076
+
2077
+ // src/core/lib/flowCompiler/setup.ts
2078
+ import * as Y5 from "yjs";
2079
+ import { MatrixProvider as MatrixProvider2 } from "@ixo/matrix-crdt";
2080
+ async function readFlowAsBaseUcan(options) {
2081
+ const { roomId, matrixClient } = options;
2082
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: false });
2083
+ try {
2084
+ const compiled = readCompiledFlowFromYDoc(yDoc);
2085
+ if (!compiled) return null;
2086
+ const plan = decompileToBaseUcanFlow(compiled);
2087
+ return { plan, compiled, roomId };
2088
+ } finally {
2089
+ provider.dispose();
2090
+ yDoc.destroy();
2091
+ }
2092
+ }
2093
+ function readFlowFromEditor(editor) {
2094
+ const yDoc = editor._yDoc;
2095
+ if (!yDoc) return null;
2096
+ const compiled = readCompiledFlowFromYDoc(yDoc);
2097
+ if (!compiled) return null;
2098
+ const plan = decompileToBaseUcanFlow(compiled);
2099
+ const roomId = editor.getRoomId?.() || "";
2100
+ return { plan, compiled, roomId };
2101
+ }
2102
+ var activeEditor = null;
2103
+ function setActiveEditor(editor) {
2104
+ activeEditor = editor;
2105
+ }
2106
+ function getActiveEditor() {
2107
+ return activeEditor;
2069
2108
  }
2070
- function resetStepRuntime(yDoc, blockId, runId) {
2071
- updateNodeRuntime(yDoc, blockId, { state: "idle", error: void 0, output: {} }, runId);
2109
+ function readFlow() {
2110
+ if (!activeEditor) {
2111
+ console.warn("[readFlow] No active editor registered. Did the editor finish mounting?");
2112
+ return null;
2113
+ }
2114
+ return readFlowFromEditor(activeEditor);
2072
2115
  }
2073
- function setFormAnswers(yDoc, blockId, answers, runId) {
2074
- const resolvedRunId = resolveRunIdForExecution(yDoc, runId);
2075
- const base = readActionState(yDoc, resolvedRunId, blockId);
2076
- const output = base.output && typeof base.output === "object" ? base.output : {};
2077
- const form = output.form && typeof output.form === "object" ? output.form : {};
2078
- writeActionState(yDoc, resolvedRunId, blockId, { output: { ...output, form: { ...form, answers: JSON.stringify(answers) } } });
2116
+ async function setupFlowFromBaseUcan(options) {
2117
+ const { plan: rawPlan, roomId, matrixClient, creatorDid, docId, templateId, strategy = "full" } = options;
2118
+ const identified = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: docId || roomId };
2119
+ const plan = templateId ? stripActiveScheduleBindings(identified) : identified;
2120
+ const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
2121
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
2122
+ let finalCompiled;
2123
+ try {
2124
+ finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, docId, templateId, strategy });
2125
+ await provider.waitForFlush();
2126
+ await bindRoomIdentity(matrixClient, roomId, yDoc);
2127
+ } finally {
2128
+ provider.dispose();
2129
+ yDoc.destroy();
2130
+ }
2131
+ return {
2132
+ compiled: finalCompiled,
2133
+ roomId,
2134
+ flowId: plan.flowId
2135
+ };
2079
2136
  }
2080
- function safeParseJson(value, fallback) {
2081
- if (typeof value !== "string" || value.length === 0) return fallback;
2137
+ async function seedDesignPodTemplateFlow(options) {
2138
+ const { methodId, roomId, matrixClient, creatorDid } = options;
2139
+ const rawPlan = createDesignPodPortalJourneyPlan(methodId);
2140
+ const plan = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: roomId };
2141
+ const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });
2142
+ const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });
2143
+ let finalCompiled;
2082
2144
  try {
2083
- return JSON.parse(value);
2084
- } catch {
2085
- return fallback;
2145
+ finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, strategy: "full" });
2146
+ seedDesignPodMethodDefinition(yDoc, methodId);
2147
+ await provider.waitForFlush();
2148
+ await bindRoomIdentity(matrixClient, roomId, yDoc);
2149
+ } finally {
2150
+ provider.dispose();
2151
+ yDoc.destroy();
2086
2152
  }
2153
+ return { compiled: finalCompiled, roomId, flowId: plan.flowId };
2087
2154
  }
2088
- function advanceDraftRevision(yDoc) {
2089
- const meta = yDoc.getMap("qi.flow.meta");
2090
- const current = Number(meta.get("draftRevision") ?? 0);
2091
- if (meta.get("draftSchemaVersion") !== 1) return current;
2092
- const next = current + 1;
2093
- meta.set("draftRevision", next);
2094
- meta.set(
2095
- "definitionDigest",
2096
- sha256Digest({
2097
- nodes: yDoc.getMap("qi.flow.nodes").toJSON(),
2098
- edges: yDoc.getMap("qi.flow.edges").toJSON(),
2099
- order: yDoc.getArray("qi.flow.order").toArray()
2100
- })
2101
- );
2102
- meta.set("executionSchemaVersion", 3);
2103
- meta.set("draftUpdatedAt", (/* @__PURE__ */ new Date()).toISOString());
2104
- return next;
2155
+ function applyFlowPlanToYDoc(yDoc, options) {
2156
+ const { plan, incomingCompiled, creatorDid, docId, templateId, strategy, runId } = options;
2157
+ const root = yDoc.getMap("root");
2158
+ const fragment = yDoc.getXmlFragment("document");
2159
+ const existingFlow = readCompiledFlowFromYDoc(yDoc);
2160
+ if (strategy === "full") {
2161
+ if (existingFlow) {
2162
+ clearFlowState(yDoc);
2163
+ removeAllFlowBlocks(fragment);
2164
+ }
2165
+ setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
2166
+ hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
2167
+ if (!existingFlow) {
2168
+ initializeRuntime(yDoc, incomingCompiled, runId);
2169
+ }
2170
+ yDoc.transact(() => {
2171
+ writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
2172
+ });
2173
+ return incomingCompiled;
2174
+ }
2175
+ if (!existingFlow) {
2176
+ setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);
2177
+ hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);
2178
+ initializeRuntime(yDoc, incomingCompiled, runId);
2179
+ yDoc.transact(() => {
2180
+ writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);
2181
+ });
2182
+ return incomingCompiled;
2183
+ }
2184
+ const mergeResult = mergeCompiledFlows(existingFlow, incomingCompiled, strategy);
2185
+ hydrateYDocFromMergeResult(yDoc, mergeResult);
2186
+ const nodesToInit = [...mergeResult.added, ...mergeResult.replaced];
2187
+ initializeRuntimeForNodes(yDoc, mergeResult.merged, nodesToInit, runId);
2188
+ yDoc.transact(() => {
2189
+ applyMergeResultToFragment(fragment, mergeResult);
2190
+ });
2191
+ return mergeResult.merged;
2105
2192
  }
2106
- function stableProps(props) {
2107
- return JSON.stringify(
2108
- Object.fromEntries(
2109
- Object.entries(props).filter(([, value]) => value !== "").sort(([left], [right]) => left.localeCompare(right))
2110
- )
2193
+ async function connectToRoom(roomId, matrixClient, options) {
2194
+ const yDoc = new Y5.Doc();
2195
+ const client = matrixClient;
2196
+ client.canSupportVoip = false;
2197
+ client.clientOpts = { lazyLoadMembers: true };
2198
+ const provider = new MatrixProvider2(
2199
+ yDoc,
2200
+ client,
2201
+ { type: "id", id: roomId },
2202
+ {
2203
+ translator: {
2204
+ updateEventType: "matrix-crdt.doc_update",
2205
+ snapshotEventType: "matrix-crdt.doc_snapshot",
2206
+ enableMediaSnapshots: true
2207
+ },
2208
+ enableExperimentalWebrtcSync: false,
2209
+ enableAwareness: false,
2210
+ reader: { snapshotInterval: 10 },
2211
+ writer: { flushInterval: 300, retryIfForbiddenInterval: 3e4 }
2212
+ }
2111
2213
  );
2112
- }
2113
- function findNodeIdForBlock(yDoc, blockId) {
2114
- const blockIndex = yDoc.getMap("qi.flow.blockIndex");
2115
- for (const [nodeId, bId] of blockIndex.entries()) {
2116
- if (bId === blockId) return nodeId;
2214
+ await new Promise((resolve, reject) => {
2215
+ const timeout = setTimeout(() => {
2216
+ reject(new Error(`Timed out connecting to room ${roomId}`));
2217
+ }, 3e4);
2218
+ provider.onDocumentAvailable(() => {
2219
+ clearTimeout(timeout);
2220
+ resolve();
2221
+ });
2222
+ provider.onDocumentUnavailable(() => {
2223
+ clearTimeout(timeout);
2224
+ reject(new Error(`Room ${roomId} is unavailable`));
2225
+ });
2226
+ provider.initialize().catch((err) => {
2227
+ clearTimeout(timeout);
2228
+ reject(err);
2229
+ });
2230
+ });
2231
+ if (options.adoptRuns && provider.canWrite) {
2232
+ collectPhantomLegacyRun(yDoc);
2117
2233
  }
2118
- return void 0;
2119
- }
2120
- function actorFromProps(props) {
2121
- const authorisedActors = safeParseJson(props.authorisedActors, void 0);
2122
- const parentCapability = props.parentCapability && props.parentCapability.length > 0 ? props.parentCapability : void 0;
2123
- const hasActors = Array.isArray(authorisedActors) && authorisedActors.length > 0;
2124
- if (!hasActors && !parentCapability) return void 0;
2125
- const actor = {};
2126
- if (hasActors) actor.authorisedActors = authorisedActors;
2127
- if (parentCapability) actor.parentCapability = parentCapability;
2128
- return actor;
2129
- }
2130
- function nodeReferences(node, nodeId, blockId) {
2131
- const trigger = safeParseJson(node.props.trigger, void 0);
2132
- if (trigger?.sourceBlockId === nodeId || trigger?.sourceBlockId === blockId) return true;
2133
- if (Array.isArray(trigger?.sources) && trigger.sources.some((s) => s?.sourceBlockId === nodeId || s?.sourceBlockId === blockId)) return true;
2134
- const cond = safeParseJson(node.props.conditions, void 0);
2135
- if (Array.isArray(cond?.conditions) && cond.conditions.some((c) => c?.sourceBlockId === blockId)) return true;
2136
- const inputs = typeof node.props.inputs === "string" ? node.props.inputs : "";
2137
- if (inputs.includes(`${nodeId}.output`)) return true;
2138
- return false;
2234
+ bindFlowOwnerFromRoom(yDoc, client, roomId);
2235
+ return { yDoc, provider };
2139
2236
  }
2140
- function fragmentHasContentBlocks(fragment) {
2141
- if (fragment.length === 0) return false;
2142
- const root = fragment.get(0);
2143
- if (!isYXmlElementLike(root) || root.nodeName !== "blockGroup") return false;
2144
- for (let i = 0; i < root.length; i++) {
2145
- const container = root.get(i);
2146
- if (!isYXmlElementLike(container)) continue;
2147
- const content = container.get(0);
2148
- if (isYXmlElementLike(content) && content.length > 0) return true;
2237
+ async function bindRoomIdentity(matrixClient, roomId, yDoc) {
2238
+ const docId = yDoc.getMap("root").get("doc_id");
2239
+ if (typeof docId !== "string" || !docId) return;
2240
+ try {
2241
+ await writeFlowIdentity(matrixClient, roomId, docId);
2242
+ } catch (error) {
2243
+ console.warn("Could not write the flow identity event:", error);
2149
2244
  }
2150
- return false;
2245
+ }
2246
+ function setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId) {
2247
+ yDoc.transact(() => {
2248
+ if (!root.get("@context")) root.set("@context", "https://ixo.world/flow/0.3");
2249
+ if (!root.get("_type")) root.set("_type", "ixo.flow.crdt");
2250
+ if (!root.get("schema_version")) root.set("schema_version", "0.3");
2251
+ if (!root.get("doc_id")) root.set("doc_id", docId || plan.flowId);
2252
+ if (!root.get("createdAt")) root.set("createdAt", (/* @__PURE__ */ new Date()).toISOString());
2253
+ if (!root.get("createdBy")) root.set("createdBy", creatorDid);
2254
+ const roomCreator = flowOwnerOf(yDoc);
2255
+ if (roomCreator) root.set("flowOwnerDid", roomCreator);
2256
+ else if (!root.get("flowOwnerDid")) root.set("flowOwnerDid", creatorDid);
2257
+ if (!hasLegacyRuntimeHistory(yDoc)) setMultiRunStorage(yDoc);
2258
+ if (templateId && !root.get("source_template_id")) {
2259
+ root.set("source_template_id", templateId);
2260
+ }
2261
+ const titleText = yDoc.getText("title");
2262
+ if (titleText.length === 0 && plan.title) {
2263
+ titleText.insert(0, plan.title);
2264
+ }
2265
+ });
2151
2266
  }
2152
2267
 
2153
2268
  // src/core/lib/flowAgent/policy.ts
@@ -2346,15 +2461,19 @@ function classifyBlockerCause(block, runtime) {
2346
2461
  return void 0;
2347
2462
  }
2348
2463
  function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0, completionVerification }) {
2464
+ const actionType = getBlockActionType(block);
2465
+ const done = !!actionType && isActionTypeDone(actionType, runtime, { runId: "", nodeId: getBlockId(block), now });
2349
2466
  const derived = deriveBlockPhase({
2350
2467
  runtime,
2351
- actionType: getBlockActionType(block),
2468
+ actionType,
2352
2469
  completionVerification,
2353
- pendingInvocationCount
2470
+ pendingInvocationCount,
2471
+ done
2354
2472
  });
2355
2473
  if (derived.phase === "failed") return "Blocked";
2356
2474
  if (derived.phase === "complete") return "Done";
2357
- if (derived.detail === "standing" && pendingInvocationCount === 0) return "Done";
2475
+ const requiresFold = !!actionType && getAction(actionType)?.done?.standingDoneRequiresFold === true;
2476
+ if (derived.detail === "standing" && pendingInvocationCount === 0 && (!requiresFold || done)) return "Done";
2358
2477
  if (runtime.error) return "Blocked";
2359
2478
  const dueAt = getDueAt(block);
2360
2479
  if (dueAt != null && dueAt <= now) return "Overdue";
@@ -3330,35 +3449,15 @@ var FlowAgentService = class {
3330
3449
 
3331
3450
  export {
3332
3451
  createUcanRunLifecycleAuthorizer,
3333
- readFlowDocumentHistory,
3334
- getSharedFlowDocument,
3335
- COMPILED_BLOCK_TYPE,
3336
- toEvaluatorOperator,
3337
- buildBlockConditionsProp,
3338
- compileBaseUcanFlow,
3452
+ readCompiledFlowFromYDoc,
3339
3453
  ACTION_SAFETY_BY_TYPE,
3340
3454
  resolveActionSafety,
3341
3455
  ensureFlowExecutionMetadata,
3342
3456
  adoptLegacyFlowDocument,
3343
- legacyPropsByBlockId,
3344
- createYMapFromNode,
3345
3457
  writeCompiledBlocksToFragment,
3346
3458
  removeBlockFromFragment,
3347
3459
  replaceBlockInFragment,
3348
3460
  readBlocksFromFragment,
3349
- readCompiledFlowFromYDoc,
3350
- mergeCompiledFlows,
3351
- decompileToBaseUcanFlow,
3352
- FLOW_IDENTITY_EVENT_TYPE,
3353
- readFlowIdentityDocId,
3354
- writeFlowIdentity,
3355
- readFlowAsBaseUcan,
3356
- readFlowFromEditor,
3357
- setActiveEditor,
3358
- getActiveEditor,
3359
- readFlow,
3360
- setupFlowFromBaseUcan,
3361
- seedDesignPodTemplateFlow,
3362
3461
  readFlowDocument,
3363
3462
  addFlowNode,
3364
3463
  setBlockProps,
@@ -3371,6 +3470,26 @@ export {
3371
3470
  updateNodeRuntime,
3372
3471
  resetStepRuntime,
3373
3472
  setFormAnswers,
3473
+ governedByStepList,
3474
+ findUnlistedActionBlocks,
3475
+ addUnlistedSteps,
3476
+ readFlowDocumentHistory,
3477
+ getSharedFlowDocument,
3478
+ toEvaluatorOperator,
3479
+ buildBlockConditionsProp,
3480
+ compileBaseUcanFlow,
3481
+ mergeCompiledFlows,
3482
+ decompileToBaseUcanFlow,
3483
+ FLOW_IDENTITY_EVENT_TYPE,
3484
+ readFlowIdentityDocId,
3485
+ writeFlowIdentity,
3486
+ readFlowAsBaseUcan,
3487
+ readFlowFromEditor,
3488
+ setActiveEditor,
3489
+ getActiveEditor,
3490
+ readFlow,
3491
+ setupFlowFromBaseUcan,
3492
+ seedDesignPodTemplateFlow,
3374
3493
  requiredCapabilityForCommand,
3375
3494
  isCapabilityMatch,
3376
3495
  canMatches,
@@ -3394,4 +3513,4 @@ export {
3394
3513
  executeQueuedFlowAgentCoreCommands,
3395
3514
  FlowAgentService
3396
3515
  };
3397
- //# sourceMappingURL=chunk-SCLMJ7FE.js.map
3516
+ //# sourceMappingURL=chunk-FYPDR7DJ.js.map