@ixo/editor 6.33.0 → 6.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (526) hide show
  1. package/dist/BidConfig-YLGSEIOS.js +154 -0
  2. package/dist/BidConfig-YLGSEIOS.js.map +1 -0
  3. package/dist/BidFlowDetail-U2SX5M7F.js +365 -0
  4. package/dist/BidFlowDetail-U2SX5M7F.js.map +1 -0
  5. package/dist/CalendarEventCreateConfig-J2LU6LJO.js +155 -0
  6. package/dist/CalendarEventCreateConfig-J2LU6LJO.js.map +1 -0
  7. package/dist/CalendarEventCreateFlowDetail-ZWHZWDOK.js +174 -0
  8. package/dist/CalendarEventCreateFlowDetail-ZWHZWDOK.js.map +1 -0
  9. package/dist/CalendarEventListConfig-GQNNF4ZB.js +116 -0
  10. package/dist/CalendarEventListConfig-GQNNF4ZB.js.map +1 -0
  11. package/dist/CalendarEventListFlowDetail-SSRTOXIX.js +58 -0
  12. package/dist/CalendarEventListFlowDetail-SSRTOXIX.js.map +1 -0
  13. package/dist/CalendarEventUpdateConfig-KACZA6GH.js +133 -0
  14. package/dist/CalendarEventUpdateConfig-KACZA6GH.js.map +1 -0
  15. package/dist/CalendarEventUpdateFlowDetail-CD6NHHOU.js +155 -0
  16. package/dist/CalendarEventUpdateFlowDetail-CD6NHHOU.js.map +1 -0
  17. package/dist/ClaimConfig-3HKPGK55.js +200 -0
  18. package/dist/ClaimConfig-3HKPGK55.js.map +1 -0
  19. package/dist/ClaimFlowDetail-I4OQSHAB.js +641 -0
  20. package/dist/ClaimFlowDetail-I4OQSHAB.js.map +1 -0
  21. package/dist/CollectionLifecycleConfig-LCCGZ3CJ.js +149 -0
  22. package/dist/CollectionLifecycleConfig-LCCGZ3CJ.js.map +1 -0
  23. package/dist/CollectionLifecycleFlowDetail-LQHKB227.js +647 -0
  24. package/dist/CollectionLifecycleFlowDetail-LQHKB227.js.map +1 -0
  25. package/dist/CollectionUsersConfig-RI2X3YY2.js +271 -0
  26. package/dist/CollectionUsersConfig-RI2X3YY2.js.map +1 -0
  27. package/dist/CollectionUsersFlowDetail-LHXVCCPQ.js +1276 -0
  28. package/dist/CollectionUsersFlowDetail-LHXVCCPQ.js.map +1 -0
  29. package/dist/CredentialStoreConfig-G66AQDGZ.js +75 -0
  30. package/dist/CredentialStoreConfig-G66AQDGZ.js.map +1 -0
  31. package/dist/CredentialStoreFlowDetail-FL7QAM3S.js +99 -0
  32. package/dist/CredentialStoreFlowDetail-FL7QAM3S.js.map +1 -0
  33. package/dist/DesignPodConfig-LJ7H2CZ6.js +8 -0
  34. package/dist/DesignPodConfig-LJ7H2CZ6.js.map +1 -0
  35. package/dist/DesignPodFlowDetail-JHJWGNVY.js +309 -0
  36. package/dist/DesignPodFlowDetail-JHJWGNVY.js.map +1 -0
  37. package/dist/DomainCardPreviewConfig-Q3X5M4WF.js +37 -0
  38. package/dist/DomainCardPreviewConfig-Q3X5M4WF.js.map +1 -0
  39. package/dist/DomainCardPreviewFlowDetail-Y2FE7O5Z.js +131 -0
  40. package/dist/DomainCardPreviewFlowDetail-Y2FE7O5Z.js.map +1 -0
  41. package/dist/DomainIndexerLookupConfig-N4VONQUY.js +41 -0
  42. package/dist/DomainIndexerLookupConfig-N4VONQUY.js.map +1 -0
  43. package/dist/DomainIndexerLookupFlowDetail-GJ7WWK7I.js +70 -0
  44. package/dist/DomainIndexerLookupFlowDetail-GJ7WWK7I.js.map +1 -0
  45. package/dist/DomainSignConfig-XFIXROVK.js +47 -0
  46. package/dist/DomainSignConfig-XFIXROVK.js.map +1 -0
  47. package/dist/DomainSignFlowDetail-BXZ6JBPR.js +206 -0
  48. package/dist/DomainSignFlowDetail-BXZ6JBPR.js.map +1 -0
  49. package/dist/DomainSingleSelectionConfig-ZNKIXB4P.js +101 -0
  50. package/dist/DomainSingleSelectionConfig-ZNKIXB4P.js.map +1 -0
  51. package/dist/DomainSingleSelectionFlowDetail-HWTQXSLA.js +147 -0
  52. package/dist/DomainSingleSelectionFlowDetail-HWTQXSLA.js.map +1 -0
  53. package/dist/EmailSendConfig-YEGZ5Q77.js +215 -0
  54. package/dist/EmailSendConfig-YEGZ5Q77.js.map +1 -0
  55. package/dist/EntityCreateOracleConfig-UZ6ZIMP5.js +150 -0
  56. package/dist/EntityCreateOracleConfig-UZ6ZIMP5.js.map +1 -0
  57. package/dist/EntityCreateOracleFlowDetail-H2X7CPYU.js +120 -0
  58. package/dist/EntityCreateOracleFlowDetail-H2X7CPYU.js.map +1 -0
  59. package/dist/EntitySingleSelectionConfig-DL57KNKM.js +30 -0
  60. package/dist/EntitySingleSelectionConfig-DL57KNKM.js.map +1 -0
  61. package/dist/EntitySingleSelectionFlowDetail-GFQGX3GA.js +118 -0
  62. package/dist/EntitySingleSelectionFlowDetail-GFQGX3GA.js.map +1 -0
  63. package/dist/EntityTransferConfig-JVZ3H35B.js +62 -0
  64. package/dist/EntityTransferConfig-JVZ3H35B.js.map +1 -0
  65. package/dist/EntityTransferFlowDetail-XEXM34XB.js +132 -0
  66. package/dist/EntityTransferFlowDetail-XEXM34XB.js.map +1 -0
  67. package/dist/EvalEngineConfig-CHC4IRN3.js +464 -0
  68. package/dist/EvalEngineConfig-CHC4IRN3.js.map +1 -0
  69. package/dist/EvalEngineFlowDetail-PUFRNO4U.js +4291 -0
  70. package/dist/EvalEngineFlowDetail-PUFRNO4U.js.map +1 -0
  71. package/dist/EvaluateBidConfig-OE4CM43G.js +151 -0
  72. package/dist/EvaluateBidConfig-OE4CM43G.js.map +1 -0
  73. package/dist/EvaluateBidFlowDetail-2EXGNBYC.js +564 -0
  74. package/dist/EvaluateBidFlowDetail-2EXGNBYC.js.map +1 -0
  75. package/dist/EvaluateClaimConfig-3D4F5LHU.js +297 -0
  76. package/dist/EvaluateClaimConfig-3D4F5LHU.js.map +1 -0
  77. package/dist/EvaluateClaimFlowDetail-QKHJVEDE.js +2237 -0
  78. package/dist/EvaluateClaimFlowDetail-QKHJVEDE.js.map +1 -0
  79. package/dist/FormSubmitConfig-UFZYMLUN.js +59 -0
  80. package/dist/FormSubmitConfig-UFZYMLUN.js.map +1 -0
  81. package/dist/FormSubmitFlowDetail-IAHDJS6P.js +169 -0
  82. package/dist/FormSubmitFlowDetail-IAHDJS6P.js.map +1 -0
  83. package/dist/GovernanceAuthzExecFlowDetail-SQBGU5BX.js +166 -0
  84. package/dist/GovernanceAuthzExecFlowDetail-SQBGU5BX.js.map +1 -0
  85. package/dist/GovernanceAuthzGrantFlowDetail-DZPNLANT.js +88 -0
  86. package/dist/GovernanceAuthzGrantFlowDetail-DZPNLANT.js.map +1 -0
  87. package/dist/GovernanceAuthzRevokeFlowDetail-3JZ4IUJG.js +88 -0
  88. package/dist/GovernanceAuthzRevokeFlowDetail-3JZ4IUJG.js.map +1 -0
  89. package/dist/GovernanceChainVoteFlowDetail-475UDNG6.js +83 -0
  90. package/dist/GovernanceChainVoteFlowDetail-475UDNG6.js.map +1 -0
  91. package/dist/GovernanceConfigConfig-V3WM4WBP.js +30 -0
  92. package/dist/GovernanceConfigConfig-V3WM4WBP.js.map +1 -0
  93. package/dist/GovernanceConfigFlowDetail-SQ5PPDRX.js +267 -0
  94. package/dist/GovernanceConfigFlowDetail-SQ5PPDRX.js.map +1 -0
  95. package/dist/GovernanceContractExecuteFlowDetail-H2ZV6W2E.js +113 -0
  96. package/dist/GovernanceContractExecuteFlowDetail-H2ZV6W2E.js.map +1 -0
  97. package/dist/GovernanceContractInstantiateFlowDetail-YJJMGM54.js +144 -0
  98. package/dist/GovernanceContractInstantiateFlowDetail-YJJMGM54.js.map +1 -0
  99. package/dist/GovernanceContractManageCw20FlowDetail-OCBMW3YJ.js +72 -0
  100. package/dist/GovernanceContractManageCw20FlowDetail-OCBMW3YJ.js.map +1 -0
  101. package/dist/GovernanceContractMigrateFlowDetail-JDNIKTT3.js +104 -0
  102. package/dist/GovernanceContractMigrateFlowDetail-JDNIKTT3.js.map +1 -0
  103. package/dist/GovernanceContractUpdateAdminFlowDetail-SZBOAOCC.js +68 -0
  104. package/dist/GovernanceContractUpdateAdminFlowDetail-SZBOAOCC.js.map +1 -0
  105. package/dist/GovernanceCustomMessageFlowDetail-CXD4ZATO.js +78 -0
  106. package/dist/GovernanceCustomMessageFlowDetail-CXD4ZATO.js.map +1 -0
  107. package/dist/GovernanceDaoAcceptToMarketplaceFlowDetail-Q6ZBNY7Z.js +98 -0
  108. package/dist/GovernanceDaoAcceptToMarketplaceFlowDetail-Q6ZBNY7Z.js.map +1 -0
  109. package/dist/GovernanceDaoAdminExecFlowDetail-JAEAY2US.js +94 -0
  110. package/dist/GovernanceDaoAdminExecFlowDetail-JAEAY2US.js.map +1 -0
  111. package/dist/GovernanceDaoCreateEntityFlowDetail-7RVNTVAB.js +96 -0
  112. package/dist/GovernanceDaoCreateEntityFlowDetail-7RVNTVAB.js.map +1 -0
  113. package/dist/GovernanceDaoJoinFlowDetail-XYCTCNHO.js +68 -0
  114. package/dist/GovernanceDaoJoinFlowDetail-XYCTCNHO.js.map +1 -0
  115. package/dist/GovernanceDaoManageStorageFlowDetail-LMLYLYYC.js +93 -0
  116. package/dist/GovernanceDaoManageStorageFlowDetail-LMLYLYYC.js.map +1 -0
  117. package/dist/GovernanceDaoManageSubDaosFlowDetail-YUFQ67JN.js +84 -0
  118. package/dist/GovernanceDaoManageSubDaosFlowDetail-YUFQ67JN.js.map +1 -0
  119. package/dist/GovernanceDaoUpdateInfoFlowDetail-G5FIBY4L.js +104 -0
  120. package/dist/GovernanceDaoUpdateInfoFlowDetail-G5FIBY4L.js.map +1 -0
  121. package/dist/GovernanceMemberProposalConfig-IGPXEFDB.js +42 -0
  122. package/dist/GovernanceMemberProposalConfig-IGPXEFDB.js.map +1 -0
  123. package/dist/GovernanceMemberProposalFlowDetail-T3VURONF.js +240 -0
  124. package/dist/GovernanceMemberProposalFlowDetail-T3VURONF.js.map +1 -0
  125. package/dist/GovernanceNftBurnFlowDetail-AG4I2O7H.js +69 -0
  126. package/dist/GovernanceNftBurnFlowDetail-AG4I2O7H.js.map +1 -0
  127. package/dist/GovernanceNftManageCollectionsFlowDetail-UAAGO3Q6.js +71 -0
  128. package/dist/GovernanceNftManageCollectionsFlowDetail-UAAGO3Q6.js.map +1 -0
  129. package/dist/GovernanceNftTransferFlowDetail-KXM7DTOV.js +130 -0
  130. package/dist/GovernanceNftTransferFlowDetail-KXM7DTOV.js.map +1 -0
  131. package/dist/GovernanceSettingsProposalConfig-4SLJTBLW.js +42 -0
  132. package/dist/GovernanceSettingsProposalConfig-4SLJTBLW.js.map +1 -0
  133. package/dist/GovernanceSettingsProposalFlowDetail-VFZPSCLR.js +165 -0
  134. package/dist/GovernanceSettingsProposalFlowDetail-VFZPSCLR.js.map +1 -0
  135. package/dist/GovernanceStakingStakeFlowDetail-ULLJ7FLM.js +123 -0
  136. package/dist/GovernanceStakingStakeFlowDetail-ULLJ7FLM.js.map +1 -0
  137. package/dist/GovernanceStakingStakeToGroupFlowDetail-CSPKJA3H.js +84 -0
  138. package/dist/GovernanceStakingStakeToGroupFlowDetail-CSPKJA3H.js.map +1 -0
  139. package/dist/GovernanceSubmissionConfigProposalFlowDetail-MZCPSZF2.js +111 -0
  140. package/dist/GovernanceSubmissionConfigProposalFlowDetail-MZCPSZF2.js.map +1 -0
  141. package/dist/GovernanceTransactionMintFlowDetail-Y2WRAODH.js +66 -0
  142. package/dist/GovernanceTransactionMintFlowDetail-Y2WRAODH.js.map +1 -0
  143. package/dist/GovernanceTransactionPerformTokenSwapFlowDetail-GEK6PMMI.js +133 -0
  144. package/dist/GovernanceTransactionPerformTokenSwapFlowDetail-GEK6PMMI.js.map +1 -0
  145. package/dist/GovernanceTransactionSendFundsConfig-VBKMLSF3.js +42 -0
  146. package/dist/GovernanceTransactionSendFundsConfig-VBKMLSF3.js.map +1 -0
  147. package/dist/GovernanceTransactionSendFundsFlowDetail-5TZB64VL.js +182 -0
  148. package/dist/GovernanceTransactionSendFundsFlowDetail-5TZB64VL.js.map +1 -0
  149. package/dist/GovernanceTransactionSendGroupTokenFlowDetail-EGOWVZM2.js +155 -0
  150. package/dist/GovernanceTransactionSendGroupTokenFlowDetail-EGOWVZM2.js.map +1 -0
  151. package/dist/GovernanceTransactionWithdrawTokenSwapFlowDetail-6XWVO5O6.js +56 -0
  152. package/dist/GovernanceTransactionWithdrawTokenSwapFlowDetail-6XWVO5O6.js.map +1 -0
  153. package/dist/GovernanceValidatorActionsFlowDetail-ZMLPAFUB.js +117 -0
  154. package/dist/GovernanceValidatorActionsFlowDetail-ZMLPAFUB.js.map +1 -0
  155. package/dist/HarvestConfig-AIGOGBFR.js +56 -0
  156. package/dist/HarvestConfig-AIGOGBFR.js.map +1 -0
  157. package/dist/HarvestFlowDetail-X3RUH3X3.js +131 -0
  158. package/dist/HarvestFlowDetail-X3RUH3X3.js.map +1 -0
  159. package/dist/HttpRequestConfig-OQEJIIJY.js +194 -0
  160. package/dist/HttpRequestConfig-OQEJIIJY.js.map +1 -0
  161. package/dist/HttpRequestFlowDetail-JVLV533Z.js +116 -0
  162. package/dist/HttpRequestFlowDetail-JVLV533Z.js.map +1 -0
  163. package/dist/IdentityCreateConfig-ZBUOJ6AL.js +94 -0
  164. package/dist/IdentityCreateConfig-ZBUOJ6AL.js.map +1 -0
  165. package/dist/IdentityCreateFlowDetail-4TE6UCEB.js +83 -0
  166. package/dist/IdentityCreateFlowDetail-4TE6UCEB.js.map +1 -0
  167. package/dist/IidCreateConfig-RRV2DYXI.js +75 -0
  168. package/dist/IidCreateConfig-RRV2DYXI.js.map +1 -0
  169. package/dist/IidCreateFlowDetail-HPVZAHVY.js +57 -0
  170. package/dist/IidCreateFlowDetail-HPVZAHVY.js.map +1 -0
  171. package/dist/KycVerifyConfig-VCG65K5K.js +65 -0
  172. package/dist/KycVerifyConfig-VCG65K5K.js.map +1 -0
  173. package/dist/KycVerifyFlowDetail-FEU43HML.js +421 -0
  174. package/dist/KycVerifyFlowDetail-FEU43HML.js.map +1 -0
  175. package/dist/ListDomainFlowsConfig-3JZEPTOJ.js +37 -0
  176. package/dist/ListDomainFlowsConfig-3JZEPTOJ.js.map +1 -0
  177. package/dist/ListDomainFlowsFlowDetail-XX5AXDZZ.js +257 -0
  178. package/dist/ListDomainFlowsFlowDetail-XX5AXDZZ.js.map +1 -0
  179. package/dist/LoadBatchesConfig-IMODIWRT.js +38 -0
  180. package/dist/LoadBatchesConfig-IMODIWRT.js.map +1 -0
  181. package/dist/LoadBatchesFlowDetail-GB24T76O.js +101 -0
  182. package/dist/LoadBatchesFlowDetail-GB24T76O.js.map +1 -0
  183. package/dist/MatrixDmConfig-NBII27CS.js +120 -0
  184. package/dist/MatrixDmConfig-NBII27CS.js.map +1 -0
  185. package/dist/MatrixRegisterConfig-N2U4FBYF.js +62 -0
  186. package/dist/MatrixRegisterConfig-N2U4FBYF.js.map +1 -0
  187. package/dist/MatrixRegisterFlowDetail-D5YNL5QX.js +86 -0
  188. package/dist/MatrixRegisterFlowDetail-D5YNL5QX.js.map +1 -0
  189. package/dist/MemberMultiSelectConfig-E7WUB2WD.js +30 -0
  190. package/dist/MemberMultiSelectConfig-E7WUB2WD.js.map +1 -0
  191. package/dist/MemberMultiSelectFlowDetail-6C4ZMSDR.js +392 -0
  192. package/dist/MemberMultiSelectFlowDetail-6C4ZMSDR.js.map +1 -0
  193. package/dist/OracleConfig-R7TDTTKN.js +56 -0
  194. package/dist/OracleConfig-R7TDTTKN.js.map +1 -0
  195. package/dist/OracleConfigureOracleConfig-QFF74X3N.js +198 -0
  196. package/dist/OracleConfigureOracleConfig-QFF74X3N.js.map +1 -0
  197. package/dist/OracleConfigureOracleFlowDetail-MIBXUEKC.js +255 -0
  198. package/dist/OracleConfigureOracleFlowDetail-MIBXUEKC.js.map +1 -0
  199. package/dist/OracleContractConfig-PHY5L7W2.js +38 -0
  200. package/dist/OracleContractConfig-PHY5L7W2.js.map +1 -0
  201. package/dist/OracleContractFlowDetail-M3PM4AU4.js +78 -0
  202. package/dist/OracleContractFlowDetail-M3PM4AU4.js.map +1 -0
  203. package/dist/OracleDeployConfig-QBG76ATZ.js +10 -0
  204. package/dist/OracleDeployConfig-QBG76ATZ.js.map +1 -0
  205. package/dist/OracleDeployFlowDetail-WKTMD2AD.js +231 -0
  206. package/dist/OracleDeployFlowDetail-WKTMD2AD.js.map +1 -0
  207. package/dist/OracleDeploySetupConfig-75XPGFJQ.js +10 -0
  208. package/dist/OracleDeploySetupConfig-75XPGFJQ.js.map +1 -0
  209. package/dist/OracleDeploySetupFlowDetail-R3BQ7EAU.js +165 -0
  210. package/dist/OracleDeploySetupFlowDetail-R3BQ7EAU.js.map +1 -0
  211. package/dist/OracleDeployStartConfig-NA6GZ4VQ.js +10 -0
  212. package/dist/OracleDeployStartConfig-NA6GZ4VQ.js.map +1 -0
  213. package/dist/OracleDeployStartFlowDetail-EL3CMDMG.js +89 -0
  214. package/dist/OracleDeployStartFlowDetail-EL3CMDMG.js.map +1 -0
  215. package/dist/OracleFlowDetail-5JCJK3GH.js +76 -0
  216. package/dist/OracleFlowDetail-5JCJK3GH.js.map +1 -0
  217. package/dist/OraclePromptConfig-YBRESISH.js +39 -0
  218. package/dist/OraclePromptConfig-YBRESISH.js.map +1 -0
  219. package/dist/OraclePromptFlowDetail-O3XNK7HY.js +112 -0
  220. package/dist/OraclePromptFlowDetail-O3XNK7HY.js.map +1 -0
  221. package/dist/OracleStoreConfigConfig-TUZWTJMA.js +134 -0
  222. package/dist/OracleStoreConfigConfig-TUZWTJMA.js.map +1 -0
  223. package/dist/OracleStoreConfigFlowDetail-Q6AUUSUL.js +99 -0
  224. package/dist/OracleStoreConfigFlowDetail-Q6AUUSUL.js.map +1 -0
  225. package/dist/OracleStoreSecretsAndConfigConfig-SZPYEK7U.js +198 -0
  226. package/dist/OracleStoreSecretsAndConfigConfig-SZPYEK7U.js.map +1 -0
  227. package/dist/OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js +220 -0
  228. package/dist/OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js.map +1 -0
  229. package/dist/OracleStoreSecretsConfig-PQMF7LFT.js +191 -0
  230. package/dist/OracleStoreSecretsConfig-PQMF7LFT.js.map +1 -0
  231. package/dist/OracleStoreSecretsFlowDetail-5RXWQ3KA.js +197 -0
  232. package/dist/OracleStoreSecretsFlowDetail-5RXWQ3KA.js.map +1 -0
  233. package/dist/ProposalCreateConfig-U5IHZNT7.js +161 -0
  234. package/dist/ProposalCreateConfig-U5IHZNT7.js.map +1 -0
  235. package/dist/ProposalCreateFlowDetail-2FCRCNYV.js +235 -0
  236. package/dist/ProposalCreateFlowDetail-2FCRCNYV.js.map +1 -0
  237. package/dist/ProposalVoteConfig-MH4MU7SL.js +150 -0
  238. package/dist/ProposalVoteConfig-MH4MU7SL.js.map +1 -0
  239. package/dist/ProposalVoteFlowDetail-IJJ3OHAB.js +280 -0
  240. package/dist/ProposalVoteFlowDetail-IJJ3OHAB.js.map +1 -0
  241. package/dist/ProtocolSelectConfig-S5U3P6K7.js +48 -0
  242. package/dist/ProtocolSelectConfig-S5U3P6K7.js.map +1 -0
  243. package/dist/ProtocolSelectFlowDetail-XBSJIEIH.js +116 -0
  244. package/dist/ProtocolSelectFlowDetail-XBSJIEIH.js.map +1 -0
  245. package/dist/RetireConfig-MV37WWZ6.js +59 -0
  246. package/dist/RetireConfig-MV37WWZ6.js.map +1 -0
  247. package/dist/RetireFlowDetail-VZ5O4SXI.js +147 -0
  248. package/dist/RetireFlowDetail-VZ5O4SXI.js.map +1 -0
  249. package/dist/SandboxProvisionConfig-ZGG4IRHM.js +46 -0
  250. package/dist/SandboxProvisionConfig-ZGG4IRHM.js.map +1 -0
  251. package/dist/SandboxProvisionFlowDetail-RUY64INV.js +79 -0
  252. package/dist/SandboxProvisionFlowDetail-RUY64INV.js.map +1 -0
  253. package/dist/WalletFundConfig-CMM3EP3B.js +117 -0
  254. package/dist/WalletFundConfig-CMM3EP3B.js.map +1 -0
  255. package/dist/WalletFundFlowDetail-TXWCZA4K.js +279 -0
  256. package/dist/WalletFundFlowDetail-TXWCZA4K.js.map +1 -0
  257. package/dist/WalletGenerateAndFundConfig-364RSEND.js +10 -0
  258. package/dist/WalletGenerateAndFundConfig-364RSEND.js.map +1 -0
  259. package/dist/WalletGenerateAndFundFlowDetail-C2LZW3NO.js +54 -0
  260. package/dist/WalletGenerateAndFundFlowDetail-C2LZW3NO.js.map +1 -0
  261. package/dist/WalletGenerateConfig-YYLCS65G.js +10 -0
  262. package/dist/WalletGenerateConfig-YYLCS65G.js.map +1 -0
  263. package/dist/WalletGenerateFlowDetail-CQCNDGJA.js +53 -0
  264. package/dist/WalletGenerateFlowDetail-CQCNDGJA.js.map +1 -0
  265. package/dist/XeroContactCreateConfig-OWG5PA3B.js +102 -0
  266. package/dist/XeroContactCreateConfig-OWG5PA3B.js.map +1 -0
  267. package/dist/XeroContactCreateFlowDetail-6MAINCF6.js +127 -0
  268. package/dist/XeroContactCreateFlowDetail-6MAINCF6.js.map +1 -0
  269. package/dist/XeroInvoiceCreateConfig-O74RUSZM.js +403 -0
  270. package/dist/XeroInvoiceCreateConfig-O74RUSZM.js.map +1 -0
  271. package/dist/XeroInvoiceCreateFlowDetail-UL7KS6CZ.js +631 -0
  272. package/dist/XeroInvoiceCreateFlowDetail-UL7KS6CZ.js.map +1 -0
  273. package/dist/XeroInvoiceListConfig-UR3GONBJ.js +113 -0
  274. package/dist/XeroInvoiceListConfig-UR3GONBJ.js.map +1 -0
  275. package/dist/XeroInvoiceListFlowDetail-LYHODWH6.js +58 -0
  276. package/dist/XeroInvoiceListFlowDetail-LYHODWH6.js.map +1 -0
  277. package/dist/XeroPaymentCreateConfig-RPMAIK6E.js +116 -0
  278. package/dist/XeroPaymentCreateConfig-RPMAIK6E.js.map +1 -0
  279. package/dist/XeroPaymentCreateFlowDetail-CF35MVIM.js +573 -0
  280. package/dist/XeroPaymentCreateFlowDetail-CF35MVIM.js.map +1 -0
  281. package/dist/action-manifest.json +2091 -393
  282. package/dist/chunk-2GAYKKTL.js +9 -0
  283. package/dist/chunk-2GAYKKTL.js.map +1 -0
  284. package/dist/chunk-3TUYY4HK.js +20 -0
  285. package/dist/chunk-3TUYY4HK.js.map +1 -0
  286. package/dist/chunk-4DGCCXD6.js +710 -0
  287. package/dist/chunk-4DGCCXD6.js.map +1 -0
  288. package/dist/chunk-4NAFQF6V.js +11 -0
  289. package/dist/chunk-4NAFQF6V.js.map +1 -0
  290. package/dist/chunk-4PONO4US.js +799 -0
  291. package/dist/chunk-4PONO4US.js.map +1 -0
  292. package/dist/chunk-4TMOIK5M.js +21 -0
  293. package/dist/chunk-4TMOIK5M.js.map +1 -0
  294. package/dist/chunk-5E6Z6JJN.js +4456 -0
  295. package/dist/chunk-5E6Z6JJN.js.map +1 -0
  296. package/dist/chunk-5IH3VC5I.js +102 -0
  297. package/dist/chunk-5IH3VC5I.js.map +1 -0
  298. package/dist/chunk-5NTKDOP6.js +89 -0
  299. package/dist/chunk-5NTKDOP6.js.map +1 -0
  300. package/dist/chunk-5O2SFRGU.js +18 -0
  301. package/dist/chunk-5O2SFRGU.js.map +1 -0
  302. package/dist/chunk-632JLECF.js +55 -0
  303. package/dist/chunk-632JLECF.js.map +1 -0
  304. package/dist/chunk-676HDB7K.js +95 -0
  305. package/dist/chunk-676HDB7K.js.map +1 -0
  306. package/dist/chunk-6ESTNTSH.js +223 -0
  307. package/dist/chunk-6ESTNTSH.js.map +1 -0
  308. package/dist/chunk-6GKJR52N.js +15 -0
  309. package/dist/chunk-6GKJR52N.js.map +1 -0
  310. package/dist/chunk-6L4ZIKYU.js +23 -0
  311. package/dist/chunk-6L4ZIKYU.js.map +1 -0
  312. package/dist/chunk-76YX5R4L.js +11 -0
  313. package/dist/chunk-76YX5R4L.js.map +1 -0
  314. package/dist/chunk-7J3GFMN3.js +32 -0
  315. package/dist/chunk-7J3GFMN3.js.map +1 -0
  316. package/dist/chunk-7LSARC2G.js +102 -0
  317. package/dist/chunk-7LSARC2G.js.map +1 -0
  318. package/dist/chunk-7W7UUUIE.js +609 -0
  319. package/dist/chunk-7W7UUUIE.js.map +1 -0
  320. package/dist/chunk-7ZLW7H37.js +21 -0
  321. package/dist/chunk-7ZLW7H37.js.map +1 -0
  322. package/dist/chunk-AAZHI22G.js +18 -0
  323. package/dist/chunk-AAZHI22G.js.map +1 -0
  324. package/dist/chunk-ACNE455I.js +76 -0
  325. package/dist/chunk-ACNE455I.js.map +1 -0
  326. package/dist/chunk-BKLSSLPZ.js +27 -0
  327. package/dist/chunk-BKLSSLPZ.js.map +1 -0
  328. package/dist/chunk-BZ7UPUTY.js +417 -0
  329. package/dist/chunk-BZ7UPUTY.js.map +1 -0
  330. package/dist/chunk-CGFAICUE.js +28 -0
  331. package/dist/chunk-CGFAICUE.js.map +1 -0
  332. package/dist/chunk-CMCEWQ3C.js +19 -0
  333. package/dist/chunk-CMCEWQ3C.js.map +1 -0
  334. package/dist/chunk-CP4UV436.js +41 -0
  335. package/dist/chunk-CP4UV436.js.map +1 -0
  336. package/dist/chunk-DIQRZP7Z.js +51 -0
  337. package/dist/chunk-DIQRZP7Z.js.map +1 -0
  338. package/dist/chunk-EBFFDDAS.js +13 -0
  339. package/dist/chunk-EBFFDDAS.js.map +1 -0
  340. package/dist/chunk-EGVS23DR.js +85 -0
  341. package/dist/chunk-EGVS23DR.js.map +1 -0
  342. package/dist/chunk-EKBQ7K4N.js +15 -0
  343. package/dist/chunk-EKBQ7K4N.js.map +1 -0
  344. package/dist/chunk-EKQCZRAN.js +24 -0
  345. package/dist/chunk-EKQCZRAN.js.map +1 -0
  346. package/dist/chunk-EYKZIZ5J.js +48 -0
  347. package/dist/chunk-EYKZIZ5J.js.map +1 -0
  348. package/dist/{chunk-NEOPTPDF.js → chunk-F4PTFXZH.js} +11554 -22046
  349. package/dist/chunk-F4PTFXZH.js.map +1 -0
  350. package/dist/chunk-F5GTFCYV.js +3333 -0
  351. package/dist/chunk-F5GTFCYV.js.map +1 -0
  352. package/dist/chunk-FFYZXA75.js +58 -0
  353. package/dist/chunk-FFYZXA75.js.map +1 -0
  354. package/dist/chunk-GFGDHPZ2.js +22 -0
  355. package/dist/chunk-GFGDHPZ2.js.map +1 -0
  356. package/dist/chunk-GR3CDFID.js +18 -0
  357. package/dist/chunk-GR3CDFID.js.map +1 -0
  358. package/dist/chunk-GR4SIU32.js +104 -0
  359. package/dist/chunk-GR4SIU32.js.map +1 -0
  360. package/dist/chunk-H5E46IIS.js +18 -0
  361. package/dist/chunk-H5E46IIS.js.map +1 -0
  362. package/dist/chunk-HFHVAMZL.js +22 -0
  363. package/dist/chunk-HFHVAMZL.js.map +1 -0
  364. package/dist/chunk-HT6L7A5M.js +12 -0
  365. package/dist/chunk-HT6L7A5M.js.map +1 -0
  366. package/dist/chunk-I2FPFISM.js +301 -0
  367. package/dist/chunk-I2FPFISM.js.map +1 -0
  368. package/dist/chunk-IADAQJDH.js +28 -0
  369. package/dist/chunk-IADAQJDH.js.map +1 -0
  370. package/dist/chunk-IBOBCMQQ.js +99 -0
  371. package/dist/chunk-IBOBCMQQ.js.map +1 -0
  372. package/dist/chunk-IFWKRCFF.js +56 -0
  373. package/dist/chunk-IFWKRCFF.js.map +1 -0
  374. package/dist/chunk-IH4T7V4C.js +40 -0
  375. package/dist/chunk-IH4T7V4C.js.map +1 -0
  376. package/dist/chunk-IIIZZ4E4.js +1679 -0
  377. package/dist/chunk-IIIZZ4E4.js.map +1 -0
  378. package/dist/chunk-ILSFU3WD.js +83 -0
  379. package/dist/chunk-ILSFU3WD.js.map +1 -0
  380. package/dist/chunk-IX3VBV3L.js +43 -0
  381. package/dist/chunk-IX3VBV3L.js.map +1 -0
  382. package/dist/chunk-JB6ASLUJ.js +315 -0
  383. package/dist/chunk-JB6ASLUJ.js.map +1 -0
  384. package/dist/chunk-JBBFSORW.js +846 -0
  385. package/dist/chunk-JBBFSORW.js.map +1 -0
  386. package/dist/chunk-JIDTNKKL.js +1183 -0
  387. package/dist/chunk-JIDTNKKL.js.map +1 -0
  388. package/dist/chunk-JSPE6NGZ.js +22 -0
  389. package/dist/chunk-JSPE6NGZ.js.map +1 -0
  390. package/dist/chunk-JVROGQ7Q.js +150 -0
  391. package/dist/chunk-JVROGQ7Q.js.map +1 -0
  392. package/dist/chunk-K4WUMWNJ.js +32 -0
  393. package/dist/chunk-K4WUMWNJ.js.map +1 -0
  394. package/dist/chunk-K74XQ4Q5.js +11 -0
  395. package/dist/chunk-K74XQ4Q5.js.map +1 -0
  396. package/dist/chunk-KLLMJ4U3.js +22 -0
  397. package/dist/chunk-KLLMJ4U3.js.map +1 -0
  398. package/dist/chunk-LTKVCJ2E.js +27 -0
  399. package/dist/chunk-LTKVCJ2E.js.map +1 -0
  400. package/dist/chunk-M36DJTFZ.js +34 -0
  401. package/dist/chunk-M36DJTFZ.js.map +1 -0
  402. package/dist/chunk-MHM52LCJ.js +154 -0
  403. package/dist/chunk-MHM52LCJ.js.map +1 -0
  404. package/dist/chunk-MQCDMHRZ.js +59 -0
  405. package/dist/chunk-MQCDMHRZ.js.map +1 -0
  406. package/dist/chunk-MZIBZ5FY.js +554 -0
  407. package/dist/chunk-MZIBZ5FY.js.map +1 -0
  408. package/dist/chunk-N3ORMGAI.js +348 -0
  409. package/dist/chunk-N3ORMGAI.js.map +1 -0
  410. package/dist/chunk-NCSGIRRQ.js +28 -0
  411. package/dist/chunk-NCSGIRRQ.js.map +1 -0
  412. package/dist/chunk-NIXT2SBH.js +1423 -0
  413. package/dist/chunk-NIXT2SBH.js.map +1 -0
  414. package/dist/chunk-NJAII6CO.js +148 -0
  415. package/dist/chunk-NJAII6CO.js.map +1 -0
  416. package/dist/chunk-NKE4TL43.js +92 -0
  417. package/dist/chunk-NKE4TL43.js.map +1 -0
  418. package/dist/chunk-NZ7AXA7B.js +1 -0
  419. package/dist/chunk-NZ7AXA7B.js.map +1 -0
  420. package/dist/chunk-OCAYEGI2.js +26 -0
  421. package/dist/chunk-OCAYEGI2.js.map +1 -0
  422. package/dist/chunk-OMLI45ER.js +90 -0
  423. package/dist/chunk-OMLI45ER.js.map +1 -0
  424. package/dist/chunk-P7OBLJAG.js +88 -0
  425. package/dist/chunk-P7OBLJAG.js.map +1 -0
  426. package/dist/chunk-PAY3CBWL.js +2321 -0
  427. package/dist/chunk-PAY3CBWL.js.map +1 -0
  428. package/dist/chunk-PFF6VY35.js +257 -0
  429. package/dist/chunk-PFF6VY35.js.map +1 -0
  430. package/dist/chunk-PYNDJDWZ.js +1758 -0
  431. package/dist/chunk-PYNDJDWZ.js.map +1 -0
  432. package/dist/chunk-QDQ6UMMN.js +53 -0
  433. package/dist/chunk-QDQ6UMMN.js.map +1 -0
  434. package/dist/chunk-QGT3G2XG.js +24 -0
  435. package/dist/chunk-QGT3G2XG.js.map +1 -0
  436. package/dist/chunk-QZYCJ2GZ.js +55 -0
  437. package/dist/chunk-QZYCJ2GZ.js.map +1 -0
  438. package/dist/chunk-REZ7RFSA.js +124 -0
  439. package/dist/chunk-REZ7RFSA.js.map +1 -0
  440. package/dist/chunk-RRYBAE6E.js +2449 -0
  441. package/dist/chunk-RRYBAE6E.js.map +1 -0
  442. package/dist/chunk-RWUZOB62.js +34 -0
  443. package/dist/chunk-RWUZOB62.js.map +1 -0
  444. package/dist/chunk-SB5UCPZH.js +116 -0
  445. package/dist/chunk-SB5UCPZH.js.map +1 -0
  446. package/dist/chunk-SEJJ7CRI.js +99 -0
  447. package/dist/chunk-SEJJ7CRI.js.map +1 -0
  448. package/dist/chunk-SHBFGRPV.js +45 -0
  449. package/dist/chunk-SHBFGRPV.js.map +1 -0
  450. package/dist/chunk-SOFJ4GC5.js +45 -0
  451. package/dist/chunk-SOFJ4GC5.js.map +1 -0
  452. package/dist/chunk-STH2HPZK.js +44 -0
  453. package/dist/chunk-STH2HPZK.js.map +1 -0
  454. package/dist/chunk-TK3JNKME.js +28 -0
  455. package/dist/chunk-TK3JNKME.js.map +1 -0
  456. package/dist/chunk-TMONHFE3.js +46 -0
  457. package/dist/chunk-TMONHFE3.js.map +1 -0
  458. package/dist/chunk-TR4KO3AG.js +44 -0
  459. package/dist/chunk-TR4KO3AG.js.map +1 -0
  460. package/dist/chunk-TS2LNBF2.js +68 -0
  461. package/dist/chunk-TS2LNBF2.js.map +1 -0
  462. package/dist/chunk-UZUMBFPP.js +26 -0
  463. package/dist/chunk-UZUMBFPP.js.map +1 -0
  464. package/dist/chunk-VRZ5LMOW.js +176 -0
  465. package/dist/chunk-VRZ5LMOW.js.map +1 -0
  466. package/dist/chunk-WLGGY6Z6.js +75 -0
  467. package/dist/chunk-WLGGY6Z6.js.map +1 -0
  468. package/dist/chunk-WO7V6ZNC.js +11 -0
  469. package/dist/chunk-WO7V6ZNC.js.map +1 -0
  470. package/dist/chunk-WXSENSRP.js +64 -0
  471. package/dist/chunk-WXSENSRP.js.map +1 -0
  472. package/dist/chunk-XEKBZ2SA.js +19 -0
  473. package/dist/chunk-XEKBZ2SA.js.map +1 -0
  474. package/dist/chunk-XPBKU3JX.js +61 -0
  475. package/dist/chunk-XPBKU3JX.js.map +1 -0
  476. package/dist/chunk-XRYXBXWH.js +24 -0
  477. package/dist/chunk-XRYXBXWH.js.map +1 -0
  478. package/dist/chunk-XVA7QRVH.js +22 -0
  479. package/dist/chunk-XVA7QRVH.js.map +1 -0
  480. package/dist/chunk-XYXDY72K.js +27508 -0
  481. package/dist/chunk-XYXDY72K.js.map +1 -0
  482. package/dist/chunk-YCTHHBSS.js +37 -0
  483. package/dist/chunk-YCTHHBSS.js.map +1 -0
  484. package/dist/chunk-YHPWD5NE.js +70 -0
  485. package/dist/chunk-YHPWD5NE.js.map +1 -0
  486. package/dist/chunk-YLNEKJQ5.js +126 -0
  487. package/dist/chunk-YLNEKJQ5.js.map +1 -0
  488. package/dist/chunk-YN4CEKCF.js +73 -0
  489. package/dist/chunk-YN4CEKCF.js.map +1 -0
  490. package/dist/chunk-YYNMESIF.js +17 -0
  491. package/dist/chunk-YYNMESIF.js.map +1 -0
  492. package/dist/chunk-Z6PRMCV6.js +1 -0
  493. package/dist/chunk-Z6PRMCV6.js.map +1 -0
  494. package/dist/chunk-ZDNW6VQG.js +11 -0
  495. package/dist/chunk-ZDNW6VQG.js.map +1 -0
  496. package/dist/chunk-ZP4D73DO.js +36 -0
  497. package/dist/chunk-ZP4D73DO.js.map +1 -0
  498. package/dist/chunk-ZUATADUV.js +26 -0
  499. package/dist/chunk-ZUATADUV.js.map +1 -0
  500. package/dist/{connections-1NtNQrsY.d.ts → connections-CEcurtWI.d.ts} +74 -9
  501. package/dist/core/index.cjs +14041 -6973
  502. package/dist/core/index.cjs.map +1 -1
  503. package/dist/core/index.d.ts +422 -138
  504. package/dist/core/index.js +425 -183
  505. package/dist/core/index.js.map +1 -1
  506. package/dist/flow-vnext/index.cjs +2842 -0
  507. package/dist/flow-vnext/index.cjs.map +1 -0
  508. package/dist/flow-vnext/index.d.ts +3 -0
  509. package/dist/flow-vnext/index.js +119 -0
  510. package/dist/flow-vnext/index.js.map +1 -0
  511. package/dist/{graphql-client-Bn0tN049.d.ts → graphql-client-B2tREsx6.d.ts} +3 -1
  512. package/dist/index-b9xxXGFs.d.ts +1230 -0
  513. package/dist/index.d.ts +5 -3
  514. package/dist/index.js +202 -37
  515. package/dist/index.js.map +1 -1
  516. package/dist/legacy-BpgIqaQ5.d.ts +14 -0
  517. package/dist/mantine/index.d.ts +7 -4
  518. package/dist/mantine/index.js +84 -30
  519. package/dist/mantine/index.js.map +1 -1
  520. package/dist/{runtime-BFwvCQDF.d.ts → types-Dqk5MTfW.d.ts} +6096 -5386
  521. package/package.json +12 -2
  522. package/dist/chunk-A4CWC4AG.js +0 -374
  523. package/dist/chunk-A4CWC4AG.js.map +0 -1
  524. package/dist/chunk-NEOPTPDF.js.map +0 -1
  525. package/dist/chunk-VRCRDKN5.js +0 -59694
  526. package/dist/chunk-VRCRDKN5.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/lib/actionRegistry/manifest.ts","../src/core/lib/actionRegistry/serviceCan.ts","../src/core/lib/actionRegistry/adapters.ts","../src/core/lib/flowEngine/runTimeline.ts","../src/core/lib/flowEngine/terminalAuthorization.ts","../src/core/lib/actionRegistry/actions/claim/surveySchema.ts","../src/core/lib/xeroWorkItems.ts","../src/core/lib/actionRegistry/actions/evaluateClaim/pendingClaims.ts","../src/core/lib/actionRegistry/actions/collectionUsers/index.ts","../src/core/lib/actionRegistry/actions/calendar/eventCreate.types.ts","../src/core/lib/flowCompiler/connections.ts","../src/core/lib/actionRegistry/actions/xero/flowBinding.ts","../src/core/utils/numbers.ts","../src/core/lib/actionRegistry/diffRegistry.ts","../src/core/lib/actionRegistry/actions/pod/domainIndexerLookup.ts","../src/core/lib/actionRegistry/actions/pod/domainSingleSelection.ts","../src/core/lib/actionRegistry/actions/pod/entitySingleSelection.ts","../src/core/lib/actionRegistry/actions/pod/memberMultiSelect.ts","../src/core/lib/actionRegistry/actions/pod/governanceConfig.ts","../src/core/lib/actionRegistry/actions/pod/listDomainFlows.ts","../src/core/lib/actionRegistry/actions/blueprint.ts","../src/core/lib/actionRegistry/actions/governance/_shared.ts","../src/core/lib/actionRegistry/actions/governance/memberProposal.ts","../src/core/lib/actionRegistry/actions/governance/settingsProposal.ts","../src/core/lib/actionRegistry/actions/governance/submissionConfigProposal.ts","../src/core/lib/actionRegistry/actions/governance/transactionSendFunds.ts","../src/core/lib/actionRegistry/actions/governance/transactionSendGroupToken.ts","../src/core/lib/actionRegistry/actions/governance/transactionMint.ts","../src/core/lib/actionRegistry/actions/governance/transactionPerformTokenSwap.ts","../src/core/lib/actionRegistry/actions/governance/transactionWithdrawTokenSwap.ts","../src/core/lib/actionRegistry/actions/governance/stakingStake.ts","../src/core/lib/actionRegistry/actions/governance/stakingStakeToGroup.ts","../src/core/lib/actionRegistry/actions/governance/authzGrant.ts","../src/core/lib/actionRegistry/actions/governance/authzRevoke.ts","../src/core/lib/actionRegistry/actions/governance/authzExec.ts","../src/core/lib/actionRegistry/actions/governance/chainGovernanceVote.ts","../src/core/lib/actionRegistry/actions/governance/daoJoin.ts","../src/core/lib/actionRegistry/actions/governance/daoUpdateInfo.ts","../src/core/lib/actionRegistry/actions/governance/daoManageSubDaos.ts","../src/core/lib/actionRegistry/actions/governance/daoManageStorage.ts","../src/core/lib/actionRegistry/actions/governance/daoAdminExec.ts","../src/core/lib/actionRegistry/actions/governance/daoAcceptToMarketplace.ts","../src/core/lib/actionRegistry/actions/governance/daoCreateEntity.ts","../src/core/lib/actionRegistry/actions/governance/nftBurn.ts","../src/core/lib/actionRegistry/actions/governance/nftTransfer.ts","../src/core/lib/actionRegistry/actions/governance/nftManageCollections.ts","../src/core/lib/actionRegistry/actions/governance/contractExecute.ts","../src/core/lib/actionRegistry/actions/governance/contractInstantiate.ts","../src/core/lib/actionRegistry/actions/governance/contractMigrate.ts","../src/core/lib/actionRegistry/actions/governance/contractUpdateAdmin.ts","../src/core/lib/actionRegistry/actions/governance/contractManageCw20.ts","../src/core/lib/actionRegistry/actions/governance/validatorActions.ts","../src/core/lib/actionRegistry/actions/governance/customMessage.ts","../src/core/lib/actionRegistry/actions/httpRequest.ts","../src/core/lib/actionRegistry/actions/emailSend.ts","../src/core/lib/actionRegistry/actions/humanCheckbox.ts","../src/core/lib/actionRegistry/actions/humanForm.ts","../src/core/lib/actionRegistry/actions/flowRunLifecycle.ts","../src/core/lib/actionRegistry/actions/notificationPush.ts","../src/core/lib/actionRegistry/actions/_shared/groupExecution.ts","../src/core/lib/actionRegistry/actions/bid/bid.ts","../src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.ts","../src/core/lib/actionRegistry/actions/claim/claim.ts","../src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.ts","../src/core/lib/actionRegistry/actions/proposalCreate.ts","../src/core/lib/actionRegistry/actions/proposalVote.ts","../src/core/lib/actionRegistry/actions/protocolSelect.ts","../src/core/lib/actionRegistry/actions/domainCardPreview.ts","../src/core/lib/actionRegistry/actions/oracle.ts","../src/core/lib/actionRegistry/actions/credentialStore.ts","../src/core/lib/actionRegistry/actions/yomaOperations.ts","../src/core/lib/actionRegistry/actions/matrixDm.ts","../src/core/lib/actionRegistry/actions/walletGenerate.ts","../src/core/lib/actionRegistry/actions/walletFund.ts","../src/core/lib/actionRegistry/actions/walletGenerateAndFund.ts","../src/core/lib/actionRegistry/actions/iidCreate.ts","../src/core/lib/actionRegistry/actions/matrixRegister.ts","../src/core/lib/actionRegistry/actions/identityCreate.ts","../src/core/lib/actionRegistry/actions/entityCreateOracle.ts","../src/core/lib/actionRegistry/actions/sandboxProvision.ts","../src/core/lib/actionRegistry/actions/oracleContract.ts","../src/core/lib/actionRegistry/actions/oracleStoreSecrets.ts","../src/core/lib/actionRegistry/actions/oracleStoreConfig.ts","../src/core/lib/actionRegistry/actions/oracleStoreSecretsAndConfig.ts","../src/core/lib/actionRegistry/actions/oracleConfigureOracle.ts","../src/core/lib/actionRegistry/actions/oracleDeploySetup.ts","../src/core/lib/actionRegistry/actions/oracleDeployStart.ts","../src/core/lib/actionRegistry/actions/oracleDeploy.ts","../src/core/lib/actionRegistry/actions/collection/index.ts","../src/core/lib/actionRegistry/actions/collection/collection.ts","../src/core/lib/actionRegistry/actions/collectionUsers/collectionUsers.ts","../src/core/lib/actionRegistry/actions/carbon/schemas.ts","../src/core/lib/actionRegistry/actions/carbon/loadBatches.ts","../src/core/lib/actionRegistry/actions/carbon/harvest.ts","../src/core/lib/actionRegistry/actions/carbon/retire.ts","../src/core/lib/actionRegistry/actions/entityTransfer/schemas.ts","../src/core/lib/actionRegistry/actions/entityTransfer/entityTransfer.ts","../src/core/lib/actionRegistry/actions/evalRegister/evalRegister.ts","../src/core/lib/actionRegistry/actions/evalRubric/canonical.ts","../src/core/lib/actionRegistry/actions/evalRubric/evalRubric.ts","../src/core/lib/actionRegistry/actions/evalRegister/index.ts","../src/core/lib/actionRegistry/actions/evalRubric/index.ts","../src/core/lib/actionRegistry/actions/evalEngine/index.ts","../src/core/lib/actionRegistry/actions/evalEngine/evalEngine.ts","../src/core/lib/actionRegistry/actions/kycVerify.ts","../src/core/lib/actionRegistry/actions/_shared/delegatedTool.ts","../src/core/lib/actionRegistry/actions/gmail/emailSend.types.ts","../src/core/lib/actionRegistry/actions/gmail/emailSend.ts","../src/core/lib/actionRegistry/actions/outlook/emailSend.types.ts","../src/core/lib/actionRegistry/actions/outlook/emailSend.ts","../src/core/lib/actionRegistry/actions/slack/messageSend.types.ts","../src/core/lib/actionRegistry/actions/slack/messageSend.ts","../src/core/lib/actionRegistry/actions/googlecalendar/eventCreate.types.ts","../src/core/lib/actionRegistry/actions/googlecalendar/eventCreate.ts","../src/core/lib/actionRegistry/actions/topicActions.ts","../src/core/lib/actionRegistry/actions/calendar/eventCreate.ts","../src/core/lib/actionRegistry/actions/calendar/eventUpdate.ts","../src/core/lib/actionRegistry/actions/calendar/eventList.ts","../src/core/lib/actionRegistry/actions/xero/contactCreate.ts","../src/core/lib/actionRegistry/actions/xero/invoiceCreate.ts","../src/core/lib/actionRegistry/actions/xero/invoiceList.ts","../src/core/lib/actionRegistry/actions/xero/paymentCreate.ts","../src/core/lib/actionRegistry/actions/bid/bid.diff.ts","../src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.diff.ts","../src/core/lib/actionRegistry/actions/claim/claim.diff.ts","../src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.diff.ts","../src/core/lib/actionRegistry/actions/calendar/eventCreate.diff.ts","../src/core/lib/actionRegistry/actions/calendar/eventUpdate.diff.ts","../src/core/lib/actionRegistry/actions/xero/contactCreate.diff.ts","../src/core/lib/actionRegistry/actions/xero/invoiceCreate.diff.ts","../src/core/lib/actionRegistry/actions/xero/paymentCreate.diff.ts","../src/core/lib/actionRegistry/actions/walletFund.diff.ts","../src/core/lib/actionRegistry/actions/collection/collection.diff.ts","../src/core/lib/actionRegistry/actions/collectionUsers/collectionUsers.diff.ts","../src/core/lib/actionRegistry/actions/carbon/harvest.diff.ts","../src/core/lib/actionRegistry/actions/carbon/retire.diff.ts","../src/core/lib/actionRegistry/actions/entityTransfer/entityTransfer.diff.ts","../src/core/lib/actionRegistry/actions/evalEngine/evalEngine.diff.ts"],"sourcesContent":["import { compareCodeUnits, sha256Digest } from './digest';\nimport type { ActionDefinition, ActionEventDefinition, ActionRiskTier, ActionSchedulingContract, OutputSchemaField, TopicActionMetadata } from './types';\nimport { actionTypeToCan, doneWhenCompleted, getAliasEntries, getAllActions, getRegistryRevision, neverDone } from './registry';\n\nexport const ACTION_MANIFEST_VERSION = '4' as const;\nexport const ACTION_REGISTRY_VERSION = '6.32.0-topic-actions.3' as const;\n\n/** Serializable declaration; custom functions remain kernel-enforced. */\nexport type ManifestProofDeclaration = { kind: 'none' } | { kind: 'fields'; fields: string[] } | { kind: 'custom' };\nexport interface ManifestDoneDeclaration {\n kind: 'default' | 'custom';\n hasExternalCheck: boolean;\n cardinality: 'once' | 'many';\n}\n\nexport interface ActionManifestEntry {\n type: string;\n contractVersion: string;\n displayName: string;\n description: string;\n aliases: string[];\n contractDigest: `sha256:${string}`;\n can: string;\n effectiveCapability: {\n action: string;\n flowExecution?: string;\n topicWriteBack: string[];\n };\n sideEffect: boolean;\n defaultRequiresConfirmation: boolean;\n executionOwner: 'agent' | 'human';\n riskTier: ActionRiskTier;\n requiredServices: string[];\n sensitiveInputPaths: string[];\n sensitiveOutputPaths: string[];\n hidden: boolean;\n deprecated: boolean;\n supersededBy?: string;\n requiredCapability?: string;\n requiresSignedInvocation: boolean;\n proof: ManifestProofDeclaration;\n done: ManifestDoneDeclaration;\n inputSchema: object;\n outputSchema: OutputSchemaField[];\n events: Array<Pick<ActionEventDefinition, 'name' | 'displayName' | 'description' | 'payloadSchema'>>;\n hasDynamicEvents: boolean;\n hasDynamicOutputSchema: boolean;\n eligibleForEventTrigger: boolean;\n /** Whether a time trigger may target this action (Sovereign Scheduling, IXO-4433). */\n eligibleForTimeTrigger: boolean;\n /** Present exactly when eligibleForTimeTrigger is true: the Timed Action contract. */\n scheduling?: ActionSchedulingContract;\n hasCustomInputValidation: boolean;\n topic: TopicActionMetadata;\n}\n\nexport interface ActionManifest {\n manifestVersion: typeof ACTION_MANIFEST_VERSION;\n registryVersion: string;\n manifestDigest: `sha256:${string}`;\n actions: ActionManifestEntry[];\n}\n\ntype UndigestedEntry = Omit<ActionManifestEntry, 'contractDigest'>;\n\nfunction serializeProof(action: ActionDefinition): ManifestProofDeclaration {\n const proof = action.proof;\n if (proof === 'none' || proof === undefined) return { kind: 'none' };\n if ('validate' in proof) return { kind: 'custom' };\n return { kind: 'fields', fields: [...proof.fields] };\n}\n\nfunction serializeDone(action: ActionDefinition): ManifestDoneDeclaration {\n const isStandard = action.done === doneWhenCompleted || action.done === neverDone;\n return {\n kind: isStandard ? 'default' : 'custom',\n hasExternalCheck: !!action.done.check,\n cardinality: action.cardinality || 'once',\n };\n}\n\nfunction serializeAction(action: ActionDefinition, aliases: string[]): UndigestedEntry {\n const can = action.can || actionTypeToCan(action.type) || '';\n return {\n type: action.type,\n contractVersion: action.contractVersion,\n displayName: action.displayName,\n description: action.description,\n aliases,\n can,\n effectiveCapability: {\n action: can,\n ...(action.requiredCapability ? { flowExecution: action.requiredCapability } : {}),\n topicWriteBack: [...(action.topic?.requiredTopicAbilities || [])].sort(),\n },\n sideEffect: action.sideEffect,\n defaultRequiresConfirmation: action.defaultRequiresConfirmation,\n executionOwner: action.executionOwner || 'agent',\n riskTier: action.riskTier || 'medium',\n requiredServices: [...(action.requiredServices || [])].sort(),\n sensitiveInputPaths: [...(action.sensitiveInputPaths || [])].sort(),\n sensitiveOutputPaths: [...(action.sensitiveOutputPaths || [])].sort(),\n hidden: action.hiddenFromAuthoring === true,\n deprecated: action.deprecated === true,\n ...(action.supersededBy ? { supersededBy: action.supersededBy } : {}),\n ...(action.requiredCapability ? { requiredCapability: action.requiredCapability } : {}),\n requiresSignedInvocation: action.requiresSignedInvocation === true,\n proof: serializeProof(action),\n done: serializeDone(action),\n inputSchema: action.inputSchema || {},\n outputSchema: action.outputSchema || [],\n events: (action.events || []).map((event) => ({\n name: event.name,\n displayName: event.displayName,\n description: event.description,\n payloadSchema: event.payloadSchema,\n })),\n hasDynamicEvents: !!action.getDynamicEvents,\n hasDynamicOutputSchema: !!action.getDynamicOutputSchema,\n eligibleForEventTrigger: !!action.eligibleForEventTrigger,\n eligibleForTimeTrigger: !!action.eligibleForTimeTrigger,\n ...(action.scheduling ? { scheduling: action.scheduling } : {}),\n hasCustomInputValidation: !!action.getMissingInputs,\n topic: action.topic!,\n };\n}\n\n/** Presentation copy remains portable but is not part of request compatibility. */\nfunction contractDigestPayload(entry: UndigestedEntry): object {\n const { displayName: _displayName, description: _description, topic, ...contract } = entry;\n const { semanticRecordTypes, ...legacyTopic } = topic;\n const semanticContracts = semanticRecordTypes.map(({ displayName: _recordDisplayName, description: _recordDescription, ...definition }) => definition);\n return {\n ...contract,\n topic: semanticContracts.length > 0 ? { ...legacyTopic, semanticRecordTypes: semanticContracts } : legacyTopic,\n };\n}\n\n/** Build Action Manifest v4 from the live registry, without consulting the cache. */\nexport function buildActionManifest(): ActionManifest {\n const aliasesByType = new Map<string, string[]>();\n for (const [alias, canonical] of getAliasEntries()) {\n aliasesByType.set(canonical, [...(aliasesByType.get(canonical) || []), alias]);\n }\n\n const actions = getAllActions()\n .map((action) => serializeAction(action, [...(aliasesByType.get(action.type) || [])].sort(compareCodeUnits)))\n .sort((a, b) => compareCodeUnits(a.type, b.type))\n .map((entry): ActionManifestEntry => ({ ...entry, contractDigest: sha256Digest(contractDigestPayload(entry)) }));\n const payload = { manifestVersion: ACTION_MANIFEST_VERSION, registryVersion: ACTION_REGISTRY_VERSION, actions };\n return { ...payload, manifestDigest: sha256Digest(payload) };\n}\n\nlet cached: { revision: number; manifest: ActionManifest } | undefined;\n\n/**\n * Generate deterministic Action Manifest v4 from the one live registry.\n *\n * Memoized against the registry revision: building the manifest canonicalizes and\n * SHA-256s every registered contract, and the validation paths (flow bindings,\n * Action requests, receipts, external invocations) call this on every check —\n * several of them from React render. The registry only changes when an Action\n * registers, which bumps the revision and invalidates this.\n *\n * The returned manifest is shared, so callers must treat it as read-only.\n */\nexport function generateActionManifest(): ActionManifest {\n const revision = getRegistryRevision();\n if (cached && cached.revision === revision) return cached.manifest;\n const manifest = buildActionManifest();\n cached = { revision, manifest };\n return manifest;\n}\n\nexport interface ActionManifestIssue {\n actionType: string;\n code:\n | 'MISSING_CAN'\n | 'MISSING_CONTRACT_VERSION'\n | 'MISSING_PRESENTATION'\n | 'MISSING_INPUT_SCHEMA'\n | 'MISSING_OUTPUT_SCHEMA'\n | 'SIDE_EFFECT_WITHOUT_PROOF'\n | 'MISSING_TOPIC_POLICY'\n | 'INVALID_TOPIC_POLICY'\n | 'INVALID_SEMANTIC_RECORD_DEFINITION';\n message: string;\n}\n\n/** CI/build gate for the public portable registry contract. */\nexport function actionManifestIssues(manifest: ActionManifest = generateActionManifest()): ActionManifestIssue[] {\n const issues: ActionManifestIssue[] = [];\n for (const action of manifest.actions) {\n const publicAction = !action.hidden;\n if (!action.contractVersion.trim()) issues.push({ actionType: action.type, code: 'MISSING_CONTRACT_VERSION', message: 'Action has no portable contract version.' });\n if (!action.can) issues.push({ actionType: action.type, code: 'MISSING_CAN', message: 'Action has no canonical can ability.' });\n if (\n !action.displayName.trim() ||\n !action.description.trim() ||\n action.displayName === action.type ||\n action.description.includes(action.type) ||\n /^Perform .* as part of this flow\\.$/.test(action.description)\n ) {\n issues.push({ actionType: action.type, code: 'MISSING_PRESENTATION', message: 'Action needs a non-technical display name and description.' });\n }\n if (publicAction && Object.keys(action.inputSchema).length === 0) {\n issues.push({ actionType: action.type, code: 'MISSING_INPUT_SCHEMA', message: 'Public Action has no input schema.' });\n }\n if (publicAction && action.outputSchema.length === 0 && !action.hasDynamicOutputSchema) {\n issues.push({ actionType: action.type, code: 'MISSING_OUTPUT_SCHEMA', message: 'Public Action has no output schema.' });\n }\n if (action.sideEffect && action.proof.kind === 'none') {\n issues.push({ actionType: action.type, code: 'SIDE_EFFECT_WITHOUT_PROOF', message: 'Side-effecting Action declares no proof.' });\n }\n if (!action.topic) issues.push({ actionType: action.type, code: 'MISSING_TOPIC_POLICY', message: 'Action has no Topic compatibility policy.' });\n else if (action.topic.lifecycleEffect !== 'none' || action.topic.supportedBaseKinds.length === 0) {\n issues.push({ actionType: action.type, code: 'INVALID_TOPIC_POLICY', message: 'Topic policy must support a base Kind and cannot imply lifecycle effects.' });\n }\n if (\n action.topic.semanticRecordTypes.some(\n (definition) =>\n !definition.type || !definition.version || !definition.displayName.trim() || !definition.description.trim() || Object.keys(definition.valueSchema).length === 0\n ) ||\n action.topic.permittedTopicRecordTypes.join('|') !== action.topic.semanticRecordTypes.map((definition) => definition.type).join('|')\n ) {\n issues.push({\n actionType: action.type,\n code: 'INVALID_SEMANTIC_RECORD_DEFINITION',\n message: 'Topic semantic record definitions must be complete and determine the compatibility type list.',\n });\n }\n }\n return issues;\n}\n","/**\n * Service-verb `can` grammar for contracted helper oracles.\n *\n * The `can` vocabulary has two tiers:\n *\n * 1. **Action cans** (`<namespace>/<verb>`, e.g. `claim/evaluate`) — the\n * identity of an execution contract. They map 1:1 to registry action types\n * (see `canMapping.ts`) and name the thing the flow engine actually runs.\n * 2. **Service cans** (`<action can>/<service verb>`, e.g.\n * `claim/evaluate/report`) — the name of a contracted helper service scoped\n * to an action. A helper oracle holding a service-can delegation does NOT\n * execute the action; it performs a service about it (produce a report,\n * format output, advise). The delegation is a **work contract** — inputs\n * passed by value, receipt returned by value — not a grant of system\n * authority over the action or its resources.\n *\n * Attenuation rule: flow-document authority covers `<can>/*` service verbs —\n * a principal authorized over the flow may contract any service verb under the\n * cans that flow uses. A narrow execution grant (e.g. `claim/evaluate` alone)\n * does not expand into service verbs, and a service-verb grant (e.g.\n * `claim/evaluate/report`) does not expand into execution.\n *\n * Generic action-agnostic services (e.g. `flow/diagnose`) are their own tier\n * with their own vocabulary and are intentionally NOT expressible through this\n * helper — `diagnose` is not a `ServiceVerb`.\n */\n\n/** The closed set of service verbs a helper oracle can be contracted for. */\nexport const SERVICE_VERBS = ['report', 'format', 'advise'] as const;\n\nexport type ServiceVerb = (typeof SERVICE_VERBS)[number];\n\n/**\n * True when `can` is namespace/verb shaped (non-empty segments around at least\n * one '/') and is not itself a service can. Service verbs are reserved words:\n * an action can may never end in one, which is what makes the grammar\n * unambiguous and rules out service-of-service composition.\n */\nfunction isActionCanShape(can: string): boolean {\n if (typeof can !== 'string' || can.length === 0) return false;\n const segments = can.split('/');\n return segments.length >= 2 && segments.every((segment) => segment.length > 0) && !(SERVICE_VERBS as readonly string[]).includes(segments[segments.length - 1]);\n}\n\n/**\n * Compose a service can from an action can and a service verb.\n *\n * `serviceCan('claim/evaluate', 'report')` → `'claim/evaluate/report'`.\n *\n * @throws when `can` is not a valid action-can shape (`<namespace>/<verb>`),\n * when `can` is already a service can (no service-of-service composition), or\n * when `verb` is not in {@link SERVICE_VERBS} — the vocabulary is closed at\n * runtime too, not only at the type level, so untyped callers (JS, decoded\n * config) cannot mint capabilities outside it.\n */\nexport function serviceCan(can: string, verb: ServiceVerb): string {\n if (!(SERVICE_VERBS as readonly string[]).includes(verb)) {\n throw new Error(`serviceCan: unknown service verb '${String(verb)}' — expected one of: ${SERVICE_VERBS.join(', ')}`);\n }\n if (!isActionCanShape(can)) {\n throw new Error(`serviceCan: invalid action can '${can}' — expected a non-empty '<namespace>/<verb>' shaped string that is not itself a service can, e.g. 'claim/evaluate'`);\n }\n return `${can}/${verb}`;\n}\n\n/**\n * Parse a service can back into its action can and service verb.\n *\n * `parseServiceCan('claim/evaluate/report')` →\n * `{ actionCan: 'claim/evaluate', verb: 'report' }`.\n *\n * Returns `null` when the last segment is not a known {@link ServiceVerb} or\n * the prefix is not a valid action-can shape. Plain action cans\n * (`claim/evaluate`) and generic-tier cans (`flow/diagnose`) both return\n * `null` — they are not service cans.\n */\nexport function parseServiceCan(value: string): { actionCan: string; verb: ServiceVerb } | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const lastSlash = value.lastIndexOf('/');\n if (lastSlash <= 0) return null;\n const verb = value.slice(lastSlash + 1);\n if (!(SERVICE_VERBS as readonly string[]).includes(verb)) return null;\n const actionCan = value.slice(0, lastSlash);\n if (!isActionCanShape(actionCan)) return null;\n return { actionCan, verb: verb as ServiceVerb };\n}\n","import type { ActionServices } from './types';\nimport { sha256Digest } from './digest';\n\n/**\n * Builds an ActionServices map from BlocknoteHandlers.\n * Used by block components to bridge existing DI into registry calls.\n *\n * The handlers parameter is typed as `any` to avoid a circular dependency\n * between core and mantine layers — BlocknoteHandlers is defined in mantine/context.\n */\n/**\n * Required handler keys per all-or-nothing service group, mirroring the\n * guards below. When a consumer provides SOME of a group's methods, the\n * whole group silently resolves to `undefined` and actions later throw\n * \"handler not available\" with no hint of what was missing — this table\n * lets us name the missing methods at wiring time instead.\n */\nconst SERVICE_GROUP_REQUIRED_HANDLERS: Record<string, string[]> = {\n bid: ['submitBid', 'approveBid', 'rejectBid', 'approveServiceAgentApplication', 'approveEvaluatorApplication'],\n claim: ['requestPin', 'submitClaim', 'evaluateClaim', 'getCurrentUser'],\n collection: [\n 'collection.get',\n 'collection.create',\n 'collection.updateState',\n 'collection.updateDates',\n 'collection.updateQuota',\n 'collection.updatePayments',\n 'collection.updateIntents',\n ],\n collectionUsers: ['collectionUsers.grant', 'collectionUsers.revoke', 'collectionUsers.list', 'collectionUsers.classifyAddress', 'collectionUsers.enumerateMembers'],\n carbon: ['carbon.loadBatches', 'carbon.harvest', 'carbon.retire'],\n kyc: ['kycLoadForm', 'kycInitiate', 'kycGetVerificationUrl', 'kycGetStatus', 'kycSaveCredential'],\n evalRegister: ['requestPin', 'mintBotDelegation', 'depositDelegation', 'registerEvalCollection'],\n // Rubric publishing (qi/eval.rubric). `pinRubric` is best-effort (run() guards it), so it is not\n // required for the group to be usable — `uploadRubric` (store the bytes) and `getRubricSchema`\n // (the pre-publish shape check) are.\n rubric: ['uploadRubric', 'getRubricSchema'],\n};\n\nfunction getHandlerAtPath(handlers: any, path: string): unknown {\n return path.split('.').reduce<any>((acc, key) => (acc == null ? undefined : acc[key]), handlers);\n}\n\nfunction warnPartialServiceGroups(handlers: any): void {\n if (!handlers) return;\n for (const [group, keys] of Object.entries(SERVICE_GROUP_REQUIRED_HANDLERS)) {\n const missing = keys.filter((key) => !getHandlerAtPath(handlers, key));\n if (missing.length > 0 && missing.length < keys.length) {\n console.warn(\n `[buildServicesFromHandlers] services.${group} is DISABLED: handlers provide ${keys.length - missing.length}/${keys.length} required methods; missing: ${missing.join(', ')}`\n );\n }\n }\n}\n\nexport function buildServicesFromHandlers(handlers: any): ActionServices {\n warnPartialServiceGroups(handlers);\n return {\n flowInvocation: handlers?.flowInvocation?.verifyInvocation\n ? {\n verifyInvocation: async (params) => handlers.flowInvocation.verifyInvocation(params),\n }\n : undefined,\n designPod:\n handlers?.designPod?.persistArtifact &&\n handlers?.designPod?.verifyArtifactReceipt &&\n handlers?.designPod?.verifyInvocation &&\n handlers?.designPod?.persistRelease &&\n handlers?.designPod?.verifyPublicationReceipt &&\n handlers?.designPod?.broadcastPublication &&\n handlers?.designPod?.getTransactionStatus &&\n handlers?.designPod?.mintProtocol\n ? {\n persistArtifact: async (params) => handlers.designPod.persistArtifact(params),\n verifyArtifactReceipt: async (params) => handlers.designPod.verifyArtifactReceipt(params),\n verifyInvocation: async (params) => handlers.designPod.verifyInvocation(params),\n persistRelease: async (params) => handlers.designPod.persistRelease(params),\n verifyPublicationReceipt: async (params) => handlers.designPod.verifyPublicationReceipt(params),\n broadcastPublication: async (params) => handlers.designPod.broadcastPublication(params),\n getTransactionStatus: async (transactionHash) => handlers.designPod.getTransactionStatus(transactionHash),\n mintProtocol: async (params) => handlers.designPod.mintProtocol(params),\n }\n : undefined,\n domainVfs: handlers?.domainVfs?.persistDomainPackage\n ? {\n persistDomainPackage: async (params) => handlers.domainVfs.persistDomainPackage(params),\n }\n : undefined,\n fundingVerification: handlers?.yomaOperations?.verifyFunding\n ? {\n verify: async (params) => handlers.yomaOperations.verifyFunding(params),\n }\n : undefined,\n credentialIssuance: handlers?.yomaOperations?.issueCredential\n ? {\n issueAndDeliver: async (params) => handlers.yomaOperations.issueCredential(params),\n }\n : undefined,\n yomaOpportunity: handlers?.yomaOperations?.executeOpportunity\n ? {\n execute: async (params) => handlers.yomaOperations.executeOpportunity(params),\n }\n : undefined,\n yoId: handlers?.yomaOperations?.executeYoIdLink\n ? {\n execute: async (params) => handlers.yomaOperations.executeYoIdLink(params),\n }\n : undefined,\n outcomeCertificate: handlers?.yomaOperations?.issueOutcomeCertificate\n ? {\n issueAndVerify: async (params) => handlers.yomaOperations.issueOutcomeCertificate(params),\n }\n : undefined,\n http: {\n request: async (params) => {\n const fetchOptions: RequestInit = {\n method: params.method,\n headers: { 'Content-Type': 'application/json', ...params.headers },\n redirect: 'error',\n };\n if (params.method !== 'GET' && params.body) {\n fetchOptions.body = typeof params.body === 'string' ? params.body : JSON.stringify(params.body);\n }\n const res = await fetch(params.url, fetchOptions);\n const data = await res.json().catch(() => ({}));\n const responseHeaders: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n return {\n status: res.status,\n headers: responseHeaders,\n data,\n responseDigest: sha256Digest(data),\n requestId: sha256Digest({ url: params.url, method: params.method, status: res.status, data }),\n };\n },\n },\n email: handlers?.sendEmail\n ? {\n send: async (params) => {\n const result = await handlers.sendEmail(params);\n return {\n messageId: result.id || '',\n sentAt: new Date().toISOString(),\n };\n },\n }\n : undefined,\n notify: handlers?.sendNotification\n ? {\n send: async (params) => {\n const result = await handlers.sendNotification(params);\n return {\n messageId: result.messageId,\n sentAt: result.timestamp || new Date().toISOString(),\n };\n },\n }\n : undefined,\n bid:\n handlers?.submitBid && handlers?.approveBid && handlers?.rejectBid && handlers?.approveServiceAgentApplication && handlers?.approveEvaluatorApplication\n ? {\n submitBid: async (params) => handlers.submitBid(params),\n approveBid: async (params) => handlers.approveBid(params),\n rejectBid: async (params) => handlers.rejectBid(params),\n approveServiceAgentApplication: async (params) => handlers.approveServiceAgentApplication(params),\n approveEvaluatorApplication: async (params) => handlers.approveEvaluatorApplication(params),\n }\n : undefined,\n claim:\n handlers?.requestPin && handlers?.submitClaim && handlers?.evaluateClaim && handlers?.getCurrentUser\n ? {\n requestPin: async (config) => handlers.requestPin(config),\n submitClaim: async (params) => handlers.submitClaim(params),\n evaluateClaim: async (granteeAddress, did, payload) => handlers.evaluateClaim(granteeAddress, did, payload),\n disputeClaim: handlers?.disputeClaim ? async (granteeAddress, did, payload) => handlers.disputeClaim(granteeAddress, did, payload) : undefined,\n getCurrentUser: () => handlers.getCurrentUser(),\n createUdid: handlers?.createUdid ? async (params) => handlers.createUdid(params) : undefined,\n }\n : undefined,\n matrix: handlers?.storeMatrixCredential\n ? {\n storeCredential: async (params) => handlers.storeMatrixCredential(params),\n }\n : undefined,\n // Claim-collection lifecycle service (IXO-2573/2579). The consumer exposes\n // a fully-formed `handlers.collection` service group (get + create + the\n // five updates); wire each method straight through. The core run()\n // dispatcher resolves admin from the on-chain collection.admin and\n // re-fetches via `get` after every write, so we only forward calls here.\n collection:\n handlers?.collection?.get &&\n handlers?.collection?.create &&\n handlers?.collection?.updateState &&\n handlers?.collection?.updateDates &&\n handlers?.collection?.updateQuota &&\n handlers?.collection?.updatePayments &&\n handlers?.collection?.updateIntents\n ? {\n get: async (params) => handlers.collection.get(params),\n create: async (params) => handlers.collection.create(params),\n updateState: async (params) => handlers.collection.updateState(params),\n updateDates: async (params) => handlers.collection.updateDates(params),\n updateQuota: async (params) => handlers.collection.updateQuota(params),\n updatePayments: async (params) => handlers.collection.updatePayments(params),\n updateIntents: async (params) => handlers.collection.updateIntents(params),\n }\n : undefined,\n // Claim-collection user-management service (IXO-2586). The consumer exposes a\n // fully-formed `handlers.collectionUsers` service group (grant + revoke +\n // list + classifyAddress + enumerateMembers); wire each method straight\n // through. The core run() dispatcher validates inputs and proof-guards the\n // results, so we only forward calls here.\n collectionUsers:\n handlers?.collectionUsers?.grant &&\n handlers?.collectionUsers?.revoke &&\n handlers?.collectionUsers?.list &&\n handlers?.collectionUsers?.classifyAddress &&\n handlers?.collectionUsers?.enumerateMembers\n ? {\n grant: async (params) => handlers.collectionUsers.grant(params),\n // Optional (IXO-4396): only hosts that can broadcast every grant in\n // one transaction expose it. Left undefined, the dispatcher falls\n // back to one `grant` per grantee.\n grantMany: handlers.collectionUsers.grantMany ? async (params: any) => handlers.collectionUsers.grantMany(params) : undefined,\n revoke: async (params) => handlers.collectionUsers.revoke(params),\n list: async (params) => handlers.collectionUsers.list(params),\n classifyAddress: async (params) => handlers.collectionUsers.classifyAddress(params),\n enumerateMembers: async (params) => handlers.collectionUsers.enumerateMembers(params),\n }\n : undefined,\n integrations: handlers?.integrations?.executeTool\n ? {\n executeTool: async (args) => handlers.integrations.executeTool(args),\n fetchCurrentState: handlers.integrations.fetchCurrentState ? async (args) => handlers.integrations.fetchCurrentState(args) : undefined,\n getEntityDid: handlers?.getEntityDid ? () => handlers.getEntityDid() : undefined,\n executeBinding: handlers.integrations.executeBinding ? async (args) => handlers.integrations.executeBinding(args) : undefined,\n }\n : undefined,\n oracle: handlers?.generateWallet\n ? {\n generateWallet: async () => handlers.generateWallet(),\n fundWallet: async (params) => handlers.fundWallet(params),\n createIidDocument: async (params) => handlers.createIidDocument(params),\n registerMatrixAccount: async (params) => handlers.registerMatrixAccount(params),\n createOracleEntity: async (params) => handlers.createOracleEntity(params),\n contract: async (params) => handlers.oracleContract(params),\n provisionSandbox: async (params) => handlers.provisionSandbox(params),\n storeSecrets: async (params) => handlers.storeSecrets(params),\n storeConfig: async (params) => handlers.storeOracleConfig(params),\n validateMcpServer: handlers.validateMcpServer || (async () => ({ success: false, error: 'Handler not configured' })),\n encryptForOracle: async (params) => handlers.encryptSecretForOracle(params),\n readStoredSecrets: async (params) => handlers.readStoredSecrets(params),\n getNetworkConstants: async (params) => handlers.getNetworkConstants(params),\n deploySetup:\n handlers.deploySetup ||\n (async () => {\n throw new Error('deploySetup handler not configured');\n }),\n deployStart:\n handlers.deployStart ||\n (async () => {\n throw new Error('deployStart handler not configured');\n }),\n updateOracleDomain:\n handlers.updateOracleDomain ||\n (async () => {\n throw new Error('updateOracleDomain handler not configured');\n }),\n }\n : undefined,\n // Carbon credit batch service (IXO-2675). The consumer exposes a\n // fully-formed `handlers.carbon` service group (loadBatches + harvest +\n // retire); wire each method straight through. The harvest/retire calls are\n // user-signed inside the consumer handler — we only forward here.\n carbon:\n handlers?.carbon?.loadBatches && handlers?.carbon?.harvest && handlers?.carbon?.retire\n ? {\n loadBatches: async (params) => handlers.carbon.loadBatches(params),\n harvest: async (params) => handlers.carbon.harvest(params),\n retire: async (params) => handlers.carbon.retire(params),\n }\n : undefined,\n // Entity (domain) ownership service (IXO-2696). The consumer exposes a\n // fully-formed `handlers.entity` service group; the transfer is user-signed\n // inside the consumer handler (resolve recipient + IID guard + broadcast) —\n // we only forward the call here.\n entity: handlers?.entity?.transfer\n ? {\n transfer: async (params) => handlers.entity.transfer(params),\n }\n : undefined,\n // KYC verification service (qi/kyc.verify). The consumer exposes the five\n // flat kyc* handlers (all-or-nothing group); wire each method straight\n // through. The consumer handler owns the KYC-server calls, PII handling,\n // and saveCredential idempotency — we only forward calls here.\n kyc:\n handlers?.kycLoadForm && handlers?.kycInitiate && handlers?.kycGetVerificationUrl && handlers?.kycGetStatus && handlers?.kycSaveCredential\n ? {\n loadForm: async (params) => handlers.kycLoadForm(params),\n initiate: async (params) => handlers.kycInitiate(params),\n getVerificationUrl: async (params) => handlers.kycGetVerificationUrl(params),\n getStatus: async (params) => handlers.kycGetStatus(params),\n saveCredential: async (params) => handlers.kycSaveCredential(params),\n }\n : undefined,\n // Evaluation-Engine enrollment service (qi/eval.register — spec §6). All\n // signing + HTTP live host-side: `mintBotDelegation` (owns the oracle-DID\n // default + the claim-bot AND subscriptions-read capabilities + signing —\n // see EvalRegisterService), `depositDelegation` (UCAN Store\n // store/add), `registerEvalCollection` (engine). The core run() proof-guards\n // every result, so we only forward calls here.\n evalRegister:\n handlers?.requestPin && handlers?.mintBotDelegation && handlers?.depositDelegation && handlers?.registerEvalCollection\n ? {\n requestPin: async (config) => handlers.requestPin(config),\n mintBotDelegation: async (params) => handlers.mintBotDelegation(params),\n depositDelegation: async (params) => handlers.depositDelegation(params),\n registerCollection: async (params) => handlers.registerEvalCollection(params),\n }\n : undefined,\n // Rubric publishing service (qi/eval.rubric — spec §B.2/§C). Host-side: `uploadRubric` (Matrix\n // media store, returns the content hash used as the id), `getRubricSchema` (fetch the engine's\n // served JSON Schema for the pre-publish shape check), `pinRubric` (best-effort engine link).\n // The core run() forwards to these and proof-guards its result. Gated on `uploadRubric` so a\n // host that hasn't wired the group yet leaves the block cleanly disabled rather than crashing.\n rubric: handlers?.uploadRubric\n ? {\n uploadRubric: async (params) => handlers.uploadRubric(params),\n ...(handlers.getRubricSchema ? { getRubricSchema: async (url?: string) => handlers.getRubricSchema(url) } : {}),\n ...(handlers.pinRubric ? { pinRubric: async (params) => handlers.pinRubric(params) } : {}),\n // §C.7 pre-publish dry run against the engine (schema + live form bind + settings); optional.\n ...(handlers.previewRubric ? { previewRubric: async (params) => handlers.previewRubric(params) } : {}),\n // Best-effort live test of a §A.14 external source (the builder's Test button); optional, like pinRubric.\n ...(handlers.testExternalSource ? { testExternalSource: async (params) => handlers.testExternalSource(params) } : {}),\n // Public did:web resolution from a source's endpoint (auto-fills its audience); optional.\n ...(handlers.resolveSourceDid ? { resolveSourceDid: async (params) => handlers.resolveSourceDid(params) } : {}),\n // The entity's existing #rub resource, so a republish can delete+add in one tx; optional.\n ...(handlers.getRubricResource ? { getRubricResource: async (params) => handlers.getRubricResource(params) } : {}),\n }\n : undefined,\n };\n}\n","import type * as Y from 'yjs';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { RunEventAppender, RunEventInput, RunJsonValue } from './runLifecycle';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport { createRunScopedRuntimeManager } from './runs';\n\n/**\n * A run head must stay small enough to replicate cheaply. Full action history\n * belongs in Matrix; the Y.Doc keeps only the latest referenceable output.\n *\n * 16 KiB leaves ample room for the run-event envelope under Matrix's 64 KiB\n * event limit and bounds ten runs independently of retry/history volume.\n */\nexport const MAX_RUN_ACTION_OUTPUT_BYTES = 16 * 1024;\nconst MAX_PENDING_TIMELINE_EVENTS = 4;\nconst TIMELINE_PENDING_CACHE_KEY = 'runTimelinePending';\nconst TIMELINE_ERROR_CACHE_KEY = 'runTimelineError';\n\nexport interface BoundedRunOutput {\n output: Record<string, unknown>;\n byteLength: number;\n exceeded: boolean;\n}\n\nexport interface PendingRunTimelineEvent {\n event: RunEventInput;\n failedAt: number;\n error: string;\n}\n\nexport interface RunTimelineAppendResult {\n ok: boolean;\n eventId?: string;\n error?: string;\n}\n\nfunction jsonByteLength(value: unknown): number {\n const encoded = JSON.stringify(value);\n if (typeof TextEncoder !== 'undefined') {\n return new TextEncoder().encode(encoded).byteLength;\n }\n return unescape(encodeURIComponent(encoded)).length;\n}\n\nfunction fnv1a32(input: string, seed: number): string {\n let hash = seed >>> 0;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Stable, bounded, Matrix-safe key. Raw block/run ids never enter the key. */\nexport function createRunEventIdempotencyKey(kind: RunEventInput['kind'], ...identity: Array<string | number>): string {\n const canonical = JSON.stringify([kind, ...identity]);\n const digest = `${fnv1a32(canonical, 0x811c9dc5)}${fnv1a32(canonical, 0x9e3779b1)}`;\n return `v1:${kind.replace(/\\./g, '_')}:${digest}`;\n}\n\n/**\n * Prepare the value allowed into the Y.Doc. Oversized output is represented by\n * a bounded marker; callers must route the action to needs-verification rather\n * than pretending downstream references still have the complete value.\n */\nexport function boundRunActionOutput(value: Record<string, unknown>): BoundedRunOutput {\n const byteLength = jsonByteLength(value);\n if (byteLength <= MAX_RUN_ACTION_OUTPUT_BYTES) {\n return {\n output: JSON.parse(JSON.stringify(value)) as Record<string, unknown>,\n byteLength,\n exceeded: false,\n };\n }\n\n return {\n output: {\n __runOutput: {\n truncated: true,\n byteLength,\n maxBytes: MAX_RUN_ACTION_OUTPUT_BYTES,\n digest: `${fnv1a32(JSON.stringify(value), 0x811c9dc5)}${fnv1a32(JSON.stringify(value), 0x9e3779b1)}`,\n keys: Object.keys(value).sort().slice(0, 32),\n },\n },\n byteLength,\n exceeded: true,\n };\n}\n\nfunction readPending(runtime: FlowRuntimeStateManager, blockId: string): PendingRunTimelineEvent[] {\n const value = runtime.get(blockId).cache?.[TIMELINE_PENDING_CACHE_KEY];\n if (!Array.isArray(value)) return [];\n return value.filter(\n (entry): entry is PendingRunTimelineEvent =>\n !!entry && typeof entry === 'object' && !!(entry as PendingRunTimelineEvent).event && typeof (entry as PendingRunTimelineEvent).failedAt === 'number'\n );\n}\n\nfunction retainPending(runtime: FlowRuntimeStateManager, blockId: string, event: RunEventInput, error: string, failedAt: number): void {\n const pending = readPending(runtime, blockId).filter((entry) => entry.event.idempotencyKey !== event.idempotencyKey);\n pending.push({ event, failedAt, error });\n updateTimelineCache(runtime, blockId, {\n pending: pending.slice(-MAX_PENDING_TIMELINE_EVENTS),\n error,\n });\n}\n\nfunction updateTimelineCache(\n runtime: FlowRuntimeStateManager,\n blockId: string,\n patch: {\n pending?: PendingRunTimelineEvent[];\n error?: string;\n lastEventId?: string;\n }\n): void {\n const current = runtime.get(blockId);\n const cache = { ...(current.cache || {}) };\n if (patch.pending !== undefined) {\n if (patch.pending.length > 0) cache[TIMELINE_PENDING_CACHE_KEY] = patch.pending;\n else delete cache[TIMELINE_PENDING_CACHE_KEY];\n }\n if (patch.error !== undefined) cache[TIMELINE_ERROR_CACHE_KEY] = patch.error;\n else if (patch.pending !== undefined && patch.pending.length === 0) delete cache[TIMELINE_ERROR_CACHE_KEY];\n runtime.update(blockId, {\n cache,\n ...(patch.lastEventId ? { lastEventId: patch.lastEventId } : {}),\n } as Partial<FlowNodeRuntimeState>);\n}\n\n/**\n * Append one canonical run event. Post-effect failures can be retained for\n * replay; preflight failures pass retainOnFailure=false and abort execution.\n */\nexport async function appendRunTimelineEvent(params: {\n eventLog?: RunEventAppender;\n event: RunEventInput;\n runtime?: FlowRuntimeStateManager;\n blockId?: string;\n retainOnFailure?: boolean;\n now?: () => number;\n}): Promise<RunTimelineAppendResult> {\n if (!params.eventLog) {\n return { ok: false, error: 'A run event log is required for multi-run execution.' };\n }\n try {\n const eventId = await params.eventLog.append(params.event);\n if (params.runtime && params.blockId) {\n const pending = readPending(params.runtime, params.blockId).filter((entry) => entry.event.idempotencyKey !== params.event.idempotencyKey);\n updateTimelineCache(params.runtime, params.blockId, { pending, lastEventId: eventId });\n }\n return { ok: true, eventId };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append run timeline event';\n if (params.retainOnFailure !== false && params.runtime && params.blockId) {\n retainPending(params.runtime, params.blockId, params.event, message, params.now?.() ?? Date.now());\n }\n return { ok: false, error: message };\n }\n}\n\n/**\n * Append an ordered event sequence. If one append fails, it and every event\n * after it are retained in order so recovery cannot publish `action.done`\n * ahead of the missing `action.output`.\n */\nexport async function appendRunTimelineEvents(params: {\n eventLog?: RunEventAppender;\n events: RunEventInput[];\n runtime: FlowRuntimeStateManager;\n blockId: string;\n retainOnFailure?: boolean;\n now?: () => number;\n}): Promise<{\n ok: boolean;\n appended: number;\n remaining: number;\n lastEventId?: string;\n error?: string;\n}> {\n let appended = 0;\n let lastEventId: string | undefined;\n for (let index = 0; index < params.events.length; index += 1) {\n const event = params.events[index]!;\n const result = await appendRunTimelineEvent({\n eventLog: params.eventLog,\n event,\n runtime: params.runtime,\n blockId: params.blockId,\n retainOnFailure: params.retainOnFailure,\n now: params.now,\n });\n if (result.eventId) lastEventId = result.eventId;\n if (!result.ok) {\n if (params.retainOnFailure !== false) {\n const failedAt = params.now?.() ?? Date.now();\n const error = result.error || 'Failed to append run timeline event';\n for (const remainingEvent of params.events.slice(index + 1)) {\n retainPending(params.runtime, params.blockId, remainingEvent, error, failedAt);\n }\n }\n return {\n ok: false,\n appended,\n remaining: readPending(params.runtime, params.blockId).length,\n ...(lastEventId ? { lastEventId } : {}),\n ...(result.error ? { error: result.error } : {}),\n };\n }\n appended += 1;\n }\n return {\n ok: true,\n appended,\n remaining: readPending(params.runtime, params.blockId).length,\n ...(lastEventId ? { lastEventId } : {}),\n };\n}\n\n/** Pure read used by status/recovery surfaces. */\nexport function readPendingRunTimelineEvents(yDoc: Y.Doc, sessionRunId: string, blockId: string): PendingRunTimelineEvent[] {\n return readPending(createRunScopedRuntimeManager(yDoc, sessionRunId), blockId).map((entry) => ({\n ...entry,\n event: JSON.parse(JSON.stringify(entry.event)) as RunEventInput,\n }));\n}\n\n/** Replay retained post-effect events in original order and clear successes. */\nexport async function retryPendingRunTimelineEvents(params: {\n yDoc: Y.Doc;\n sessionRunId: string;\n blockId: string;\n eventLog: RunEventAppender;\n now?: () => number;\n}): Promise<{ attempted: number; remaining: number; lastEventId?: string }> {\n const runtime = createRunScopedRuntimeManager(params.yDoc, params.sessionRunId);\n const pending = readPending(runtime, params.blockId);\n let attempted = 0;\n let lastEventId: string | undefined;\n for (const entry of pending) {\n attempted += 1;\n const result = await appendRunTimelineEvent({\n eventLog: params.eventLog,\n event: entry.event,\n runtime,\n blockId: params.blockId,\n retainOnFailure: true,\n now: params.now,\n });\n if (result.eventId) lastEventId = result.eventId;\n if (!result.ok) break;\n }\n return {\n attempted,\n remaining: readPending(runtime, params.blockId).length,\n ...(lastEventId ? { lastEventId } : {}),\n };\n}\n\n/**\n * Matrix canonical JSON forbids non-integer numbers and integers outside\n * ±(2^53 - 1) — Synapse rejects the whole event with M_BAD_JSON otherwise.\n * Event copies are diagnostic (authoritative values live in the Y.Doc), so\n * unsafe numbers are carried as strings rather than dropped.\n */\nfunction toCanonicalJsonSafe(value: RunJsonValue): RunJsonValue {\n if (typeof value === 'number') {\n return Number.isSafeInteger(value) ? value : String(value);\n }\n if (Array.isArray(value)) return value.map(toCanonicalJsonSafe);\n if (value && typeof value === 'object') {\n const result: Record<string, RunJsonValue> = {};\n for (const [key, entry] of Object.entries(value)) result[key] = toCanonicalJsonSafe(entry);\n return result;\n }\n return value;\n}\n\n/**\n * Bound arbitrary JSON before embedding it in an event. Inputs are diagnostic,\n * not authoritative; oversized values become the same compact marker.\n */\nexport function boundRunEventJson(value: unknown): RunJsonValue {\n const json = value === undefined ? null : toCanonicalJsonSafe(JSON.parse(JSON.stringify(value)) as RunJsonValue);\n if (jsonByteLength(json) <= MAX_RUN_ACTION_OUTPUT_BYTES) return json;\n const wrapped =\n json && typeof json === 'object' && !Array.isArray(json) ? boundRunActionOutput(json as Record<string, unknown>).output : boundRunActionOutput({ value: json }).output;\n return wrapped as RunJsonValue;\n}\n","import type { UcanCapability } from '../../types/ucan';\n\n/** Signed authority carried by one atomic Matrix terminal event. */\nexport interface RunTerminalAuthorizationProof {\n invocationCid: string;\n invocation: string;\n actorDid: string;\n actionType: 'qi/flow.run.close';\n actionBlockId: string;\n inputDigest: string;\n actionInputs: Record<string, unknown>;\n capability: UcanCapability;\n proofCids: string[];\n}\n\n/** Build the canonical authorization envelope shared by action and Portal close paths. */\nexport function createRunTerminalAuthorizationProof(params: Omit<RunTerminalAuthorizationProof, 'actionType'>): RunTerminalAuthorizationProof {\n return {\n invocationCid: params.invocationCid,\n invocation: params.invocation,\n actorDid: params.actorDid,\n actionType: 'qi/flow.run.close',\n actionBlockId: params.actionBlockId,\n inputDigest: params.inputDigest,\n actionInputs: { ...params.actionInputs },\n capability: { ...params.capability },\n proofCids: [...params.proofCids],\n };\n}\n","import type { OutputSchemaField } from '../../types';\n\n/**\n * SurveyJS question types mapped to our OutputSchemaField types. Unknown\n * SurveyJS types default to 'string' — these show up as text refs in the\n * downstream reference picker, which is safe but unhelpful; extend the map\n * when new survey question types appear in real templates.\n */\nconst TYPE_MAP: Record<string, OutputSchemaField['type']> = {\n text: 'string',\n comment: 'string',\n html: 'string',\n expression: 'string',\n dropdown: 'string',\n radiogroup: 'string',\n rating: 'number',\n number: 'number',\n boolean: 'boolean',\n checkbox: 'array',\n tagbox: 'array',\n ranking: 'array',\n imagepicker: 'array',\n file: 'array',\n paneldynamic: 'array',\n matrix: 'object',\n matrixdropdown: 'object',\n matrixdynamic: 'object',\n multipletext: 'object',\n panel: 'object',\n};\n\ninterface SurveyElement {\n name?: string;\n title?: string;\n type?: string;\n description?: string;\n elements?: SurveyElement[]; // panels nest\n /** paneldynamic: shape of each iteration row. */\n templateElements?: SurveyElement[];\n}\n\ninterface SurveyJson {\n pages?: Array<{ elements?: SurveyElement[] }>;\n elements?: SurveyElement[];\n}\n\n/**\n * Extract the answer schema from a SurveyJS template.\n *\n * Recurses into `panel` containers so grouped questions surface as flat\n * `surveyAnswers.<name>` fields. Returns [] for an empty / unparseable survey\n * so callers can treat \"no schema yet\" as a normal state.\n *\n * The returned field paths are **relative** — callers typically prefix them\n * with `surveyAnswers.` when composing an event payload schema.\n */\nexport function extractSurveyAnswerSchema(survey: unknown): OutputSchemaField[] {\n if (!survey || typeof survey !== 'object') return [];\n const json = survey as SurveyJson;\n\n const collected: OutputSchemaField[] = [];\n const seen = new Set<string>();\n\n const walk = (elements: SurveyElement[] | undefined) => {\n if (!Array.isArray(elements)) return;\n for (const el of elements) {\n if (!el || typeof el !== 'object') continue;\n // Panels don't hold an answer themselves — descend into their children.\n if (el.type === 'panel' && Array.isArray(el.elements)) {\n walk(el.elements);\n continue;\n }\n const name = typeof el.name === 'string' ? el.name.trim() : '';\n if (!name) continue;\n if (seen.has(name)) continue;\n seen.add(name);\n\n const rawType = typeof el.type === 'string' ? el.type : '';\n const mapped = TYPE_MAP[rawType] ?? 'string';\n\n // For paneldynamic, recurse into `templateElements` to capture the\n // per-item shape. Element-scoped pickers (iterative mappers) read this\n // from `OutputSchemaField.itemSchema`.\n let itemSchema: OutputSchemaField[] | undefined;\n if (rawType === 'paneldynamic' && Array.isArray(el.templateElements) && el.templateElements.length > 0) {\n const nested: OutputSchemaField[] = [];\n const nestedSeen = new Set<string>();\n const walkNested = (inner: SurveyElement[]) => {\n for (const child of inner) {\n if (!child || typeof child !== 'object') continue;\n if (child.type === 'panel' && Array.isArray(child.elements)) {\n walkNested(child.elements);\n continue;\n }\n const childName = typeof child.name === 'string' ? child.name.trim() : '';\n if (!childName || nestedSeen.has(childName)) continue;\n nestedSeen.add(childName);\n const childType = typeof child.type === 'string' ? child.type : '';\n nested.push({\n path: childName,\n displayName: stripHtml(String(child.title || '').trim() || humanize(childName)),\n type: TYPE_MAP[childType] ?? 'string',\n description: typeof child.description === 'string' && child.description.trim() ? stripHtml(child.description.trim()) : undefined,\n });\n }\n };\n walkNested(el.templateElements);\n if (nested.length > 0) itemSchema = nested;\n }\n\n collected.push({\n path: name,\n displayName: stripHtml(String(el.title || '').trim() || humanize(name)),\n type: mapped,\n description: typeof el.description === 'string' && el.description.trim() ? stripHtml(el.description.trim()) : undefined,\n ...(itemSchema ? { itemSchema } : {}),\n });\n }\n };\n\n if (Array.isArray(json.pages) && json.pages.length > 0) {\n for (const page of json.pages) walk(page.elements);\n }\n walk(json.elements);\n\n return collected;\n}\n\n/**\n * Prefix a survey-answer schema with `surveyAnswers.` so the fields slot into\n * an event payloadSchema cleanly.\n */\nexport function prefixSurveyAnswerSchema(fields: OutputSchemaField[], namespace = 'surveyAnswers'): OutputSchemaField[] {\n // Preserve `itemSchema` when prefixing — only the top-level path moves.\n return fields.map((f) => ({\n ...f,\n path: `${namespace}.${f.path}`,\n }));\n}\n\nfunction humanize(name: string): string {\n return name.replace(/[-_]+/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\nfunction stripHtml(s: string): string {\n return s\n .replace(/<[^>]*>/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n","import type { Doc as YDoc, Map as YMap } from 'yjs';\n\nexport type XeroWorkKind = 'invoice.create' | 'payment.create';\n/**\n * `approved` is the human gate for oracle-managed settlement: a `pending`\n * payment item is only a review card until the flow owner approves it; the\n * flow-manager contractor picks up `approved` items exclusively.\n */\nexport type XeroWorkStatus = 'pending' | 'approved' | 'failed' | 'completed' | 'cancelled';\n\nexport interface XeroWorkAttempt {\n at: number;\n byDid?: string;\n payload: Record<string, any>;\n error?: string;\n result?: Record<string, any>;\n}\n\nexport interface XeroWorkSource {\n claimId: string;\n evaluationBlockId: string;\n deedDid: string;\n collectionId: string;\n invoiceWorkItemId?: string;\n}\n\nexport interface XeroWorkProvenance {\n createdAt: number;\n createdByDid?: string;\n templateBlockId: string;\n templateInputsSnapshot?: unknown;\n evaluationOutput?: Record<string, any>;\n claimSnapshot?: Record<string, any>;\n}\n\nexport interface XeroWorkItem {\n id: string;\n kind: XeroWorkKind;\n status: XeroWorkStatus;\n assignedBlockId: string;\n idempotencyKey: string;\n source: XeroWorkSource;\n originalPayload: Record<string, any>;\n reviewPayload: Record<string, any>;\n submittedPayload?: Record<string, any>;\n provenance: XeroWorkProvenance;\n attempts: XeroWorkAttempt[];\n result?: Record<string, any>;\n error?: { message: string; at: number };\n approvedAt?: number;\n approvedByDid?: string;\n completedAt?: number;\n completedByDid?: string;\n}\n\nexport const XERO_WORK_ITEMS_MAP_NAME = 'xeroWorkItems';\nexport const XERO_WORK_TERMINAL_MAP_NAME = 'xeroWorkItemsTerminal';\n\n/**\n * Write-once record of a completed work item, stored under its own key in a\n * separate Y.Map. This is what makes \"completed is never downgraded\" a\n * *distributed* invariant rather than a local guard: each item lives in the\n * base map as one plain object, so two disconnected peers concurrently\n * writing `completed` and `failed` merge last-writer-wins on the whole value\n * — the losing write is erased and no local status check ever runs. A key\n * that only completion writes (and nothing deletes) cannot lose a merge, so\n * the success survives regardless of Yjs tie-breaking; readers overlay it\n * over whatever the base object says. Concurrent duplicate completions are\n * interchangeable records of the same fact — LWW keeping either is correct.\n */\nexport interface XeroWorkTerminalRecord {\n itemId: string;\n reviewPayload?: Record<string, any>;\n submittedPayload?: Record<string, any>;\n result?: Record<string, any>;\n completedAt: number;\n completedByDid?: string;\n}\n\nexport type XeroWorkItemFilter = { kind?: XeroWorkKind; assignedBlockId?: string; statuses?: XeroWorkStatus[] };\n\n/**\n * Statuses meaning \"the oracle lane is actively working this item\", per kind —\n * the contract behind every settlement indicator. Invoice drafting has no\n * human gate: the flow-manager contracts `pending` invoice items directly, so\n * a pending invoice is already queued oracle work. A `pending` payment item is\n * only a review card awaiting the flow owner; approval is what moves it into\n * the oracle lane.\n */\nexport const XERO_ORACLE_WORKING_STATUSES: Record<XeroWorkKind, XeroWorkStatus[]> = {\n 'invoice.create': ['pending', 'approved'],\n 'payment.create': ['approved'],\n};\n\nexport const XERO_PAYMENT_CREATE_ACTION_TYPE = 'qi/xero.payment.create';\n\n/**\n * The oracle-working indicator for the whole Xero settlement chain anchors on\n * the `qi/xero.payment.create` action block — the one user-facing settlement\n * surface (its detail page is where drafts are reviewed and approved). Any\n * other block resolves to null. Invoice work items are assigned to the\n * evaluation block that minted them, so they are matched doc-wide here rather\n * than by `assignedBlockId`; payment items belong to the block itself. The\n * invoice stage outranks the payment stage: while an invoice is still being\n * drafted, that is the activity to show.\n */\nexport function xeroOracleActivityForBlock(map: YMap<XeroWorkItem> | null | undefined, params: { blockId: string; actionType?: string }): XeroWorkKind | null {\n if (params.actionType !== XERO_PAYMENT_CREATE_ACTION_TYPE) return null;\n if (findXeroWorkItems(map, { kind: 'invoice.create', statuses: XERO_ORACLE_WORKING_STATUSES['invoice.create'] }).length > 0) return 'invoice.create';\n if (findXeroWorkItems(map, { kind: 'payment.create', assignedBlockId: params.blockId, statuses: XERO_ORACLE_WORKING_STATUSES['payment.create'] }).length > 0)\n return 'payment.create';\n return null;\n}\n\n/**\n * Resolve the work-items map from a raw Y.Doc. Flow-manager (and any other\n * consumer holding the doc rather than an editor instance) goes through this.\n */\nexport function getXeroWorkItemsMap(doc: YDoc): YMap<XeroWorkItem> {\n return doc.getMap<XeroWorkItem>(XERO_WORK_ITEMS_MAP_NAME);\n}\n\n/** Resolve the terminal-records map from a raw Y.Doc. */\nexport function getXeroWorkTerminalMap(doc: YDoc): YMap<XeroWorkTerminalRecord> {\n return doc.getMap<XeroWorkTerminalRecord>(XERO_WORK_TERMINAL_MAP_NAME);\n}\n\n/** The terminal map sharing a doc with the given items map (null when the map is unintegrated). */\nfunction terminalMapFor(map: YMap<XeroWorkItem> | null | undefined): YMap<XeroWorkTerminalRecord> | null {\n return map?.doc ? getXeroWorkTerminalMap(map.doc) : null;\n}\n\n/**\n * Effective view of an item: a terminal record outranks whatever the base\n * object says — status is decided by the highest-ranking status ever\n * recorded, not by whichever peer's write happened to win the CRDT merge.\n */\nfunction resolveItem(terminal: YMap<XeroWorkTerminalRecord> | null, item: XeroWorkItem): XeroWorkItem {\n const record = terminal?.get(item.id);\n if (!record || item.status === 'completed') return item;\n return {\n ...item,\n status: 'completed',\n error: undefined,\n ...(record.reviewPayload !== undefined ? { reviewPayload: record.reviewPayload } : {}),\n ...(record.submittedPayload !== undefined ? { submittedPayload: record.submittedPayload } : {}),\n ...(record.result !== undefined ? { result: record.result } : {}),\n completedAt: record.completedAt,\n ...(record.completedByDid !== undefined ? { completedByDid: record.completedByDid } : {}),\n };\n}\n\n/** Mint the write-once terminal record for a completed item (an existing record wins). */\nfunction ensureTerminalRecord(terminal: YMap<XeroWorkTerminalRecord> | null, item: XeroWorkItem): void {\n if (!terminal || terminal.get(item.id)) return;\n terminal.set(item.id, {\n itemId: item.id,\n ...(item.reviewPayload !== undefined ? { reviewPayload: item.reviewPayload } : {}),\n ...(item.submittedPayload !== undefined ? { submittedPayload: item.submittedPayload } : {}),\n ...(item.result !== undefined ? { result: item.result } : {}),\n completedAt: item.completedAt ?? Date.now(),\n ...(item.completedByDid !== undefined ? { completedByDid: item.completedByDid } : {}),\n });\n}\n\nfunction getEditorXeroWorkItemsMap(editor?: any): YMap<XeroWorkItem> | null {\n return (editor?._yXeroWorkItems as YMap<XeroWorkItem> | undefined) || null;\n}\n\nfunction readMapItems(map: YMap<XeroWorkItem> | null | undefined): XeroWorkItem[] {\n if (!map) return [];\n const terminal = terminalMapFor(map);\n const items: XeroWorkItem[] = [];\n map.forEach((value) => {\n if (value && typeof value === 'object' && 'id' in value) {\n items.push(resolveItem(terminal, { ...(value as XeroWorkItem) }));\n }\n });\n return items;\n}\n\n/**\n * Completed-item merge guard — the single implementation shared by every\n * writer (editor-instance and doc-level alike). A `completed` item is\n * immutable: merging anything into it returns it unchanged. This is the\n * ordered-local-writes half of the invariant; the terminal-record overlay\n * (`resolveItem`) is the half that survives concurrent peers merging.\n */\nfunction mergeItem(existing: XeroWorkItem, next: XeroWorkItem): XeroWorkItem {\n if (existing.status === 'completed') {\n return existing;\n }\n\n return {\n ...existing,\n ...next,\n id: existing.id,\n // A re-upsert (e.g. a replayed receipt re-creating the payment item as\n // `pending`) must never revoke a human approval already recorded.\n status: existing.status === 'approved' && next.status === 'pending' ? existing.status : next.status,\n attempts: existing.attempts ?? [],\n originalPayload: existing.originalPayload,\n submittedPayload: existing.submittedPayload,\n result: existing.result,\n approvedAt: existing.approvedAt,\n approvedByDid: existing.approvedByDid,\n completedAt: existing.completedAt,\n completedByDid: existing.completedByDid,\n };\n}\n\n// ── Idempotency keys (§4.1) ─────────────────────────────────────\n// One invoice work item per approved claim per evaluation block. Re-approving\n// the same claim re-upserts the same key; `mergeItem` protects completed items.\n\nexport function buildXeroInvoiceWorkKey(params: { flowId: string; evaluationBlockId: string; claimId: string }): string {\n return ['xero', 'invoice.create', params.flowId, params.evaluationBlockId, params.claimId].join(':');\n}\n\nexport function buildXeroPaymentWorkKey(params: { flowId: string; evaluationBlockId: string; claimId: string; invoiceWorkItemId: string }): string {\n return ['xero', 'payment.create', params.flowId, params.evaluationBlockId, params.claimId, params.invoiceWorkItemId].join(':');\n}\n\n// ── Doc-level helpers — operate on the Y.Map directly ───────────\n// Flow-manager holds a raw Y.Doc (`getXeroWorkItemsMap(doc)`), not an editor\n// instance. These are the canonical implementations; the `...ForEditor`\n// variants below delegate here so the merge guard exists exactly once.\n\nexport function findXeroWorkItems(map: YMap<XeroWorkItem> | null | undefined, filter: XeroWorkItemFilter = {}): XeroWorkItem[] {\n return readMapItems(map).filter((item) => {\n if (filter.kind && item.kind !== filter.kind) return false;\n if (filter.assignedBlockId && item.assignedBlockId !== filter.assignedBlockId) return false;\n if (filter.statuses && !filter.statuses.includes(item.status)) return false;\n return true;\n });\n}\n\n/**\n * Idempotencykey-deduped upsert. An existing item with the same\n * `idempotencyKey` is merged (never resurrecting a `completed` item);\n * otherwise the item is stored as given.\n */\nexport function upsertXeroWorkItem(map: YMap<XeroWorkItem> | null | undefined, next: XeroWorkItem): XeroWorkItem {\n if (!map) {\n return next;\n }\n\n const terminal = terminalMapFor(map);\n let existing: XeroWorkItem | undefined;\n map.forEach((item) => {\n if (item?.idempotencyKey === next.idempotencyKey) existing = item;\n });\n\n const stored = existing ? mergeItem(resolveItem(terminal, existing), next) : next;\n const write = () => {\n map.set(stored.id, stored);\n // An upsert carrying `completed` (e.g. a replayed receipt) must mint the\n // merge-proof record too, not just the clobberable base object.\n if (stored.status === 'completed') ensureTerminalRecord(terminal, stored);\n };\n if (map.doc) map.doc.transact(write);\n else write();\n return stored;\n}\n\nexport function updateXeroWorkReviewPayload(map: YMap<XeroWorkItem> | null | undefined, itemId: string, reviewPayload: Record<string, any>): XeroWorkItem | null {\n if (!map) return null;\n const raw = map.get(itemId);\n if (!raw) return null;\n const item = resolveItem(terminalMapFor(map), raw);\n if (item.status === 'completed') return item;\n const updatedItem = { ...item, reviewPayload };\n map.set(itemId, updatedItem);\n return updatedItem;\n}\n\n/**\n * Record a failed attempt and flip the item to `failed`. Refuses to downgrade\n * a `completed` item — a late/duplicate failure receipt must never erase a\n * recorded success.\n */\nexport function markXeroWorkFailed(\n map: YMap<XeroWorkItem> | null | undefined,\n itemId: string,\n params: { byDid?: string; payload: Record<string, any>; error: string; at?: number }\n): XeroWorkItem | null {\n if (!map) return null;\n const raw = map.get(itemId);\n if (!raw) return null;\n const item = resolveItem(terminalMapFor(map), raw);\n if (item.status === 'completed') return item;\n const at = params.at ?? Date.now();\n const updatedItem: XeroWorkItem = {\n ...item,\n status: 'failed',\n reviewPayload: params.payload,\n error: { message: params.error, at },\n attempts: [...(item.attempts ?? []), { at, byDid: params.byDid, payload: params.payload, error: params.error }],\n };\n map.set(itemId, updatedItem);\n return updatedItem;\n}\n\n/**\n * Record the human approval and flip the item to `approved` — the gate the\n * flow-manager contractor requires before contracting the settlement oracle.\n * Approvable from `pending` (first review) or `failed` (human retry after\n * attempt exhaustion). Idempotent on `approved`; refuses `completed` and\n * `cancelled` items.\n */\nexport function markXeroWorkApproved(map: YMap<XeroWorkItem> | null | undefined, itemId: string, params: { byDid?: string; at?: number }): XeroWorkItem | null {\n if (!map) return null;\n const raw = map.get(itemId);\n if (!raw) return null;\n const item = resolveItem(terminalMapFor(map), raw);\n if (item.status === 'approved' || item.status === 'completed' || item.status === 'cancelled') return item;\n const at = params.at ?? Date.now();\n const updatedItem: XeroWorkItem = {\n ...item,\n status: 'approved',\n error: undefined,\n approvedAt: at,\n approvedByDid: params.byDid,\n };\n map.set(itemId, updatedItem);\n return updatedItem;\n}\n\n/**\n * Record a successful attempt and flip the item to `completed`. Idempotent:\n * an already-completed item is returned unchanged — the first recorded result\n * wins and is never overwritten. Alongside the base object, a write-once\n * terminal record is minted under its own key, so the success survives a\n * concurrent conflicting write from a disconnected peer (see\n * `XeroWorkTerminalRecord`).\n */\nexport function markXeroWorkCompleted(\n map: YMap<XeroWorkItem> | null | undefined,\n itemId: string,\n params: { byDid?: string; payload: Record<string, any>; result: Record<string, any>; at?: number }\n): XeroWorkItem | null {\n if (!map) return null;\n const raw = map.get(itemId);\n if (!raw) return null;\n const terminal = terminalMapFor(map);\n const item = resolveItem(terminal, raw);\n if (item.status === 'completed') return item;\n const at = params.at ?? Date.now();\n const updatedItem: XeroWorkItem = {\n ...item,\n status: 'completed',\n reviewPayload: params.payload,\n submittedPayload: params.payload,\n result: params.result,\n error: undefined,\n completedAt: at,\n completedByDid: params.byDid,\n attempts: [...(item.attempts ?? []), { at, byDid: params.byDid, payload: params.payload, result: params.result }],\n };\n const write = () => {\n map.set(itemId, updatedItem);\n ensureTerminalRecord(terminal, updatedItem);\n };\n if (map.doc) map.doc.transact(write);\n else write();\n return updatedItem;\n}\n\n// ── Editor-instance helpers — thin delegates ────────────────────\n\nexport function findXeroWorkItemsForEditor(editor: any, filter: XeroWorkItemFilter): XeroWorkItem[] {\n return findXeroWorkItems(getEditorXeroWorkItemsMap(editor), filter);\n}\n\nexport function xeroOracleActivityForBlockForEditor(editor: any, params: { blockId: string; actionType?: string }): XeroWorkKind | null {\n return xeroOracleActivityForBlock(getEditorXeroWorkItemsMap(editor), params);\n}\n\nexport function upsertXeroWorkItemForEditor(editor: any, next: XeroWorkItem): XeroWorkItem {\n return upsertXeroWorkItem(getEditorXeroWorkItemsMap(editor), next);\n}\n\nexport function updateXeroWorkReviewPayloadForEditor(editor: any, itemId: string, reviewPayload: Record<string, any>): XeroWorkItem | null {\n return updateXeroWorkReviewPayload(getEditorXeroWorkItemsMap(editor), itemId, reviewPayload);\n}\n\nexport function markXeroWorkApprovedForEditor(editor: any, itemId: string, params: { byDid?: string; at?: number }): XeroWorkItem | null {\n return markXeroWorkApproved(getEditorXeroWorkItemsMap(editor), itemId, params);\n}\n\nexport function markXeroWorkFailedForEditor(\n editor: any,\n itemId: string,\n params: { byDid?: string; payload: Record<string, any>; error: string; at?: number }\n): XeroWorkItem | null {\n return markXeroWorkFailed(getEditorXeroWorkItemsMap(editor), itemId, params);\n}\n\nexport function markXeroWorkCompletedForEditor(\n editor: any,\n itemId: string,\n params: { byDid?: string; payload: Record<string, any>; result: Record<string, any>; at?: number }\n): XeroWorkItem | null {\n return markXeroWorkCompleted(getEditorXeroWorkItemsMap(editor), itemId, params);\n}\n","import type { ActionHandlers } from '../../types';\n\n/**\n * The stored answer to \"is there still work for this evaluation block?\".\n *\n * Written into the block's runtime `output` (merged, never replacing the\n * proof fields) so the pure `done.isDone` fold and every session summary can\n * answer without touching Blocksync. Refreshed only at the three natural\n * moments — after an evaluation, when the block is opened, and on a close\n * attempt — never on a timer.\n */\nexport interface PendingClaimSnapshot {\n /** Claims in the collection with no terminal evaluation recorded. */\n pendingClaimCount: number;\n /** Unix ms of the Blocksync read that produced `pendingClaimCount`. */\n pendingCheckedAt: number;\n /** The collection can no longer accept claims (closed, or past its end date). */\n collectionClosed: boolean;\n}\n\nexport const PENDING_CLAIM_SNAPSHOT_SOURCE = 'blocksync.claims';\n\nconst SETTLED_ENUM_STATUSES = new Set([1, 2, 3, 4]);\nconst SETTLED_STRING_STATUSES = new Set(['approved', 'rejected', 'disputed', 'invalidated']);\n\nfunction toNumber(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const numeric = Number(value);\n return Number.isFinite(numeric) ? numeric : null;\n }\n return null;\n}\n\nfunction isSettledStatus(value: unknown): boolean {\n const numeric = toNumber(value);\n if (numeric !== null) return SETTLED_ENUM_STATUSES.has(numeric);\n return SETTLED_STRING_STATUSES.has(\n String(value ?? '')\n .trim()\n .toLowerCase()\n );\n}\n\n/**\n * A claim stays pending until it is settled: approved, rejected, invalidated,\n * or disputed. Disputed counts as settled because the evaluate block locks its\n * slider for a disputed claim (see `isClaimEvaluated` in the block UI) — the\n * dispute process, not this block, owes the next move.\n */\nexport function isClaimPending(claim: unknown): boolean {\n if (!claim || typeof claim !== 'object') return false;\n const record = claim as Record<string, any>;\n if (isSettledStatus(record.evaluationByClaimId?.status)) return false;\n if (record.disputeBySubjectId) return false;\n if (isSettledStatus(record.status)) return false;\n const payments = record.paymentsStatus;\n if (payments && typeof payments === 'object') {\n if (payments.approval === 'PAID' || payments.rejection === 'PAID') return false;\n }\n return true;\n}\n\nexport function countPendingClaims(claims: unknown): number {\n if (!Array.isArray(claims)) return 0;\n return claims.filter(isClaimPending).length;\n}\n\n/**\n * Blocksync reports `state` as the chain enum name (\"CLOSED\") and the editor's\n * `CollectionService` as the numeric enum (2). Accept both.\n */\nexport function isCollectionClosed(collection: unknown, now: number): boolean {\n if (!collection || typeof collection !== 'object') return false;\n const record = collection as Record<string, any>;\n const state = record.state;\n if (toNumber(state) === 2) return true;\n if (\n String(state ?? '')\n .trim()\n .toUpperCase() === 'CLOSED'\n )\n return true;\n const endDate = record.endDate ? Date.parse(String(record.endDate)) : NaN;\n return Number.isFinite(endDate) && endDate <= now;\n}\n\nexport function buildPendingClaimSnapshot(params: { claims: unknown; collection?: unknown; now: number }): PendingClaimSnapshot {\n return {\n pendingClaimCount: countPendingClaims(params.claims),\n pendingCheckedAt: params.now,\n collectionClosed: isCollectionClosed(params.collection, params.now),\n };\n}\n\nexport function readPendingClaimSnapshot(output: Record<string, unknown> | undefined | null): PendingClaimSnapshot | null {\n const count = toNumber(output?.pendingClaimCount);\n if (count === null) return null;\n const checkedAt = toNumber(output?.pendingCheckedAt) ?? 0;\n return { pendingClaimCount: count, pendingCheckedAt: checkedAt, collectionClosed: output?.collectionClosed === true };\n}\n\nexport function samePendingClaimSnapshot(left: PendingClaimSnapshot | null, right: PendingClaimSnapshot | null): boolean {\n if (!left || !right) return left === right;\n return left.pendingClaimCount === right.pendingClaimCount && left.collectionClosed === right.collectionClosed;\n}\n\nexport function findCollection(collections: unknown, collectionId: string): unknown {\n const list = Array.isArray(collections) ? collections : Array.isArray((collections as any)?.collections) ? (collections as any).collections : [];\n return list.find((entry: any) => String(entry?.id ?? '') === collectionId);\n}\n\n/**\n * One Blocksync round trip: the collection's claims plus the collection row\n * (for its state and end date). Throws when the claim read is unavailable so\n * callers can report `unknown` rather than a false zero.\n */\nexport async function fetchPendingClaimSnapshot(\n handlers: ActionHandlers | undefined,\n params: { collectionId: string; deedDid: string },\n now: number\n): Promise<PendingClaimSnapshot> {\n const listClaims = handlers?.getClaimsPerCollectionId;\n if (typeof listClaims !== 'function') {\n throw new Error('Claim listing is unavailable (getClaimsPerCollectionId handler missing)');\n }\n const [claims, collection] = await Promise.all([listClaims({ collectionId: params.collectionId }), readCollection(handlers, params).catch(() => undefined)]);\n return buildPendingClaimSnapshot({ claims, collection, now });\n}\n\nasync function readCollection(handlers: ActionHandlers | undefined, params: { collectionId: string; deedDid: string }): Promise<unknown> {\n if (!params.deedDid) return undefined;\n if (typeof handlers?.getOnlyClaimCollections === 'function') {\n return findCollection(await handlers.getOnlyClaimCollections(params.deedDid), params.collectionId);\n }\n if (typeof handlers?.getClaimCollections === 'function') {\n return findCollection(await handlers.getClaimCollections(params.deedDid), params.collectionId);\n }\n return undefined;\n}\n","import type { OutputSchemaField } from '../../types';\n\n/**\n * Canonical action type for the single claim-collection user-management block\n * (IXO-2586). One block, one runtime entry; `run()` dispatches on the\n * `operation` input (add | revoke | list). Extends and is intended to replace\n * `qi/bid.evaluate` once tested.\n */\nexport const COLLECTION_USERS_ACTION_TYPE = 'qi/collection.users';\n\n/**\n * How many grants ride in a single transaction on a bulk add (IXO-4396).\n *\n * A pasted list of up to this many accounts is one message batch = one\n * signature. Past it the dispatcher splits the list into consecutive batches of\n * this size and signs each one, because a single transaction carrying hundreds\n * of authorization messages exceeds the chain's gas/size limits (and stalls the\n * SignX round trip) — so the split is deliberate and surfaced to the user up\n * front, never a silent surprise mid-signing.\n */\nexport const COLLECTION_USERS_MAX_GRANTS_PER_TX = 40;\n\n/** Number of transactions a bulk add of `count` accounts will ask the user to sign. */\nexport function collectionUsersBatchCount(count: number): number {\n if (!Number.isFinite(count) || count <= 0) return 0;\n return Math.ceil(count / COLLECTION_USERS_MAX_GRANTS_PER_TX);\n}\n\n/**\n * Output schema. The shape of `output` depends on the operation that last ran:\n * `add`/`revoke` write a `transactionHash` (the proof field); `list` writes a\n * `grantees` array. All fields are declared so the reference picker can target\n * any of them.\n */\nexport const COLLECTION_USERS_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'operation', displayName: 'Operation', type: 'string', description: 'Which op produced this output: add, revoke or list' },\n { path: 'transactionHash', displayName: 'Tx Hash', type: 'string', description: 'Broadcast transaction hash (add/revoke)' },\n { path: 'grantedCount', displayName: 'Granted Count', type: 'number', description: 'Number of grants broadcast (fan-out)' },\n { path: 'role', displayName: 'Role', type: 'string', description: 'submit or evaluate' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Target claim collection identifier' },\n { path: 'granteeAddress', displayName: 'Grantee Address', type: 'string', description: 'Address granted/revoked' },\n { path: 'granteeAddresses', displayName: 'Grantee Addresses', type: 'array', description: 'Every address granted by a bulk/fan-out add' },\n {\n path: 'grantees',\n displayName: 'Grantees',\n type: 'array',\n description: 'Grantees holding a constraint for the collection (list)',\n itemSchema: [\n { path: 'address', displayName: 'Address', type: 'string' },\n { path: 'role', displayName: 'Role', type: 'string' },\n { path: 'agentQuota', displayName: 'Agent Quota', type: 'string' },\n { path: 'intentDurationNs', displayName: 'Intent Duration (ns)', type: 'string' },\n ],\n },\n];\n\n// NOTE: The action is registered (with the real operation dispatcher `run()`)\n// in `./collectionUsers`. This module intentionally exports only the shared\n// constants (action type + output schema) that `./collectionUsers`, the\n// FlowDetail and the diff resolver import, so there is exactly one\n// `registerAction` call for `qi/collection.users`.\n","import type { PinnedConnection } from '@/mantine/blocks/action/actionTypes/_shared/ConnectionSelector';\n\n/**\n * Template storage shape for `qi/calendar.event.create`.\n * Field names mirror the `GOOGLECALENDAR_CREATE_EVENT` schema verbatim — see\n * `docs/integrations-reference/tools/GOOGLECALENDAR_CREATE_EVENT.json`.\n * Do NOT introduce a translation layer (see integrations-plan.md §7).\n */\nexport interface CalendarEventCreateInputs {\n connection: PinnedConnection | null;\n calendar_id: string;\n summary: string;\n description: string;\n location: string;\n timezone: string;\n /** ISO 8601. Required by Composio. */\n start_datetime: string;\n /** ISO 8601. Optional; when empty, duration fields are used. */\n end_datetime: string;\n /** JSON array of email strings. Stored as string for DataInput compatibility. */\n attendees: string;\n send_updates: string;\n}\n\nconst EMPTY: CalendarEventCreateInputs = {\n connection: null,\n calendar_id: 'primary',\n summary: '',\n description: '',\n location: '',\n timezone: '',\n start_datetime: '',\n end_datetime: '',\n attendees: '',\n send_updates: '',\n};\n\nexport function parseCalendarEventCreateInputs(raw: string | Record<string, any> | undefined): CalendarEventCreateInputs {\n try {\n const parsed: any = typeof raw === 'string' ? JSON.parse(raw || '{}') : raw || {};\n const conn = parsed.connection;\n const connection: PinnedConnection | null =\n conn && typeof conn === 'object' && typeof conn.connectedAccountId === 'string' && typeof conn.entityDid === 'string'\n ? { connectedAccountId: conn.connectedAccountId, entityDid: conn.entityDid }\n : null;\n\n return {\n connection,\n calendar_id: typeof parsed.calendar_id === 'string' && parsed.calendar_id ? parsed.calendar_id : 'primary',\n summary: typeof parsed.summary === 'string' ? parsed.summary : '',\n description: typeof parsed.description === 'string' ? parsed.description : '',\n location: typeof parsed.location === 'string' ? parsed.location : '',\n timezone: typeof parsed.timezone === 'string' ? parsed.timezone : '',\n start_datetime: typeof parsed.start_datetime === 'string' ? parsed.start_datetime : '',\n end_datetime: typeof parsed.end_datetime === 'string' ? parsed.end_datetime : '',\n attendees: typeof parsed.attendees === 'string' ? parsed.attendees : Array.isArray(parsed.attendees) ? JSON.stringify(parsed.attendees) : '',\n send_updates: typeof parsed.send_updates === 'string' ? parsed.send_updates : '',\n };\n } catch {\n return { ...EMPTY };\n }\n}\n\nexport function serializeCalendarEventCreateInputs(inputs: CalendarEventCreateInputs): string {\n return JSON.stringify(inputs);\n}\n\n/**\n * Parse the `attendees` template field (may be a JSON array, newline-separated,\n * or comma-separated emails) into the shape Composio expects.\n */\nexport function parseAttendeesField(raw: string): Array<string> {\n const trimmed = (raw || '').trim();\n if (!trimmed) return [];\n if (trimmed.startsWith('[')) {\n try {\n const parsed = JSON.parse(trimmed);\n if (Array.isArray(parsed)) return parsed.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim());\n } catch {\n // fall through to split\n }\n }\n return trimmed\n .split(/[\\n,]+/)\n .map((s) => s.trim())\n .filter(Boolean);\n}\n","import * as Y from 'yjs';\nimport type { Doc as YDoc, Map as YMap } from 'yjs';\nimport { isYMapLike } from '../yjsTypes';\n\n/**\n * Top-level Y.Doc map holding the integrations a flow needs, keyed by toolkit\n * slug. This is template *configuration* — \"this flow talks to Xero, and needs\n * an organisation and a bank account picked before it can run\" — so it is NOT\n * cleared by `clearRuntimeForTemplateClone` (`flowEngine/runtime.ts`), exactly\n * like the participant roster: a clone that lost its requirements would come up\n * looking ready while every integration call has nowhere to go.\n */\nexport const FLOW_CONNECTIONS_MAP_KEY = 'qi.flow.connections';\n\n/**\n * Top-level Y.Doc map holding the concrete account/organisation/bank selections\n * made for *this* flow, keyed by toolkit slug.\n *\n * Bindings are execution state, not configuration: they name one workspace's\n * connected account. `clearRuntimeForTemplateClone` therefore clears this map —\n * a template cloned out of a live flow must not carry another entity's Xero\n * account into a room whose members were never granted access to it.\n */\nexport const FLOW_CONNECTION_BINDINGS_MAP_KEY = 'qi.flow.connectionBindings';\n\n/** Sub-selections a toolkit needs before it counts as satisfied. */\nexport type FlowConnectionRequirementKey = 'org' | 'bankAccount';\n\nconst REQUIREMENT_KEYS: readonly FlowConnectionRequirementKey[] = ['org', 'bankAccount'];\n\nexport type FlowConnection = {\n /** Toolkit slug, e.g. `'xero'`. Also the map key — one entry per toolkit. */\n toolkit: string;\n label?: string;\n /** Absent/false = required. True = the flow may start without it. */\n optional?: boolean;\n /**\n * Whether the flow's automated agent acts through this connection, decided by\n * the template author. Deliberately tri-state: `true` and `false` are both an\n * answer, and absent means nobody has answered yet, so a reader falls back to\n * inferring it from the agent-owned steps. A template written before this\n * field existed carries no answer and must keep behaving as it did.\n *\n * It governs what the flow ASKS FOR, never what an actor may be given: a\n * person can grant the agent any connection at flow time regardless.\n */\n agent?: boolean;\n requires: FlowConnectionRequirementKey[];\n /** Epoch ms. Supplied by the caller — this module never calls `Date.now()`. */\n addedAt?: number;\n};\n\nexport type FlowConnectionBinding = {\n /** Toolkit slug, e.g. `'xero'`. Also the map key — one entry per toolkit. */\n toolkit: string;\n connectedAccountId: string;\n /** Entity the connection belongs to — guards template-copy across workspaces. */\n entityDid: string;\n /** Xero organisation (tenant). */\n tenantId?: string;\n /** Xero chart-of-accounts UUID for the bank/treasury account. */\n bankAccountId?: string;\n /** Epoch ms. Supplied by the caller — this module never calls `Date.now()`. */\n boundAt?: number;\n boundByDid?: string;\n};\n\n/**\n * Read the connections a flow requires.\n *\n * Normalizes defensively rather than trusting the map: this is read against a\n * live, replicated doc, so an entry can be observed mid-sync, written by an older\n * client, or malformed outright. Anything that is not a `Y.Map` carrying a\n * non-empty `toolkit` is skipped, and a read never throws.\n *\n * Order is stable across peers — `addedAt` ascending with unstamped entries last,\n * tie-broken by `toolkit` — so a rendered list does not reshuffle on every sync.\n */\nexport function readFlowConnections(yDoc: YDoc): FlowConnection[] {\n const connections: FlowConnection[] = [];\n getConnectionsMap(yDoc).forEach((value) => {\n const connection = toConnection(value);\n if (connection) connections.push(connection);\n });\n\n return connections.sort((a, b) => {\n const aAt = a.addedAt ?? Number.POSITIVE_INFINITY;\n const bAt = b.addedAt ?? Number.POSITIVE_INFINITY;\n if (aAt !== bAt) return aAt < bAt ? -1 : 1;\n return compareKeys(a.toolkit, b.toolkit);\n });\n}\n\n/**\n * Add a connection, or merge into the existing entry for the same `toolkit`.\n *\n * `addedAt` is write-once: an existing stamp is preserved so a later edit (a\n * label refresh, a requirement change) cannot reorder the list. `requires` is\n * part of the connection's identity as a requirement and is always written —\n * pass the full list. `optional` and the optional string fields are merged —\n * omit one to leave it as it is, pass `''` (or `false`) to clear it.\n */\nexport function upsertFlowConnection(yDoc: YDoc, connection: FlowConnection): void {\n const toolkit = connection.toolkit;\n if (typeof toolkit !== 'string' || toolkit.length === 0) return;\n\n yDoc.transact(() => {\n const entry = ensureEntry(getConnectionsMap(yDoc), toolkit);\n entry.set('toolkit', toolkit);\n entry.set('requires', toRequirementKeys(connection.requires));\n mergeOptionalString(entry, 'label', connection.label);\n mergeOptionalFlag(entry, 'optional', connection.optional);\n mergeTriStateFlag(entry, 'agent', connection.agent);\n\n const addedAt = toTimestamp(entry.get('addedAt')) ?? toTimestamp(connection.addedAt);\n if (addedAt !== undefined) entry.set('addedAt', addedAt);\n });\n}\n\n/** Remove a connection. No-op when the flow has no entry for `toolkit`. */\nexport function removeFlowConnection(yDoc: YDoc, toolkit: string): void {\n yDoc.transact(() => {\n const map = getConnectionsMap(yDoc);\n if (map.has(toolkit)) map.delete(toolkit);\n });\n}\n\n/**\n * Mark an existing connection optional or required. No-op when the flow has no\n * entry for `toolkit` — a flag alone carries no identity, so creating an entry\n * from one would invent a requirement nobody declared.\n */\nexport function setFlowConnectionOptional(yDoc: YDoc, toolkit: string, optional: boolean): void {\n yDoc.transact(() => {\n const entry = getConnectionsMap(yDoc).get(toolkit);\n if (isYMapLike<unknown>(entry)) mergeOptionalFlag(entry, 'optional', optional);\n });\n}\n\n/**\n * Record whether the flow's automated agent acts through this connection. No-op\n * when the flow has no entry for `toolkit`, for the same reason as\n * {@link setFlowConnectionOptional}.\n *\n * `false` is written, not erased: \"the agent does not use this\" is an answer\n * the author gave, and erasing it would hand the question back to the\n * step-based inference the author was overriding.\n */\nexport function setFlowConnectionAgent(yDoc: YDoc, toolkit: string, agent: boolean): void {\n yDoc.transact(() => {\n const entry = getConnectionsMap(yDoc).get(toolkit);\n if (isYMapLike<unknown>(entry)) mergeTriStateFlag(entry, 'agent', agent);\n });\n}\n\n/**\n * Replace an existing connection's sub-selection requirements. No-op when the\n * flow has no entry for `toolkit`, for the same reason as\n * {@link setFlowConnectionOptional}.\n */\nexport function setFlowConnectionRequires(yDoc: YDoc, toolkit: string, requires: FlowConnectionRequirementKey[]): void {\n yDoc.transact(() => {\n const entry = getConnectionsMap(yDoc).get(toolkit);\n if (isYMapLike<unknown>(entry)) entry.set('requires', toRequirementKeys(requires));\n });\n}\n\n/**\n * Read the concrete connection bindings for this flow.\n *\n * Normalized as defensively as {@link readFlowConnections}: an entry is skipped\n * unless it carries the three fields that make a binding usable — `toolkit`,\n * `connectedAccountId` and `entityDid`. A half-written binding is not a binding\n * to a different account, it is no binding at all.\n *\n * Order is stable across peers — `boundAt` ascending with unstamped entries last,\n * tie-broken by `toolkit`.\n */\nexport function readFlowConnectionBindings(yDoc: YDoc): FlowConnectionBinding[] {\n const bindings: FlowConnectionBinding[] = [];\n getBindingsMap(yDoc).forEach((value) => {\n const binding = toBinding(value);\n if (binding) bindings.push(binding);\n });\n\n return bindings.sort((a, b) => {\n const aAt = a.boundAt ?? Number.POSITIVE_INFINITY;\n const bAt = b.boundAt ?? Number.POSITIVE_INFINITY;\n if (aAt !== bAt) return aAt < bAt ? -1 : 1;\n return compareKeys(a.toolkit, b.toolkit);\n });\n}\n\n/**\n * Bind a toolkit to a connected account, or merge into the existing binding for\n * the same `toolkit`.\n *\n * `boundAt` is write-once, so re-picking an organisation does not reorder the\n * list. Optional string fields are merged — omit one to leave it as it is, pass\n * `''` to clear it. Ignored unless `toolkit`, `connectedAccountId` and\n * `entityDid` are all present: those three are what a binding *is*.\n */\nexport function upsertFlowConnectionBinding(yDoc: YDoc, binding: FlowConnectionBinding): void {\n const toolkit = toNonEmptyString(binding.toolkit);\n const connectedAccountId = toNonEmptyString(binding.connectedAccountId);\n const entityDid = toNonEmptyString(binding.entityDid);\n if (toolkit === undefined || connectedAccountId === undefined || entityDid === undefined) return;\n\n yDoc.transact(() => {\n const entry = ensureEntry(getBindingsMap(yDoc), toolkit);\n entry.set('toolkit', toolkit);\n entry.set('connectedAccountId', connectedAccountId);\n entry.set('entityDid', entityDid);\n mergeOptionalString(entry, 'tenantId', binding.tenantId);\n mergeOptionalString(entry, 'bankAccountId', binding.bankAccountId);\n mergeOptionalString(entry, 'boundByDid', binding.boundByDid);\n\n const boundAt = toTimestamp(entry.get('boundAt')) ?? toTimestamp(binding.boundAt);\n if (boundAt !== undefined) entry.set('boundAt', boundAt);\n });\n}\n\n/** Remove a binding. No-op when the flow has no binding for `toolkit`. */\nexport function removeFlowConnectionBinding(yDoc: YDoc, toolkit: string): void {\n yDoc.transact(() => {\n const map = getBindingsMap(yDoc);\n if (map.has(toolkit)) map.delete(toolkit);\n });\n}\n\n// ─── Internal helpers ──────────────────────────────────────────────────────────\n\nfunction getConnectionsMap(yDoc: YDoc): YMap<unknown> {\n return yDoc.getMap<unknown>(FLOW_CONNECTIONS_MAP_KEY);\n}\n\nfunction getBindingsMap(yDoc: YDoc): YMap<unknown> {\n return yDoc.getMap<unknown>(FLOW_CONNECTION_BINDINGS_MAP_KEY);\n}\n\n/** The entry for `toolkit`, replacing any malformed (non-`Y.Map`) value in place. */\nfunction ensureEntry(map: YMap<unknown>, toolkit: string): YMap<unknown> {\n const existing = map.get(toolkit);\n if (isYMapLike<unknown>(existing)) return existing;\n const created = new Y.Map<unknown>();\n map.set(toolkit, created);\n return created;\n}\n\nfunction toConnection(value: unknown): FlowConnection | undefined {\n if (!isYMapLike<unknown>(value)) return undefined;\n\n const toolkit = value.get('toolkit');\n if (typeof toolkit !== 'string' || toolkit.length === 0) return undefined;\n\n const connection: FlowConnection = { toolkit, requires: toRequirementKeys(value.get('requires')) };\n\n const label = toNonEmptyString(value.get('label'));\n if (label !== undefined) connection.label = label;\n\n if (value.get('optional') === true) connection.optional = true;\n\n // Only a real boolean is an answer. Anything else — absent, a string, a\n // half-synced value — leaves the field undefined so the caller falls back to\n // inferring the agent's use from the flow's steps.\n const agent = value.get('agent');\n if (typeof agent === 'boolean') connection.agent = agent;\n\n const addedAt = toTimestamp(value.get('addedAt'));\n if (addedAt !== undefined) connection.addedAt = addedAt;\n\n return connection;\n}\n\nfunction toBinding(value: unknown): FlowConnectionBinding | undefined {\n if (!isYMapLike<unknown>(value)) return undefined;\n\n const toolkit = toNonEmptyString(value.get('toolkit'));\n const connectedAccountId = toNonEmptyString(value.get('connectedAccountId'));\n const entityDid = toNonEmptyString(value.get('entityDid'));\n if (toolkit === undefined || connectedAccountId === undefined || entityDid === undefined) return undefined;\n\n const binding: FlowConnectionBinding = { toolkit, connectedAccountId, entityDid };\n\n const tenantId = toNonEmptyString(value.get('tenantId'));\n if (tenantId !== undefined) binding.tenantId = tenantId;\n\n const bankAccountId = toNonEmptyString(value.get('bankAccountId'));\n if (bankAccountId !== undefined) binding.bankAccountId = bankAccountId;\n\n const boundAt = toTimestamp(value.get('boundAt'));\n if (boundAt !== undefined) binding.boundAt = boundAt;\n\n const boundByDid = toNonEmptyString(value.get('boundByDid'));\n if (boundByDid !== undefined) binding.boundByDid = boundByDid;\n\n return binding;\n}\n\n/**\n * Keeps only the requirement keys this version understands, de-duplicated, in\n * the caller's order. An unknown key from a newer client is dropped rather than\n * carried through: a requirement nobody can satisfy would block the flow\n * forever.\n */\nfunction toRequirementKeys(value: unknown): FlowConnectionRequirementKey[] {\n if (!Array.isArray(value)) return [];\n const keys: FlowConnectionRequirementKey[] = [];\n for (const entry of value) {\n if (!isRequirementKey(entry)) continue;\n if (!keys.includes(entry)) keys.push(entry);\n }\n return keys;\n}\n\nfunction isRequirementKey(value: unknown): value is FlowConnectionRequirementKey {\n return typeof value === 'string' && (REQUIREMENT_KEYS as readonly string[]).includes(value);\n}\n\nfunction toTimestamp(value: unknown): number | undefined {\n const numeric = typeof value === 'string' ? Number(value) : value;\n return typeof numeric === 'number' && Number.isFinite(numeric) ? Math.trunc(numeric) : undefined;\n}\n\nfunction toNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction mergeOptionalString(entry: YMap<unknown>, key: string, value: string | undefined): void {\n if (value === undefined) return;\n if (value.length === 0) entry.delete(key);\n else entry.set(key, value);\n}\n\n/** `false` is the default, so it is stored as absence rather than as `false`. */\nfunction mergeOptionalFlag(entry: YMap<unknown>, key: string, value: boolean | undefined): void {\n if (value === undefined) return;\n if (value) entry.set(key, true);\n else entry.delete(key);\n}\n\n/**\n * Like {@link mergeOptionalFlag}, but `false` is stored rather than erased —\n * for a field where \"no\" and \"not answered\" mean different things.\n */\nfunction mergeTriStateFlag(entry: YMap<unknown>, key: string, value: boolean | undefined): void {\n if (value === undefined) return;\n entry.set(key, value);\n}\n\nfunction compareKeys(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n","import type { Doc as YDoc } from 'yjs';\n\nimport { readFlowConnectionBindings, type FlowConnectionBinding } from '@/core/lib/flowCompiler/connections';\n\nexport const XERO_TOOLKIT = 'xero';\n\n/**\n * The Xero account, organisation and bank account this flow acts through.\n *\n * Flow-level, not block-level: the binding is chosen once in the flow's\n * Connections and is a prerequisite of starting a session, so by the time any\n * action runs it is already there. Blocks therefore no longer carry their own\n * connection or bank-account pin — two payment blocks in one flow debiting two\n * different accounts was never a real case, and a per-block pin could disagree\n * with the account the actors were actually granted.\n *\n * Reads defensively and never throws: the doc is live and replicated, so this\n * can be called mid-sync.\n */\nexport function readFlowXeroBinding(yDoc?: YDoc | null): FlowConnectionBinding | undefined {\n if (!yDoc) return undefined;\n try {\n return readFlowConnectionBindings(yDoc).find((binding) => binding.toolkit === XERO_TOOLKIT);\n } catch {\n return undefined;\n }\n}\n\n/** Same, from an editor (or anything carrying `_yDoc`). */\nexport function readFlowXeroBindingFromEditor(editor: { _yDoc?: YDoc } | null | undefined): FlowConnectionBinding | undefined {\n return readFlowXeroBinding(editor?._yDoc);\n}\n","export const numberFormatter = (num: number, digits: number) => {\n const lookup = [\n { value: 1, symbol: '' },\n { value: 1e3, symbol: 'k' },\n { value: 1e6, symbol: 'M' },\n { value: 1e9, symbol: 'G' },\n { value: 1e12, symbol: 'T' },\n { value: 1e15, symbol: 'P' },\n { value: 1e18, symbol: 'E' },\n ];\n const rx = /\\.0+$|(\\.[0-9]*[1-9])0+$/;\n const item = lookup\n .slice()\n .reverse()\n .find((lookupItem) => num >= lookupItem.value);\n return item ? (num / item.value).toFixed(digits).replace(rx, '$1') + item.symbol : '0';\n};\n\nexport const microAmountToAmount = (microAmount: number, microUnits: number = 6) => {\n const amount = (microAmount ?? 0) / Math.pow(10, microUnits);\n return amount;\n};\n\nexport function renderNumber(value: number | undefined): string {\n if (value === 0) return '0';\n if (!value) return '';\n\n const formattedValue = value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 6 });\n\n return formattedValue;\n}\n\nexport interface AssetDenomUnit {\n denom: string;\n exponent: number;\n aliases: string[];\n}\n\nexport interface AssetPair {\n display: string;\n base: string;\n denomUnits: AssetDenomUnit[];\n}\n\n/**\n * Format a Coin for display without an assets list. Maps the well-known\n * IXO/USDC denoms to friendly labels and divides by 10^6 when the amount\n * is in micro-units. Falls back to `${amount} ${denom}` for unknown denoms.\n */\nexport const formatCoin = (coin: { denom: string; amount: string | number }): string => {\n const USDC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\n const DECIMALS = 6;\n const denom = coin.denom === USDC_DENOM ? 'USDC' : coin.denom === 'uixo' ? 'IXO' : coin.denom;\n const raw = Number(coin.amount);\n const display = raw >= Math.pow(10, DECIMALS) ? raw / Math.pow(10, DECIMALS) : raw;\n return `${display} ${denom}`;\n};\n\nexport const formatCoinAmount = (coin: { denom: string; amount: string }, assetsList: AssetPair[]): string => {\n const pair = assetsList.find((item) => item.display === coin.denom || item.base === coin.denom);\n\n if (!pair) {\n return `${coin.amount} ${coin.denom}`;\n }\n\n const exponent = pair.denomUnits.find((u) => u.denom === pair.display)?.exponent ?? 0;\n const amount = Number(coin.amount) / Math.pow(10, exponent);\n const displayDenom = pair.display.toUpperCase();\n\n return `${amount.toLocaleString(undefined, { maximumFractionDigits: 6 })} ${displayDenom}`;\n};\n","import type { DiffResolver, ActionNarrativeProps } from './diffTypes';\nimport { resolveActionType } from './registry';\n\nexport interface DiffResolverRegistration {\n resolver: DiffResolver;\n NarrativeComponent?: React.ComponentType<ActionNarrativeProps>;\n}\n\nconst diffResolvers = new Map<string, DiffResolverRegistration>();\n\nexport function registerDiffResolver(actionType: string, reg: DiffResolverRegistration): void {\n diffResolvers.set(resolveActionType(actionType), reg);\n}\n\nexport function getDiffResolver(actionType: string): DiffResolverRegistration | undefined {\n return diffResolvers.get(resolveActionType(actionType));\n}\n\nexport function hasDiffResolver(actionType: string): boolean {\n return diffResolvers.has(resolveActionType(actionType));\n}\n","import { registerAction, doneWhenCompleted } from '../../registry';\n\n/**\n * @description AI-assisted intent capture that queries the Domain Indexer for matching\n * Blueprint candidates. Returns a ranked list of blueprint DIDs with metadata.\n * @flowStep 1 — Define Purpose\n * @paramsSchema { agentMessage: string, userMessage: string }\n */\nregisterAction({\n type: 'qi/pod.domain-indexer-lookup',\n can: 'pod/domain-indexer-lookup',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n userMessage: { type: 'string', description: 'The user-provided purpose text used to query the Domain Indexer.' },\n purposeDescription: { type: 'string', description: 'Fallback purpose text used when userMessage is absent.' },\n },\n },\n\n outputSchema: [\n { path: 'purposeDescription', displayName: 'Purpose Description', type: 'string', description: 'The user-provided purpose text' },\n { path: 'blueprintCandidates', displayName: 'Blueprint Candidates', type: 'array', description: 'Ranked array of matching blueprint DIDs and metadata' },\n ],\n\n // Mirrors run(): either userMessage or purposeDescription satisfies the\n // purpose-text requirement, reported under the primary name.\n getMissingInputs: (inputs) => (String(inputs.userMessage || inputs.purposeDescription || '').trim() ? [] : ['userMessage']),\n\n run: async (inputs) => {\n const purposeDescription = String(inputs.userMessage || inputs.purposeDescription || '').trim();\n if (!purposeDescription) throw new Error('userMessage is required');\n\n // Stub: return placeholder until real Domain Indexer is wired\n return {\n output: {\n purposeDescription,\n blueprintCandidates: [],\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { extractDid } from '@/core/lib/did';\n\n/**\n * @description Single-select a Blueprint (protocol entity) from a filtered list.\n * The selected blueprint DID is carried forward to all subsequent POD setup steps.\n * @flowStep 2 — Select Blueprint\n * @paramsSchema { filter: string }\n */\nregisterAction({\n type: 'qi/pod.domain-single-selection',\n can: 'pod/domain-single-selection',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['selectedBlueprintDid'],\n properties: {\n selectedBlueprintDid: { type: 'string', description: 'DID of the blueprint to select.' },\n selectedBlueprintName: { type: 'string', description: 'Display name of the selected blueprint.' },\n selectedBlueprintDescription: { type: 'string', description: 'Description of the selected blueprint.' },\n },\n },\n\n outputSchema: [\n { path: 'selectedBlueprintDid', displayName: 'Selected Blueprint DID', type: 'string', description: 'DID of the selected blueprint' },\n { path: 'selectedBlueprintName', displayName: 'Selected Blueprint Name', type: 'string', description: 'Display name of the selected blueprint' },\n { path: 'selectedBlueprintDescription', displayName: 'Selected Blueprint Description', type: 'string', description: 'Description of the selected blueprint' },\n { path: 'context', displayName: 'Entity Context', type: 'array', description: 'Entity context entries derived from the selected blueprint' },\n ],\n\n events: [\n {\n name: 'selected',\n displayName: 'Blueprint Selected',\n description: 'Fires when a blueprint is selected for the POD.',\n payloadSchema: [\n { path: 'selectedBlueprintDid', displayName: 'Selected Blueprint DID', type: 'string', description: 'DID of the selected blueprint' },\n { path: 'selectedBlueprintName', displayName: 'Selected Blueprint Name', type: 'string', description: 'Display name of the selected blueprint' },\n { path: 'selectedBlueprintDescription', displayName: 'Selected Blueprint Description', type: 'string', description: 'Description of the selected blueprint' },\n { path: 'context', displayName: 'Entity Context', type: 'array', description: 'Entity context entries for createDomain, including class = selected blueprint DID' },\n ],\n pendingDisplayFields: ['selectedBlueprintName', 'selectedBlueprintDid'],\n },\n ],\n\n run: async (inputs) => {\n const selectedBlueprintDid = extractDid(inputs.selectedBlueprintDid);\n if (!selectedBlueprintDid) throw new Error('selectedBlueprintDid is required');\n const selectedBlueprintName = String(inputs.selectedBlueprintName || '').trim();\n const selectedBlueprintDescription = String(inputs.selectedBlueprintDescription || '').trim();\n const context = [{ key: 'class', val: selectedBlueprintDid }];\n const output = {\n selectedBlueprintDid,\n selectedBlueprintName,\n selectedBlueprintDescription,\n context,\n };\n\n return {\n output,\n events: [{ name: 'selected', payload: output }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { isBlankInputValue } from '../../inputRequirements';\n\n/**\n * @description Lists IXO entities where the current user holds a specified role (e.g. controller).\n * Optional step — the user may skip to leave parentDID as null.\n * @flowStep 3A — Parent Organisation (optional)\n * @paramsSchema { did: string, role: string }\n */\nregisterAction({\n type: 'qi/pod.entity-single-selection',\n can: 'pod/entity-single-selection',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n skipped: { type: 'boolean', description: 'True to skip selecting a parent entity, leaving parentDID null.' },\n selectedEntityDid: { type: 'string', description: 'DID of the selected parent entity; required when not skipping.' },\n selectedEntityName: { type: 'string', description: 'Display name of the selected parent entity.' },\n selectedEntityType: { type: 'string', description: 'Entity type of the selected parent entity.' },\n },\n },\n\n outputSchema: [\n { path: 'selectedEntityDid', displayName: 'Selected Entity DID', type: 'string', description: 'DID of the selected parent entity, or null if skipped' },\n { path: 'selectedEntityName', displayName: 'Selected Entity Name', type: 'string', description: 'Display name of the selected parent entity' },\n { path: 'selectedEntityType', displayName: 'Selected Entity Type', type: 'string', description: 'Entity type of the selected parent entity' },\n { path: 'skipped', displayName: 'Skipped', type: 'boolean', description: 'True if the user skipped this step' },\n ],\n\n events: [\n {\n name: 'selected',\n displayName: 'Entity Selected',\n description: 'Fires when a parent DAO or POD is selected.',\n payloadSchema: [\n { path: 'selectedEntityDid', displayName: 'Selected Entity DID', type: 'string', description: 'DID of the selected parent entity' },\n { path: 'selectedEntityName', displayName: 'Selected Entity Name', type: 'string', description: 'Display name of the selected parent entity' },\n { path: 'selectedEntityType', displayName: 'Selected Entity Type', type: 'string', description: 'Entity type of the selected parent entity' },\n { path: 'skipped', displayName: 'Skipped', type: 'boolean', description: 'False when a parent entity was selected' },\n ],\n pendingDisplayFields: ['selectedEntityName', 'selectedEntityDid'],\n },\n ],\n\n // Mirrors run(): a truthy `skipped` waives the selection entirely.\n getMissingInputs: (inputs) => (inputs.skipped ? [] : isBlankInputValue(inputs.selectedEntityDid) ? ['selectedEntityDid'] : []),\n\n run: async (inputs) => {\n const skipped = !!inputs.skipped;\n if (skipped) {\n const output = { selectedEntityDid: null, selectedEntityName: '', selectedEntityType: '', skipped: true };\n return { output, events: [] };\n }\n\n const selectedEntityDid = String(inputs.selectedEntityDid || '').trim();\n if (!selectedEntityDid) throw new Error('selectedEntityDid is required when not skipping');\n\n const selectedEntityType = String(inputs.selectedEntityType || '').trim();\n const output = {\n selectedEntityDid,\n selectedEntityName: String(inputs.selectedEntityName || '').trim(),\n selectedEntityType,\n skipped: false,\n };\n\n return {\n output,\n events: [{ name: 'selected', payload: output }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { isBlankInputValue } from '../../inputRequirements';\n\ntype GroupType = 'categorical' | 'multisig' | 'nftStaking' | 'tokenStaking';\n\n/**\n * @description Configure POD membership. Behaviour depends on the governance group type\n * selected in the previous step:\n * - categorical: members with role + votingPower (weight-based)\n * - multisig: signatories + absolute threshold count (no voting power)\n * - nftStaking: NFT contract address (no explicit member list)\n * - tokenStaking: token config — existing address or new token params (no explicit member list)\n *\n * @flowStep 5 — Membership\n * @inputsFrom orchestrator: { groupType: 'categorical' | 'multisig' | 'nftStaking' | 'tokenStaking' }\n */\nregisterAction({\n type: 'qi/pod.member-multi-select',\n can: 'pod/member-multi-select',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n groupType: { type: 'string', description: 'Governance group type that determines which member fields apply; defaults to categorical.' },\n members: { type: 'array', description: 'Array of { did, role, votingPower } members; required for categorical and multisig groups.' },\n multisigThreshold: { type: 'number', description: 'Minimum number of signers required; used for multisig groups.' },\n nftContractAddress: { type: 'string', description: 'NFT staking contract address; required for nftStaking groups.' },\n tokenConfig: { type: 'object', description: 'Token configuration; required for tokenStaking groups.' },\n },\n },\n\n outputSchema: [\n { path: 'members', displayName: 'Members', type: 'array', description: 'Array of { did, role, votingPower } — categorical/multisig only' },\n { path: 'multisigThreshold', displayName: 'Multisig Threshold', type: 'number', description: 'Minimum signers required — multisig only' },\n { path: 'nftContractAddress', displayName: 'NFT Contract Address', type: 'string', description: 'NFT staking contract address — nftStaking only' },\n { path: 'tokenConfig', displayName: 'Token Config', type: 'object', description: 'Token configuration — tokenStaking only' },\n ],\n\n events: [\n {\n name: 'configured',\n displayName: 'Members Configured',\n description: 'Fires when membership configuration is complete.',\n payloadSchema: [\n {\n path: 'memberConfig',\n displayName: 'Member Config',\n type: 'object',\n description: 'Full member configuration (members, multisigThreshold, nftContractAddress, or tokenConfig depending on group type)',\n },\n ],\n pendingDisplayFields: ['memberConfig.memberCount'],\n },\n ],\n\n // Mirrors run(), including its default: an absent groupType is treated as\n // 'categorical', not as a missing input.\n getMissingInputs: (inputs) => {\n const groupType = String(inputs.groupType || '').trim() || 'categorical';\n\n if (groupType === 'nftStaking') {\n return String(inputs.nftContractAddress || '').trim() ? [] : ['nftContractAddress'];\n }\n\n if (groupType === 'tokenStaking') {\n const tokenConfig = inputs.tokenConfig as Record<string, unknown> | undefined;\n if (!tokenConfig || typeof tokenConfig !== 'object') return ['tokenConfig'];\n if (tokenConfig.isExistingToken) {\n return String(tokenConfig.tokenAddress || '').trim() ? [] : ['tokenConfig.tokenAddress'];\n }\n const missing: string[] = [];\n if (!String(tokenConfig.tokenName || '').trim()) missing.push('tokenConfig.tokenName');\n if (!String(tokenConfig.tokenSymbol || '').trim()) missing.push('tokenConfig.tokenSymbol');\n if (isBlankInputValue(tokenConfig.tokenSupply)) missing.push('tokenConfig.tokenSupply');\n return missing;\n }\n\n // categorical and multisig both require a member list\n const missing: string[] = [];\n if (!Array.isArray(inputs.members) || inputs.members.length === 0) missing.push('members');\n if (groupType === 'multisig' && isBlankInputValue(inputs.multisigThreshold)) missing.push('multisigThreshold');\n return missing;\n },\n\n run: async (inputs) => {\n const groupType: GroupType = (inputs.groupType as GroupType) || 'categorical';\n\n if (groupType === 'nftStaking') {\n const addr = String(inputs.nftContractAddress || '').trim();\n if (!addr) throw new Error('NFT contract address is required for nftStaking groups');\n return {\n output: { nftContractAddress: addr },\n events: [{ name: 'configured', payload: { memberConfig: { nftContractAddress: addr, memberCount: 0 } } }],\n };\n }\n\n if (groupType === 'tokenStaking') {\n const tokenConfig = inputs.tokenConfig as Record<string, any>;\n if (!tokenConfig) throw new Error('tokenConfig is required for tokenStaking groups');\n if (tokenConfig.isExistingToken) {\n if (!String(tokenConfig.tokenAddress || '').trim()) throw new Error('Token contract address is required');\n } else {\n if (!String(tokenConfig.tokenName || '').trim()) throw new Error('Token name is required');\n if (!String(tokenConfig.tokenSymbol || '').trim()) throw new Error('Token symbol is required');\n const supply = Number(tokenConfig.tokenSupply);\n if (isNaN(supply) || supply <= 0) throw new Error('Token supply must be a positive number');\n }\n return {\n output: { tokenConfig },\n events: [{ name: 'configured', payload: { memberConfig: { tokenConfig, memberCount: 0 } } }],\n };\n }\n\n // categorical and multisig both require a member list\n const members = Array.isArray(inputs.members) ? inputs.members : [];\n if (members.length === 0) throw new Error('At least one member is required');\n\n const dids = members.map((m: any) => String(m.did || ''));\n const uniqueDids = new Set(dids);\n if (uniqueDids.size !== dids.length) throw new Error('Duplicate member DIDs are not allowed');\n\n if (groupType === 'multisig') {\n const threshold = Number(inputs.multisigThreshold);\n if (!Number.isInteger(threshold) || threshold < 1) throw new Error('Multisig threshold must be a positive integer');\n if (threshold > members.length) throw new Error(`Threshold (${threshold}) cannot exceed member count (${members.length})`);\n return {\n output: { members, multisigThreshold: threshold },\n events: [{ name: 'configured', payload: { memberConfig: { members, multisigThreshold: threshold, memberCount: members.length } } }],\n };\n }\n\n // categorical\n const hasAdmin = members.some((m: any) => String(m.role || '').toLowerCase() === 'admin');\n if (!hasAdmin) throw new Error('At least one member must have the Admin role');\n\n for (const m of members) {\n const vp = Number(m.votingPower);\n if (!Number.isInteger(vp) || vp <= 0) throw new Error(`Voting power must be a positive integer (got ${m.votingPower} for ${m.did})`);\n }\n\n return {\n output: { members },\n events: [{ name: 'configured', payload: { memberConfig: { members, memberCount: members.length } } }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\n\ntype GroupType = 'categorical' | 'multisig' | 'nftStaking' | 'tokenStaking';\n\nconst VALID_GROUP_TYPES: GroupType[] = ['categorical', 'multisig', 'nftStaking', 'tokenStaking'];\n\n/**\n * @description Configure the governance group type and Cosmos group DecisionPolicy.\n * The groupType determines which validation rules apply and what member\n * configuration is collected in the next step.\n *\n * @flowStep 4 — Governance\n */\nregisterAction({\n type: 'qi/pod.governance-config',\n can: 'pod/governance-config',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['groupName', 'groupType', 'governance'],\n properties: {\n groupName: { type: 'string', description: 'Human-readable name for the governance group.' },\n groupType: { type: 'string', description: 'Governance group type: categorical, multisig, nftStaking, or tokenStaking.' },\n governance: { type: 'object', description: 'Cosmos group decision policy parameters; must include votingPeriod.' },\n },\n },\n\n outputSchema: [\n { path: 'groupName', displayName: 'Group Name', type: 'string', description: 'Human-readable name for the governance group' },\n { path: 'groupType', displayName: 'Group Type', type: 'string', description: 'Governance group type (categorical | multisig | nftStaking | tokenStaking)' },\n { path: 'governance', displayName: 'Governance Settings', type: 'object', description: 'Cosmos group decision policy parameters' },\n ],\n\n events: [\n {\n name: 'configured',\n displayName: 'Governance Configured',\n description: 'Fires when governance group type and decision policy are configured.',\n payloadSchema: [\n { path: 'governanceConfig.groupName', displayName: 'Group Name', type: 'string' },\n { path: 'governanceConfig.groupType', displayName: 'Group Type', type: 'string' },\n { path: 'governanceConfig.governance', displayName: 'Governance Settings', type: 'object' },\n ],\n pendingDisplayFields: ['governanceConfig.groupName', 'governanceConfig.groupType'],\n },\n ],\n\n // Mirrors run()'s presence preamble: base fields always, then the decision\n // policy fields the selected groupType demands. Value validity (quorum and\n // threshold ranges, veto sum) stays in run().\n getMissingInputs: (inputs) => {\n const missing: string[] = [];\n if (!String(inputs.groupName || '').trim()) missing.push('groupName');\n const groupType = String(inputs.groupType || '').trim();\n if (!groupType) missing.push('groupType');\n\n const governance = inputs.governance as Record<string, unknown> | undefined;\n if (!governance || typeof governance !== 'object') {\n missing.push('governance', 'governance.votingPeriod');\n return missing;\n }\n if (!governance.votingPeriod) missing.push('governance.votingPeriod');\n\n if (!groupType) return missing;\n if (groupType === 'multisig') {\n if (!String(governance.threshold ?? '').trim()) missing.push('governance.threshold');\n } else {\n if (governance.quorum == null || String(governance.quorum).trim() === '') missing.push('governance.quorum');\n if (governance.threshold == null || String(governance.threshold).trim() === '') missing.push('governance.threshold');\n }\n return missing;\n },\n\n run: async (inputs) => {\n const groupName = String(inputs.groupName || '').trim();\n if (!groupName) throw new Error('groupName is required');\n\n const groupType = inputs.groupType as GroupType;\n if (!groupType || !VALID_GROUP_TYPES.includes(groupType)) {\n throw new Error(`groupType must be one of: ${VALID_GROUP_TYPES.join(', ')}`);\n }\n\n const governance = inputs.governance as Record<string, any>;\n if (!governance) throw new Error('governance settings are required');\n if (!governance.votingPeriod) throw new Error('votingPeriod is required');\n\n if (groupType === 'multisig') {\n const raw = String(governance.threshold ?? '').trim();\n const threshold = Number(raw);\n if (!raw || !Number.isFinite(threshold) || !Number.isInteger(threshold) || threshold < 1) {\n throw new Error('multisig threshold must be a positive integer');\n }\n } else {\n const quorum = parseFloat(governance.quorum);\n if (isNaN(quorum) || quorum <= 0 || quorum > 1) throw new Error('quorum must be between 0 and 1 (e.g. 0.33)');\n const threshold = parseFloat(governance.threshold);\n if (isNaN(threshold) || threshold <= 0 || threshold > 1) throw new Error('threshold must be between 0 and 1 (e.g. 0.51)');\n const vetoThreshold = parseFloat(governance.vetoThreshold);\n if (!isNaN(vetoThreshold) && vetoThreshold + threshold > 1) {\n throw new Error('threshold + vetoThreshold cannot exceed 1.0');\n }\n }\n\n return {\n output: { groupName, groupType, governance },\n events: [{ name: 'configured', payload: { governanceConfig: { groupName, groupType, governance } } }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\n\ntype SelectedProtocolTemplate = {\n protocolDid: string;\n protocolName: string;\n sourceRoomId: string;\n sourceLabel: string;\n path?: string;\n};\n\nfunction normalizeSelectedTemplates(value: unknown): SelectedProtocolTemplate[] {\n if (!Array.isArray(value)) return [];\n\n return value\n .map((item) => {\n if (!item || typeof item !== 'object') return null;\n const raw = item as Record<string, unknown>;\n const protocolDid = String(raw.protocolDid || '').trim();\n const sourceRoomId = String(raw.sourceRoomId || '').trim();\n if (!protocolDid || !sourceRoomId) return null;\n\n const sourceLabel = String(raw.sourceLabel || raw.label || sourceRoomId).trim();\n return {\n protocolDid,\n protocolName: String(raw.protocolName || protocolDid).trim(),\n sourceRoomId,\n sourceLabel,\n ...(raw.path ? { path: String(raw.path) } : {}),\n };\n })\n .filter((item): item is SelectedProtocolTemplate => item !== null);\n}\n\n/**\n * @description Lists protocol deeds and their Matrix flow templates.\n * Multi-select across deeds. The selected templates are carried forward so\n * POD creation can import them after the POD entity and flows space exist.\n * @flowStep 3D - Flow Templates\n * @paramsSchema { entity?: string, domainFlowsSubspaceId?: string }\n */\nregisterAction({\n type: 'qi/pod.list-domain-flows',\n can: 'pod/list-domain-flows',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n selectedProtocolTemplates: { type: 'array', description: 'Selected protocol templates, each with protocolDid and sourceRoomId; empty selection is valid.' },\n selectedFlowDids: { type: 'array', description: 'Source Matrix room IDs for selected templates; used as a fallback when no templates are selected.' },\n },\n },\n\n outputSchema: [\n {\n path: 'selectedProtocolTemplates',\n displayName: 'Selected Protocol Templates',\n type: 'array',\n description: 'Selected protocol templates with protocol DID and source room ID',\n },\n { path: 'selectedFlowDids', displayName: 'Selected Flow Room IDs', type: 'array', description: 'Source Matrix room IDs for selected templates' },\n { path: 'flowTemplateConfig', displayName: 'Flow Template Config', type: 'object', description: 'Event payload consumed by POD signing/import steps' },\n ],\n\n events: [\n {\n name: 'selected',\n displayName: 'Flow Templates Selected',\n description: 'Fires when the flow template selection is confirmed, including an empty selection.',\n payloadSchema: [\n {\n path: 'flowTemplateConfig',\n displayName: 'Flow Template Config',\n type: 'object',\n description: 'Selected templates grouped by their protocol DID for later import',\n },\n {\n path: 'selectedProtocolTemplates',\n displayName: 'Selected Protocol Templates',\n type: 'array',\n description: 'Selected protocol templates with protocol DID and source room ID',\n },\n {\n path: 'selectedFlowDids',\n displayName: 'Selected Flow Room IDs',\n type: 'array',\n description: 'Source Matrix room IDs for selected templates',\n },\n ],\n pendingDisplayFields: ['flowTemplateConfig.templateCount', 'flowTemplateConfig.protocolCount'],\n },\n ],\n\n run: async (inputs) => {\n // Zero templates selected is valid. It means \"create the POD without imported flow templates\".\n const selectedProtocolTemplates = normalizeSelectedTemplates(inputs.selectedProtocolTemplates);\n const selectedFlowDids =\n selectedProtocolTemplates.length > 0\n ? selectedProtocolTemplates.map((template) => template.sourceRoomId)\n : Array.isArray(inputs.selectedFlowDids)\n ? inputs.selectedFlowDids\n : [];\n\n const protocolCount = new Set(selectedProtocolTemplates.map((template) => template.protocolDid)).size;\n const flowTemplateConfig = {\n selectedTemplates: selectedProtocolTemplates,\n templateCount: selectedProtocolTemplates.length,\n protocolCount,\n };\n\n return {\n output: { selectedProtocolTemplates, selectedFlowDids, flowTemplateConfig },\n events: [\n {\n name: 'selected',\n payload: {\n flowTemplateConfig,\n selectedProtocolTemplates,\n selectedFlowDids,\n },\n },\n ],\n };\n },\n});\n","import {\n DESIGN_POD_CONTROL_IDS,\n DESIGN_POD_METHODS,\n DESIGN_POD_PHASE_IDS,\n DESIGN_POD_STATE_MAP_KEY,\n commitDesignPodPhase,\n compileDesignPodRelease,\n computeDesignPodRevisionSetDigest,\n canonicalDesignPodJson,\n createDesignPodArtifactReceipt,\n digestDesignPodValue,\n markDesignPodReviewed,\n readDesignPodDefinition,\n readDesignPodState,\n sameDesignPodActor,\n updateDesignPodControl,\n type DesignPodControlId,\n type DesignPodActionProofV1,\n type DesignPodChecklistRecordV1,\n type DesignPodFlowStateV1,\n type DesignPodPhaseId,\n type DesignPodProjectIdentityV1,\n type DesignPodReviewRecordV1,\n type DesignPodReviewAssignmentV1,\n type DesignPodReviewRequestV1,\n type DesignPodRuntimeAuthorityV1,\n} from '../../designPod';\nimport { isRunTerminalOrPending, TerminalRunExecutionError } from '../../flowEngine/runs';\nimport { createRunEventIdempotencyKey } from '../../flowEngine/runTimeline';\nimport type { StoredInvocation } from '../../../types/ucan';\nimport { doneWhenCompleted, registerAction } from '../registry';\nimport type { ActionContext, ActionProofDeclaration, ActionResult, OutputSchemaField } from '../types';\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${name} is required`);\n return value.trim();\n}\n\nfunction requiredRecord(value: unknown, name: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${name} must be an object`);\n return value as Record<string, unknown>;\n}\n\nfunction requireDoc(ctx: ActionContext) {\n if (!ctx.yDoc) throw new Error('Design POD actions require the active Flow Y.Doc');\n return ctx.yDoc;\n}\n\nfunction requireExecutionProof(ctx: ActionContext): DesignPodActionProofV1 {\n const proof = ctx.executionProof;\n if (!proof?.invocationCid || !proof.inputDigest) {\n throw new Error('This governed Design POD action requires an identity-bound Flow invocation');\n }\n return {\n invocationCid: proof.invocationCid,\n actionBlockId: ctx.nodeId,\n inputDigest: proof.inputDigest,\n };\n}\n\nconst sameActorDid = sameDesignPodActor;\n\nfunction assertFlowAuthority(doc: NonNullable<ActionContext['yDoc']>, authority: DesignPodRuntimeAuthorityV1): void {\n const root = doc.getMap('root');\n if (root.get('doc_id') !== authority.flowRoomId || root.get('flowOwnerDid') !== authority.flowOwnerDid) {\n throw new Error('The collaborative Flow authority does not match the Portal-owned Flow owner and Matrix room');\n }\n}\n\nconst DESIGN_POD_PUBLICATION_CLAIM_MESSAGE = 'Design POD IXO publication broadcast claim';\n\ninterface DesignPodPublicationClaim {\n eventId: string;\n originServerTs: number;\n invocationCid: string;\n actorDid: string;\n actionBlockId: string;\n inputDigest: string;\n signedInvocation: string;\n}\n\nfunction publicationClaimFromEvent(\n event: { eventId: string; originServerTs: number; content: unknown },\n expected: {\n designProjectEntityDid: string;\n flowRoomId: string;\n releaseDigest: string;\n packageRoot: string;\n domainCid: string;\n broadcastAttempt: number;\n }\n): DesignPodPublicationClaim | undefined {\n const content = event.content;\n if (!content || typeof content !== 'object' || Array.isArray(content)) return undefined;\n const record = content as Record<string, unknown>;\n if (record.kind !== 'log') return undefined;\n const payload = record.payload;\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return undefined;\n const payloadRecord = payload as Record<string, unknown>;\n if (payloadRecord.message !== DESIGN_POD_PUBLICATION_CLAIM_MESSAGE) return undefined;\n const data = payloadRecord.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const claim = data as Record<string, unknown>;\n if (\n claim.designProjectEntityDid !== expected.designProjectEntityDid ||\n claim.flowRoomId !== expected.flowRoomId ||\n claim.releaseDigest !== expected.releaseDigest ||\n claim.packageRoot !== expected.packageRoot ||\n claim.domainCid !== expected.domainCid ||\n claim.broadcastAttempt !== expected.broadcastAttempt ||\n typeof claim.invocationCid !== 'string' ||\n typeof claim.actorDid !== 'string' ||\n typeof claim.actionBlockId !== 'string' ||\n typeof claim.inputDigest !== 'string' ||\n typeof claim.signedInvocation !== 'string'\n ) {\n return undefined;\n }\n return {\n eventId: event.eventId,\n originServerTs: event.originServerTs,\n invocationCid: claim.invocationCid,\n actorDid: claim.actorDid,\n actionBlockId: claim.actionBlockId,\n inputDigest: claim.inputDigest,\n signedInvocation: claim.signedInvocation,\n };\n}\n\nasync function claimPublicationBroadcast(\n ctx: ActionContext,\n params: {\n authority: DesignPodRuntimeAuthorityV1;\n releaseDigest: string;\n packageRoot: string;\n domainCid: string;\n broadcastAttempt: number;\n verifyInvocation: NonNullable<ActionContext['services']['designPod']>['verifyInvocation'];\n }\n): Promise<DesignPodPublicationClaim> {\n const eventLog = ctx.runEventLog;\n if (!eventLog?.read) throw new Error('Matrix ordered readback is required before an IXO publication broadcast');\n const proof = requireExecutionProof(ctx);\n const signedInvocation = ctx.executionProof?.invocation;\n if (!signedInvocation) throw new Error('The signed publish invocation CAR is required before claiming the IXO broadcast slot');\n const candidate = {\n designProjectEntityDid: params.authority.designProjectEntityDid,\n flowRoomId: params.authority.flowRoomId,\n releaseDigest: params.releaseDigest,\n packageRoot: params.packageRoot,\n domainCid: params.domainCid,\n broadcastAttempt: params.broadcastAttempt,\n invocationCid: proof.invocationCid,\n actorDid: ctx.actorDid,\n actionBlockId: proof.actionBlockId,\n inputDigest: proof.inputDigest,\n signedInvocation,\n };\n await eventLog.append({\n runId: params.authority.sessionRunId,\n blockId: ctx.nodeId,\n kind: 'log',\n payload: { level: 'info', message: DESIGN_POD_PUBLICATION_CLAIM_MESSAGE, data: candidate },\n // The raw digest + CID form exceeds the 128-char idempotency-key ceiling of\n // ixo.flow.run.event — hash the identity the same way run events do.\n idempotencyKey: createRunEventIdempotencyKey('log', 'design-pod.publication', params.releaseDigest, params.broadcastAttempt, proof.invocationCid),\n });\n\n let from: string | undefined;\n const seenTokens = new Set<string>();\n let firstClaim: DesignPodPublicationClaim | undefined;\n do {\n const page = await eventLog.read(params.authority.sessionRunId, { direction: 'forward', limit: 100, ...(from ? { from } : {}) });\n for (const event of page.events) {\n firstClaim = publicationClaimFromEvent(event, {\n designProjectEntityDid: params.authority.designProjectEntityDid,\n flowRoomId: params.authority.flowRoomId,\n releaseDigest: params.releaseDigest,\n packageRoot: params.packageRoot,\n domainCid: params.domainCid,\n broadcastAttempt: params.broadcastAttempt,\n });\n if (firstClaim) break;\n }\n if (firstClaim) break;\n from = page.nextToken;\n if (from && seenTokens.has(from)) throw new Error('Matrix repeated a Design POD publication pagination token');\n if (from) seenTokens.add(from);\n } while (from);\n if (!firstClaim) throw new Error('Matrix did not retain the Design POD publication broadcast claim');\n\n const flowUri = `ixo:flow:${params.authority.flowRoomId}`;\n const state = readDesignPodState(requireDoc(ctx));\n if (!state) throw new Error('Design POD is not initialized');\n const expectedInputDigest = await digestDesignPodValue({\n releaseDigest: params.releaseDigest,\n designProjectEntityDid: params.authority.designProjectEntityDid,\n flowRoomId: params.authority.flowRoomId,\n sessionRunId: params.authority.sessionRunId,\n methodManifestDigest: state.identity.methodManifestDigest,\n });\n if (firstClaim.inputDigest !== expectedInputDigest) {\n throw new Error('The first Matrix publication claim is not bound to the canonical release action input');\n }\n const invocation: StoredInvocation = {\n cid: firstClaim.invocationCid,\n invocation: firstClaim.signedInvocation,\n invokerDid: firstClaim.actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${firstClaim.actionBlockId}` },\n executedAt: firstClaim.originServerTs,\n flowId: params.authority.flowRoomId,\n sessionRunId: params.authority.sessionRunId,\n blockId: firstClaim.actionBlockId,\n result: 'success',\n proofCids: [],\n facts: { actionType: 'qi/blueprint.publish', inputDigest: firstClaim.inputDigest, sessionRunId: params.authority.sessionRunId },\n };\n const verified = await params.verifyInvocation({\n invocation,\n expected: {\n actorDid: firstClaim.actorDid,\n actionType: 'qi/blueprint.publish',\n blockId: firstClaim.actionBlockId,\n inputDigest: firstClaim.inputDigest,\n flowUri,\n flowOwnerDid: params.authority.flowOwnerDid,\n designProjectEntityDid: params.authority.designProjectEntityDid,\n sessionRunId: params.authority.sessionRunId,\n },\n });\n if (!verified.valid) throw new Error(`The first Matrix publication claim failed cryptographic verification${verified.error ? `: ${verified.error}` : ''}`);\n if (firstClaim.invocationCid !== proof.invocationCid) {\n throw new Error('The IXO publication broadcast slot was already claimed by a different signed Flow invocation');\n }\n return firstClaim;\n}\n\nfunction controlId(value: unknown): DesignPodControlId {\n const id = requiredString(value, 'controlId') as DesignPodControlId;\n if (!DESIGN_POD_CONTROL_IDS.includes(id)) throw new Error(`Unknown Design POD control: ${id}`);\n return id;\n}\n\nfunction phaseId(value: unknown): DesignPodPhaseId {\n const id = requiredString(value, 'phase') as DesignPodPhaseId;\n if (!DESIGN_POD_PHASE_IDS.includes(id)) throw new Error(`Unknown Design POD phase: ${id}`);\n return id;\n}\n\nasync function assertIdentity(inputs: Record<string, unknown>, ctx: ActionContext): Promise<void> {\n const doc = requireDoc(ctx);\n const state = readDesignPodState(doc);\n if (!state) throw new Error('This Flow is not an initialized Design POD project');\n const authority = ctx.designPodAuthority;\n if (!authority) throw new Error('Portal-owned Design Project entity, Flow room, and session authority are required');\n if (!ctx.sessionRunId || authority.sessionRunId !== ctx.sessionRunId) throw new Error('The active Flow session is not the Portal-authorized Design POD session');\n assertFlowAuthority(doc, authority);\n const manifest = readDesignPodDefinition(doc);\n const registeredManifest = manifest && DESIGN_POD_METHODS[manifest.methodId];\n if (!manifest || !registeredManifest || canonicalDesignPodJson(manifest) !== canonicalDesignPodJson(registeredManifest)) {\n throw new Error('The active Design POD method does not match the registered Portal method');\n }\n const methodManifestDigest = await digestDesignPodValue(registeredManifest);\n const expected = {\n designProjectEntityDid: authority.designProjectEntityDid,\n flowRoomId: authority.flowRoomId,\n sessionRunId: authority.sessionRunId,\n methodManifestDigest,\n };\n for (const [field, authoritative] of Object.entries(expected)) {\n if (inputs[field] !== authoritative || state.identity[field as keyof typeof state.identity] !== authoritative) {\n throw new Error(`${field} does not match the Portal-authorized Design POD project identity`);\n }\n }\n}\n\nfunction markRecordStale(map: { get(key: string): unknown; set(key: string, value: unknown): unknown }, key: string): void {\n const value = map.get(key);\n if (value && typeof value === 'object' && !Array.isArray(value)) map.set(key, { ...(value as Record<string, unknown>), status: 'stale' });\n}\n\ntype CapturedDesignPodAuthority = DesignPodRuntimeAuthorityV1 & Pick<DesignPodProjectIdentityV1, 'methodManifestDigest'>;\n\nfunction captureDesignPodAuthority(ctx: ActionContext): CapturedDesignPodAuthority {\n const authority = ctx.designPodAuthority;\n if (!authority) throw new Error('Portal-owned Design Project entity, Flow room, and session authority are required');\n const doc = requireDoc(ctx);\n assertFlowAuthority(doc, authority);\n const identity = readDesignPodState(doc)?.identity;\n if (\n !identity ||\n identity.designProjectEntityDid !== authority.designProjectEntityDid ||\n identity.flowRoomId !== authority.flowRoomId ||\n identity.sessionRunId !== authority.sessionRunId\n ) {\n throw new Error('The Portal-authorized Design POD project identity changed while action authority was being captured');\n }\n return { ...authority, methodManifestDigest: identity.methodManifestDigest };\n}\n\nfunction assertAuthorizedSessionOpen(doc: NonNullable<ActionContext['yDoc']>, map: { get(key: string): unknown }, authority: CapturedDesignPodAuthority, operation: string): void {\n assertFlowAuthority(doc, authority);\n const identity = map.get('identity') as Partial<DesignPodProjectIdentityV1> | undefined;\n if (\n !identity ||\n identity.designProjectEntityDid !== authority.designProjectEntityDid ||\n identity.flowRoomId !== authority.flowRoomId ||\n identity.sessionRunId !== authority.sessionRunId ||\n identity.methodManifestDigest !== authority.methodManifestDigest\n ) {\n throw new Error(`The Portal-authorized Design POD project identity changed while ${operation} was being prepared`);\n }\n if (isRunTerminalOrPending(doc, authority.sessionRunId)) {\n throw new TerminalRunExecutionError(authority.sessionRunId, operation);\n }\n}\n\nfunction assertPublicationCanBeInvalidated(\n doc: NonNullable<ActionContext['yDoc']>,\n map: { get(key: string): unknown },\n authority: CapturedDesignPodAuthority,\n operation: string\n): void {\n assertAuthorizedSessionOpen(doc, map, authority, operation);\n const release = map.get('release');\n if (release && typeof release === 'object' && !Array.isArray(release) && (release as Record<string, unknown>).status === 'publishing') {\n throw new Error(`${operation} cannot change Design POD authority while IXO publication is reserved`);\n }\n}\n\ntype PhaseCommitmentSnapshot = Record<DesignPodPhaseId, string>;\n\nfunction capturePhaseCommitments(state: DesignPodFlowStateV1): PhaseCommitmentSnapshot {\n return Object.fromEntries(\n DESIGN_POD_PHASE_IDS.map((phase) => {\n const commitment = state.phaseCommitments[phase];\n if (commitment?.status !== 'current' || !commitment.digest) throw new Error(`A current ${phase} commitment is required`);\n return [phase, canonicalDesignPodJson(commitment)];\n })\n ) as PhaseCommitmentSnapshot;\n}\n\nfunction assertPhaseCommitments(map: { get(key: string): unknown }, snapshot: PhaseCommitmentSnapshot, operation: string): void {\n for (const phase of DESIGN_POD_PHASE_IDS) {\n const commitment = map.get(`commitment:${phase}`) as { status?: string } | undefined;\n if (commitment?.status !== 'current' || canonicalDesignPodJson(commitment) !== snapshot[phase]) {\n throw new Error(`The ${phase} commitment changed while ${operation} was being prepared`);\n }\n }\n}\n\nfunction captureReviewAuthority(state: DesignPodFlowStateV1): string {\n if (!state.reviewAssignment || !state.reviewRequest || !state.review) throw new Error('Current review authority is required');\n return canonicalDesignPodJson({ assignment: state.reviewAssignment, request: state.reviewRequest, review: state.review });\n}\n\nfunction assertReviewAuthority(map: { get(key: string): unknown }, snapshot: string, operation: string): void {\n const current = canonicalDesignPodJson({ assignment: map.get('reviewAssignment'), request: map.get('reviewRequest'), review: map.get('review') });\n if (current !== snapshot) throw new Error(`The independent review changed while ${operation} was being prepared`);\n}\n\nfunction captureBlueprintAuthority(doc: Parameters<typeof readDesignPodState>[0], state: DesignPodFlowStateV1): string {\n const manifest = readDesignPodDefinition(doc);\n if (!manifest) throw new Error('The Design POD method definition is missing');\n const root = doc.getMap('root');\n return canonicalDesignPodJson({\n manifest,\n identity: state.identity,\n flowAuthority: { docId: root.get('doc_id'), flowOwnerDid: root.get('flowOwnerDid') },\n controls: state.controls,\n checklistRecords: state.checklistRecords,\n });\n}\n\nfunction assertBlueprintAuthority(doc: Parameters<typeof readDesignPodState>[0], snapshot: string, operation: string): void {\n const state = readDesignPodState(doc);\n if (!state || captureBlueprintAuthority(doc, state) !== snapshot) {\n throw new Error(`The project identity, method manifest, control bodies, or checklist dispositions changed while ${operation} was being prepared`);\n }\n}\n\nfunction assertReleaseCanBeCompiled(map: { get(key: string): unknown }, operation: string): void {\n const release = map.get('release') as { status?: string } | undefined;\n if (release?.status === 'publishing' || release?.status === 'published') {\n throw new Error(`A ${release.status} release cannot be replaced while ${operation} is being prepared`);\n }\n}\n\nconst COMMON_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'operation', displayName: 'Operation', type: 'string', description: 'Portal-native Design POD operation.' },\n { path: 'stateDigest', displayName: 'State digest', type: 'string', description: 'Digest binding this compact result to Flow-owned state.' },\n];\n\nfunction register(\n definition: {\n type: string;\n can: string;\n sideEffect: boolean;\n confirmation: boolean;\n required?: string[];\n properties?: Record<string, { type: string; description: string }>;\n hiddenFromAuthoring?: boolean;\n output: OutputSchemaField[];\n proof: ActionProofDeclaration;\n },\n run: (inputs: Record<string, unknown>, ctx: ActionContext) => Promise<Record<string, unknown>>\n): void {\n registerAction({\n type: definition.type,\n can: definition.can,\n sideEffect: definition.sideEffect,\n defaultRequiresConfirmation: definition.confirmation,\n requiredCapability: 'flow/block/execute',\n requiresSignedInvocation: definition.sideEffect,\n hiddenFromAuthoring: definition.hiddenFromAuthoring,\n proof: definition.proof,\n done: doneWhenCompleted,\n inputSchema: { type: 'object', required: definition.required ?? [], properties: definition.properties ?? {} },\n outputSchema: [...COMMON_OUTPUT_SCHEMA, ...definition.output],\n run: async (inputs, ctx): Promise<ActionResult> => {\n const result = await run(inputs, ctx);\n const stateDigest = await digestDesignPodValue(result);\n return { output: { operation: definition.type, stateDigest, ...result } };\n },\n });\n}\n\nconst LEGACY_WORKSPACE = { type: 'string', description: 'Read-only legacy v0.5/v0.6 Blueprint Runtime workspace ID.' };\nfor (const legacy of [\n ['qi/blueprint.workspace-start', 'blueprint/workspace-start'],\n ['qi/blueprint.journey-resume', 'blueprint/journey-resume'],\n ['qi/blueprint.guided-authoring', 'blueprint/guided-authoring'],\n] as const) {\n register(\n {\n type: legacy[0],\n can: legacy[1],\n sideEffect: false,\n confirmation: false,\n hiddenFromAuthoring: true,\n output: [],\n proof: 'none',\n properties: { workspaceId: LEGACY_WORKSPACE },\n },\n async () => {\n throw new Error('Remote Design POD workspaces are read-only legacy evidence. Export and import this workspace into design-pod-portal-journey-v2.');\n }\n );\n}\n\nregister(\n {\n type: 'qi/blueprint.artifact-preview',\n can: 'blueprint/artifact-preview',\n sideEffect: false,\n confirmation: false,\n required: ['controlId', 'content'],\n properties: {\n controlId: { type: 'string', description: 'One of the 17 controls in the pinned method manifest.' },\n content: { type: 'object', description: 'Typed draft patch proposed by Oxi or the provider.' },\n },\n output: [\n { path: 'controlId', displayName: 'Control ID', type: 'string' },\n { path: 'draftDigest', displayName: 'Draft digest', type: 'string' },\n { path: 'readyToAccept', displayName: 'Ready to accept', type: 'boolean' },\n ],\n proof: 'none',\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const id = controlId(inputs.controlId);\n const content = requiredRecord(inputs.content, 'content');\n const manifest = readDesignPodDefinition(requireDoc(ctx));\n if (!manifest?.controls[id]) throw new Error(`${id} is not part of the pinned Design POD method`);\n return { controlId: id, draftDigest: await digestDesignPodValue({ controlId: id, content }), readyToAccept: true };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.artifact-save',\n can: 'blueprint/artifact-save',\n sideEffect: true,\n confirmation: true,\n required: ['controlId', 'content'],\n properties: {\n controlId: { type: 'string', description: 'One of the 17 controls in the pinned method manifest.' },\n content: { type: 'object', description: 'Human-accepted typed control content.' },\n designProjectEntityDid: { type: 'string', description: 'Pinned Design Project entity DID.' },\n flowRoomId: { type: 'string', description: 'Pinned Matrix Flow room.' },\n sessionRunId: { type: 'string', description: 'Pinned Flow session run.' },\n methodManifestDigest: { type: 'string', description: 'Pinned method-manifest digest.' },\n },\n output: [\n { path: 'controlId', displayName: 'Control ID', type: 'string' },\n { path: 'revision', displayName: 'Revision', type: 'number' },\n { path: 'revisionDigest', displayName: 'Revision digest', type: 'string' },\n { path: 'status', displayName: 'Revision status', type: 'string' },\n ],\n proof: { fields: ['revisionDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const revision = await updateDesignPodControl(requireDoc(ctx), {\n controlId: controlId(inputs.controlId),\n content: requiredRecord(inputs.content, 'content'),\n actorDid: ctx.actorDid,\n sessionRunId: ctx.sessionRunId,\n });\n return { controlId: revision.controlId, revision: revision.revision, revisionDigest: revision.digest, status: revision.status };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.checklist-update',\n can: 'blueprint/checklist-update',\n sideEffect: true,\n confirmation: true,\n required: ['itemId', 'disposition'],\n properties: {\n itemId: { type: 'string', description: 'Governed checklist item identifier.' },\n disposition: { type: 'string', description: 'resolved, accepted_for_later, or blocking.' },\n },\n output: [\n { path: 'itemId', displayName: 'Checklist item', type: 'string' },\n { path: 'disposition', displayName: 'Disposition', type: 'string' },\n { path: 'checklistDigest', displayName: 'Checklist digest', type: 'string' },\n ],\n proof: { fields: ['checklistDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const doc = requireDoc(ctx);\n const itemId = requiredString(inputs.itemId, 'itemId');\n const disposition = requiredString(inputs.disposition, 'disposition');\n if (!['resolved', 'accepted_for_later', 'blocking'].includes(disposition)) throw new Error('Invalid checklist disposition');\n const manifest = readDesignPodDefinition(doc);\n if (!manifest?.publicationRules.checklistItems.some((item) => item.id === itemId)) throw new Error(`${itemId} is not a governed checklist item in the pinned method`);\n const updatedAt = new Date().toISOString();\n const digest = await digestDesignPodValue({ itemId, disposition, updatedByDid: ctx.actorDid, updatedAt });\n const record: DesignPodChecklistRecordV1 = {\n schemaVersion: '1.0',\n itemId,\n disposition: disposition as DesignPodChecklistRecordV1['disposition'],\n updatedByDid: ctx.actorDid,\n updatedAt,\n proof: requireExecutionProof(ctx),\n digest,\n };\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n doc.transact(() => {\n assertPublicationCanBeInvalidated(doc, map, authority, 'blueprint-checklist-update');\n map.set(`checklist:${itemId}`, record);\n markRecordStale(map, 'reviewRequest');\n markRecordStale(map, 'review');\n markRecordStale(map, 'release');\n });\n return { itemId, disposition, checklistDigest: digest };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.phase-commit',\n can: 'blueprint/phase-commit',\n sideEffect: true,\n confirmation: true,\n required: ['phase', 'decision', 'expectedControlDigests'],\n properties: {\n phase: { type: 'string', description: 'Discovery, design, validation, testing, or deployment.' },\n decision: { type: 'string', description: 'Must be exactly “Yes, continue”.' },\n expectedControlDigests: { type: 'object', description: 'Relevant-control concurrency guard.' },\n designProjectEntityDid: { type: 'string', description: 'Pinned Design Project entity DID.' },\n },\n output: [\n { path: 'phase', displayName: 'Phase', type: 'string' },\n { path: 'commitmentDigest', displayName: 'Commitment digest', type: 'string' },\n { path: 'artifactReceiptRefs', displayName: 'Artifact receipt references', type: 'array' },\n ],\n proof: { fields: ['commitmentDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const proof = requireExecutionProof(ctx);\n const doc = requireDoc(ctx);\n const state = readDesignPodState(doc)!;\n const manifest = readDesignPodDefinition(doc)!;\n const phase = phaseId(inputs.phase);\n const phaseDefinition = manifest.phases.find((candidate) => candidate.id === phase)!;\n const expectedControlDigests = requiredRecord(inputs.expectedControlDigests, 'expectedControlDigests') as Partial<Record<DesignPodControlId, string>>;\n const persistence = ctx.services.designPod;\n if (!persistence) throw new Error('Entity VFS Design POD service is not configured');\n\n for (const id of phaseDefinition.controls) {\n const revision = state.controls[id];\n if (!revision || revision.status !== 'current') throw new Error(`${id} must be current before committing ${phase}`);\n if (expectedControlDigests[id] !== revision.digest) throw new Error(`${id} changed while ${phase} was being committed`);\n const existing = state.artifactReceipts.find((receipt) => receipt.controlId === id && receipt.digest === revision.digest);\n if (existing) {\n const verified = await persistence.verifyArtifactReceipt({\n designProjectEntityDid: state.identity.designProjectEntityDid,\n revision,\n receipt: existing,\n });\n assertAuthorizedSessionOpen(doc, doc.getMap(DESIGN_POD_STATE_MAP_KEY), authority, `blueprint-phase-commit:${phase}`);\n createDesignPodArtifactReceipt(doc, { controlId: id, digest: revision.digest, ...verified });\n continue;\n }\n const persisted = await persistence.persistArtifact({\n designProjectEntityDid: state.identity.designProjectEntityDid,\n controlId: id,\n revision: revision.revision,\n digest: revision.digest,\n content: revision.content,\n });\n assertAuthorizedSessionOpen(doc, doc.getMap(DESIGN_POD_STATE_MAP_KEY), authority, `blueprint-phase-commit:${phase}`);\n createDesignPodArtifactReceipt(doc, { controlId: id, digest: revision.digest, ...persisted });\n }\n\n const commitment = await commitDesignPodPhase(doc, {\n phaseId: phase,\n actorDid: ctx.actorDid,\n decision: requiredString(inputs.decision, 'decision') as 'Yes, continue',\n expectedControlDigests,\n proof,\n });\n return {\n phase,\n commitmentDigest: commitment.digest,\n artifactReceiptRefs: commitment.artifactReceipts.map(({ id, path, version, contentHash, cid }) => ({ id, path, version, contentHash, cid })),\n };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.phase-confirm',\n can: 'blueprint/phase-confirm',\n sideEffect: false,\n confirmation: false,\n hiddenFromAuthoring: true,\n output: [],\n proof: 'none',\n },\n async () => {\n throw new Error('Phase confirmation is now atomic with qi/blueprint.phase-commit. Use the explicit “Yes, continue” commitment.');\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.reviewer-assign',\n can: 'blueprint/reviewer-assign',\n sideEffect: true,\n confirmation: true,\n required: ['reviewerDid'],\n properties: { reviewerDid: { type: 'string', description: 'Independent reviewer IXO DID.' } },\n output: [\n { path: 'reviewerDid', displayName: 'Reviewer DID', type: 'string' },\n { path: 'assignmentDigest', displayName: 'Assignment digest', type: 'string' },\n { path: 'status', displayName: 'Assignment status', type: 'string' },\n ],\n proof: { fields: ['assignmentDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const reviewerDid = requiredString(inputs.reviewerDid, 'reviewerDid');\n if (sameActorDid(reviewerDid, ctx.actorDid)) throw new Error('The provider cannot assign themself as the independent reviewer');\n const assignedAt = new Date().toISOString();\n const digest = await digestDesignPodValue({ reviewerDid, assignedByDid: ctx.actorDid, assignedAt });\n const assignment: DesignPodReviewAssignmentV1 = {\n schemaVersion: '1.0',\n reviewerDid,\n assignedByDid: ctx.actorDid,\n assignedAt,\n digest,\n proof: requireExecutionProof(ctx),\n };\n const doc = requireDoc(ctx);\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n doc.transact(() => {\n assertPublicationCanBeInvalidated(doc, map, authority, 'blueprint-reviewer-assign');\n map.set('reviewAssignment', assignment);\n markRecordStale(map, 'reviewRequest');\n markRecordStale(map, 'review');\n markRecordStale(map, 'release');\n });\n return { reviewerDid, assignmentDigest: digest, status: 'assigned' };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.review-submit',\n can: 'blueprint/review-submit',\n sideEffect: true,\n confirmation: true,\n output: [\n { path: 'revisionSetDigest', displayName: 'Revision-set digest', type: 'string' },\n { path: 'reviewRequestDigest', displayName: 'Review-request digest', type: 'string' },\n { path: 'status', displayName: 'Review request status', type: 'string' },\n ],\n proof: { fields: ['reviewRequestDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const doc = requireDoc(ctx);\n const state = readDesignPodState(doc)!;\n if (Object.values(state.phaseCommitments).filter((commitment) => commitment?.status === 'current').length !== 5) {\n throw new Error('All five provider phase commitments are required before independent review');\n }\n if (!state.reviewAssignment) throw new Error('An independent reviewer must be assigned before review submission');\n const phaseCommitments = capturePhaseCommitments(state);\n const assignmentDigest = state.reviewAssignment.digest;\n const revisionSetDigest = await computeDesignPodRevisionSetDigest(doc);\n const submittedAt = new Date().toISOString();\n const digest = await digestDesignPodValue({ revisionSetDigest, submittedByDid: ctx.actorDid, submittedAt });\n const request: DesignPodReviewRequestV1 = {\n schemaVersion: '1.0',\n revisionSetDigest,\n submittedByDid: ctx.actorDid,\n submittedAt,\n digest,\n proof: requireExecutionProof(ctx),\n status: 'current',\n };\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n doc.transact(() => {\n assertPublicationCanBeInvalidated(doc, map, authority, 'blueprint-review-submit');\n assertPhaseCommitments(map, phaseCommitments, 'the review request');\n const currentAssignment = map.get('reviewAssignment') as DesignPodReviewAssignmentV1 | undefined;\n if (currentAssignment?.digest !== assignmentDigest) throw new Error('The reviewer assignment changed while the review request was being prepared');\n map.set('reviewRequest', request);\n markRecordStale(map, 'review');\n markRecordStale(map, 'release');\n });\n return { revisionSetDigest, reviewRequestDigest: digest, status: 'submitted' };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.review-respond',\n can: 'blueprint/review-respond',\n sideEffect: true,\n confirmation: true,\n required: ['revisionSetDigest', 'decision', 'assignmentDigest', 'reviewRequestDigest'],\n properties: {\n revisionSetDigest: { type: 'string', description: 'Exact submitted revision-set digest.' },\n decision: { type: 'string', description: 'approved or changes_required.' },\n assignmentDigest: { type: 'string', description: 'Exact reviewer-assignment digest.' },\n reviewRequestDigest: { type: 'string', description: 'Exact review-request digest.' },\n },\n output: [\n { path: 'reviewerDid', displayName: 'Reviewer DID', type: 'string' },\n { path: 'revisionSetDigest', displayName: 'Revision-set digest', type: 'string' },\n { path: 'decision', displayName: 'Review decision', type: 'string' },\n { path: 'reviewDigest', displayName: 'Review digest', type: 'string' },\n ],\n proof: { fields: ['reviewDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const doc = requireDoc(ctx);\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n const assignment = map.get('reviewAssignment') as DesignPodReviewAssignmentV1 | undefined;\n if (!assignment || !sameActorDid(assignment.reviewerDid, ctx.actorDid)) {\n throw new Error(`The active IXO DID (${ctx.actorDid}) is not the assigned independent reviewer (${assignment?.reviewerDid ?? 'none'})`);\n }\n const assignmentDigest = requiredString(inputs.assignmentDigest, 'assignmentDigest');\n if (assignment.digest !== assignmentDigest) throw new Error('The review response is not bound to the current reviewer assignment');\n const revisionSetDigest = requiredString(inputs.revisionSetDigest, 'revisionSetDigest');\n const request = map.get('reviewRequest') as DesignPodReviewRequestV1 | undefined;\n if (!request || request.revisionSetDigest !== revisionSetDigest) {\n throw new Error('The review response is not bound to the exact submitted blueprint revision set');\n }\n const reviewRequestDigest = requiredString(inputs.reviewRequestDigest, 'reviewRequestDigest');\n if (request.digest !== reviewRequestDigest || request.status !== 'current') throw new Error('The review response is not bound to the current review request');\n if (sameActorDid(request.submittedByDid, ctx.actorDid)) throw new Error('The provider cannot independently review their own submitted blueprint');\n const phaseCommitments = capturePhaseCommitments(readDesignPodState(doc)!);\n if (revisionSetDigest !== (await computeDesignPodRevisionSetDigest(doc))) throw new Error('The blueprint changed after this review revision set was prepared');\n const decision = requiredString(inputs.decision, 'decision');\n if (!['approved', 'changes_required'].includes(decision)) throw new Error('Review decision must be approved or changes_required');\n let review!: DesignPodReviewRecordV1;\n doc.transact(() => {\n assertAuthorizedSessionOpen(doc, map, authority, 'blueprint-review-respond');\n assertPhaseCommitments(map, phaseCommitments, 'the review response');\n const currentAssignment = map.get('reviewAssignment') as DesignPodReviewAssignmentV1 | undefined;\n const currentRequest = map.get('reviewRequest') as DesignPodReviewRequestV1 | undefined;\n if (currentAssignment?.digest !== assignmentDigest || !sameActorDid(currentAssignment.reviewerDid, ctx.actorDid)) {\n throw new Error('The reviewer assignment changed while the review response was being prepared');\n }\n if (currentRequest?.digest !== reviewRequestDigest || currentRequest.status !== 'current') {\n throw new Error('The review request changed while the review response was being prepared');\n }\n review = markDesignPodReviewed(doc, {\n reviewerDid: ctx.actorDid,\n revisionSetDigest,\n decision: decision as 'approved' | 'changes_required',\n assignmentDigest,\n reviewRequestDigest,\n proof: requireExecutionProof(ctx),\n });\n map.set('reviewRequest', { ...currentRequest, respondedAt: review.reviewedAt, status: 'responded' });\n });\n const reviewDigest = await digestDesignPodValue(review);\n return { reviewerDid: review.reviewerDid, revisionSetDigest, decision, reviewDigest };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.release-compile',\n can: 'blueprint/release-compile',\n sideEffect: true,\n confirmation: true,\n output: [\n { path: 'releaseDigest', displayName: 'Release digest', type: 'string' },\n { path: 'revisionSetDigest', displayName: 'Revision-set digest', type: 'string' },\n { path: 'packageRoot', displayName: 'Package root', type: 'string' },\n { path: 'fileCount', displayName: 'File count', type: 'number' },\n ],\n proof: { fields: ['releaseDigest'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const authority = captureDesignPodAuthority(ctx);\n const doc = requireDoc(ctx);\n const persistence = ctx.services.designPod;\n if (!persistence) throw new Error('Entity VFS Design POD service is not configured');\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n assertReleaseCanBeCompiled(map, 'release compilation');\n const state = readDesignPodState(doc)!;\n const phaseCommitments = capturePhaseCommitments(state);\n const reviewAuthority = captureReviewAuthority(state);\n const blueprintAuthority = captureBlueprintAuthority(doc, state);\n const release = await compileDesignPodRelease(doc, {\n authority,\n verifyInvocation: persistence.verifyInvocation,\n verifyArtifactReceipt: persistence.verifyArtifactReceipt,\n });\n doc.transact(() => {\n assertPhaseCommitments(map, phaseCommitments, 'release compilation');\n assertReviewAuthority(map, reviewAuthority, 'release compilation');\n assertBlueprintAuthority(doc, blueprintAuthority, 'release compilation');\n assertReleaseCanBeCompiled(map, 'release compilation');\n map.set('release', {\n digest: release.releaseDigest,\n status: 'compiled',\n packageRoot: release.packageRoot,\n revisionSetDigest: release.revisionSetDigest,\n });\n });\n return { releaseDigest: release.releaseDigest, revisionSetDigest: release.revisionSetDigest, packageRoot: release.packageRoot, fileCount: release.files.length };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.yoma-readiness',\n can: 'blueprint/yoma-readiness',\n sideEffect: false,\n confirmation: false,\n output: [\n { path: 'readiness', displayName: 'Readiness', type: 'object' },\n { path: 'publicationStatus', displayName: 'Publication status', type: 'string' },\n { path: 'currentCommitments', displayName: 'Current commitments', type: 'number' },\n { path: 'reviewStatus', displayName: 'Review status', type: 'string' },\n { path: 'releaseDigest', displayName: 'Release digest', type: 'string' },\n ],\n proof: 'none',\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const state = readDesignPodState(requireDoc(ctx))!;\n return {\n readiness: state.readiness,\n publicationStatus: state.publicationStatus,\n currentCommitments: Object.values(state.phaseCommitments).filter((commitment) => commitment?.status === 'current').length,\n reviewStatus: state.review?.status ?? 'not_started',\n releaseDigest: state.release?.digest,\n };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.publish',\n can: 'blueprint/publish',\n sideEffect: true,\n confirmation: true,\n required: ['releaseDigest'],\n properties: {\n releaseDigest: { type: 'string', description: 'Exact independently reviewed compiled release digest.' },\n designProjectEntityDid: { type: 'string', description: 'Pinned Design Project entity DID.' },\n },\n output: [\n { path: 'releaseDigest', displayName: 'Release digest', type: 'string' },\n { path: 'packageRoot', displayName: 'Package root', type: 'string' },\n { path: 'domainCid', displayName: 'Domain CID', type: 'string' },\n { path: 'resourceId', displayName: 'IXO linked-resource ID', type: 'string' },\n { path: 'transactionHash', displayName: 'IXO transaction hash', type: 'string' },\n { path: 'verifiedAt', displayName: 'Verified at', type: 'string' },\n { path: 'fileReceipts', displayName: 'VFS file receipts', type: 'array' },\n ],\n proof: { fields: ['resourceId', 'domainCid'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const doc = requireDoc(ctx);\n const state = readDesignPodState(doc)!;\n const authority = captureDesignPodAuthority(ctx);\n const persistence = ctx.services.designPod;\n if (!persistence) throw new Error('Entity VFS Design POD service is not configured');\n const phaseCommitments = capturePhaseCommitments(state);\n const reviewAuthority = captureReviewAuthority(state);\n const blueprintAuthority = captureBlueprintAuthority(doc, state);\n const publishableReleaseDigest = state.release && ['compiled', 'publishing'].includes(state.release.status) ? state.release.digest : undefined;\n if (!publishableReleaseDigest) throw new Error('A current compiled or verification-pending release is required before publication');\n const release = await compileDesignPodRelease(doc, {\n authority,\n verifyInvocation: persistence.verifyInvocation,\n verifyArtifactReceipt: persistence.verifyArtifactReceipt,\n });\n if (requiredString(inputs.releaseDigest, 'releaseDigest') !== release.releaseDigest) throw new Error('releaseDigest is not the current independently reviewed release');\n const persisted = await persistence.persistRelease({ designProjectEntityDid: state.identity.designProjectEntityDid, release });\n const linkedResource = {\n id: `${state.identity.designProjectEntityDid}#design-pod-${release.releaseDigest.replace('sha256:', '').slice(0, 24)}`,\n type: 'application/vnd.ixo.design-pod+json',\n description: 'Independently reviewed Design POD release package',\n serviceEndpoint: persisted.domainServiceEndpoint,\n proof: persisted.domainCid,\n mediaType: 'text/markdown',\n encrypted: 'true',\n right: 'UCAN',\n };\n const map = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n const priorAttempt = state.release?.status === 'publishing' ? requiredRecord(state.release.publicationAttempt, 'publicationAttempt') : undefined;\n if (\n priorAttempt &&\n (priorAttempt.releaseDigest !== release.releaseDigest || priorAttempt.packageRoot !== persisted.packageRoot || priorAttempt.domainCid !== persisted.domainCid)\n ) {\n throw new Error('The verification-pending publication reservation does not match the current deterministic release');\n }\n const publicationInvocationCid = requireExecutionProof(ctx).invocationCid;\n const recordedBroadcastAttempt = priorAttempt?.broadcastAttempt;\n if (recordedBroadcastAttempt !== undefined && (typeof recordedBroadcastAttempt !== 'number' || !Number.isInteger(recordedBroadcastAttempt) || recordedBroadcastAttempt <= 0)) {\n throw new Error('The publication broadcast attempt counter is invalid');\n }\n let broadcastAttempt = (recordedBroadcastAttempt as number | undefined) ?? 1;\n let publicationAttempt: Record<string, unknown> =\n priorAttempt ??\n ({\n releaseDigest: release.releaseDigest,\n packageRoot: persisted.packageRoot,\n domainCid: persisted.domainCid,\n resourceId: linkedResource.id,\n reservedAt: new Date().toISOString(),\n invocationCid: publicationInvocationCid,\n broadcastAttempt,\n } satisfies Record<string, unknown>);\n doc.transact(() => {\n assertPhaseCommitments(map, phaseCommitments, 'publication');\n assertReviewAuthority(map, reviewAuthority, 'publication');\n assertBlueprintAuthority(doc, blueprintAuthority, 'publication');\n const currentRelease = map.get('release') as { digest?: string; status?: string; publicationAttempt?: unknown } | undefined;\n if (\n !currentRelease ||\n !['compiled', 'publishing'].includes(currentRelease.status || '') ||\n currentRelease.digest !== publishableReleaseDigest ||\n currentRelease.digest !== release.releaseDigest\n ) {\n throw new Error('The compiled release changed while publication was being authorized');\n }\n if (currentRelease.status === 'publishing' && canonicalDesignPodJson(currentRelease.publicationAttempt) !== canonicalDesignPodJson(publicationAttempt)) {\n throw new Error('The publication reservation changed while receipt verification was being authorized');\n }\n map.set('release', {\n ...currentRelease,\n digest: release.releaseDigest,\n status: 'publishing',\n packageRoot: persisted.packageRoot,\n publicationAttempt,\n });\n });\n\n const verifyPublication = () =>\n persistence.verifyPublicationReceipt({\n designProjectEntityDid: state.identity.designProjectEntityDid,\n releaseDigest: release.releaseDigest,\n linkedResource,\n });\n const finalizePublication = (verification: Awaited<ReturnType<typeof persistence.verifyPublicationReceipt>>, transactionHash?: string): Record<string, unknown> => {\n if (verification.status !== 'published' || !verification.linkedResource) throw new Error('IXO publication has not been authoritatively verified');\n const publicationReceipt = {\n releaseDigest: release.releaseDigest,\n resourceId: linkedResource.id,\n linkedResource: verification.linkedResource,\n domainCid: persisted.domainCid,\n fileReceipts: persisted.files,\n verifiedAt: verification.verifiedAt,\n ...(transactionHash ? { transactionHash } : {}),\n };\n doc.transact(() => {\n const currentRelease = map.get('release') as { digest?: string; status?: string; [key: string]: unknown } | undefined;\n if (currentRelease?.digest !== release.releaseDigest || !['publishing', 'published'].includes(currentRelease.status || '')) {\n throw new Error('The publication reservation changed before authoritative receipt reconciliation');\n }\n map.set(`publication:${release.releaseDigest}`, {\n ...publicationAttempt,\n ...publicationReceipt,\n reconciledByInvocationCid: publicationInvocationCid,\n });\n map.set('release', { ...currentRelease, status: 'published', publicationReceipt });\n });\n return publicationReceipt;\n };\n\n const existing = await verifyPublication();\n if (existing.status === 'published') {\n const priorTransactionHash = typeof publicationAttempt.transactionHash === 'string' ? publicationAttempt.transactionHash : undefined;\n const receipt = finalizePublication(existing, priorTransactionHash);\n return { releaseDigest: release.releaseDigest, packageRoot: persisted.packageRoot, domainCid: persisted.domainCid, resourceId: linkedResource.id, ...receipt };\n }\n const recordedTransactionHash = typeof publicationAttempt.transactionHash === 'string' ? publicationAttempt.transactionHash : undefined;\n if (recordedTransactionHash) {\n const transactionStatus = await persistence.getTransactionStatus(recordedTransactionHash);\n const status = requiredString(transactionStatus?.status, 'transactionStatus.status');\n if (status !== 'failed') {\n throw new Error(`IXO transaction ${recordedTransactionHash} is ${status} and remains reconciliation-only until its linked resource is authoritatively indexed`);\n }\n const code = transactionStatus?.code;\n if (typeof code !== 'number' || !Number.isInteger(code) || code <= 0) {\n throw new Error('A definitively failed IXO transaction requires a positive integer result code');\n }\n const observedTransactionHash = requiredString(transactionStatus.transactionHash, 'transactionStatus.transactionHash');\n const comparableTransactionHash = (value: string) => value.replace(/^0x/i, '').toLowerCase();\n if (comparableTransactionHash(observedTransactionHash) !== comparableTransactionHash(recordedTransactionHash)) {\n throw new Error('IXO transaction status readback returned a different transaction hash');\n }\n const observedAt = requiredString(transactionStatus.observedAt, 'transactionStatus.observedAt');\n const priorFailures = publicationAttempt.failedTransactions;\n if (priorFailures !== undefined && !Array.isArray(priorFailures)) throw new Error('The publication failure history is invalid');\n const retryAttempt = Object.fromEntries(Object.entries(publicationAttempt).filter(([key]) => key !== 'transactionHash' && key !== 'broadcastAt' && key !== 'broadcastLease'));\n retryAttempt.failedTransactions = [\n ...((priorFailures as unknown[] | undefined) ?? []),\n { transactionHash: recordedTransactionHash, code, observedAt, ...(transactionStatus.height ? { height: transactionStatus.height } : {}) },\n ];\n retryAttempt.retryAuthorizedAt = new Date().toISOString();\n retryAttempt.invocationCid = publicationInvocationCid;\n broadcastAttempt += 1;\n retryAttempt.broadcastAttempt = broadcastAttempt;\n doc.transact(() => {\n const currentRelease = map.get('release') as { digest?: string; status?: string; publicationAttempt?: unknown; [key: string]: unknown } | undefined;\n if (\n currentRelease?.digest !== release.releaseDigest ||\n currentRelease.status !== 'publishing' ||\n canonicalDesignPodJson(currentRelease.publicationAttempt) !== canonicalDesignPodJson(publicationAttempt)\n ) {\n throw new Error('The publication reservation changed while failed-transaction recovery was being authorized');\n }\n map.set('release', { ...currentRelease, publicationAttempt: retryAttempt });\n });\n publicationAttempt = retryAttempt;\n }\n\n const matrixClaim = await claimPublicationBroadcast(ctx, {\n authority,\n releaseDigest: release.releaseDigest,\n packageRoot: persisted.packageRoot,\n domainCid: persisted.domainCid,\n broadcastAttempt,\n verifyInvocation: persistence.verifyInvocation,\n });\n const leasedAttempt = {\n ...publicationAttempt,\n broadcastAttempt,\n broadcastLease: {\n invocationCid: publicationInvocationCid,\n acquiredAt: new Date().toISOString(),\n matrixEventId: matrixClaim.eventId,\n matrixOriginServerTs: matrixClaim.originServerTs,\n },\n };\n doc.transact(() => {\n const currentRelease = map.get('release') as { digest?: string; status?: string; publicationAttempt?: unknown; [key: string]: unknown } | undefined;\n if (\n currentRelease?.digest !== release.releaseDigest ||\n currentRelease.status !== 'publishing' ||\n canonicalDesignPodJson(currentRelease.publicationAttempt) !== canonicalDesignPodJson(publicationAttempt)\n ) {\n throw new Error('The publication reservation changed before the IXO broadcast lease was acquired');\n }\n const currentAttempt = requiredRecord(currentRelease.publicationAttempt, 'publicationAttempt');\n if (currentAttempt.transactionHash) throw new Error('An IXO transaction is already recorded for this publication');\n if (currentAttempt.broadcastLease) {\n throw new Error('The IXO publication broadcast lease is already held and remains reconciliation-only');\n }\n map.set('release', { ...currentRelease, publicationAttempt: leasedAttempt });\n });\n publicationAttempt = leasedAttempt;\n let transactionHash: string | undefined;\n const recordBroadcast = (candidate: unknown): string => {\n const nextTransactionHash = requiredString(candidate, 'transactionHash');\n doc.transact(() => {\n const currentRelease = map.get('release') as { digest?: string; status?: string; publicationAttempt?: unknown; [key: string]: unknown } | undefined;\n if (currentRelease?.digest !== release.releaseDigest || currentRelease.status !== 'publishing') {\n throw new Error('The publication reservation changed after the IXO broadcast');\n }\n const currentAttempt = requiredRecord(currentRelease.publicationAttempt, 'publicationAttempt');\n if (currentAttempt.releaseDigest !== release.releaseDigest || currentAttempt.packageRoot !== persisted.packageRoot || currentAttempt.domainCid !== persisted.domainCid) {\n throw new Error('The publication reservation changed after the IXO broadcast');\n }\n const currentLease = requiredRecord(currentAttempt.broadcastLease, 'broadcastLease');\n if (currentLease.invocationCid !== publicationInvocationCid) {\n throw new Error('The IXO broadcast was not made by the invocation holding the publication lease');\n }\n const currentTransactionHash = typeof currentAttempt.transactionHash === 'string' ? currentAttempt.transactionHash : undefined;\n if (currentTransactionHash && currentTransactionHash !== nextTransactionHash) {\n throw new Error('A different IXO transaction is already recorded for this publication');\n }\n map.set('release', {\n ...currentRelease,\n publicationAttempt: {\n ...currentAttempt,\n transactionHash: nextTransactionHash,\n broadcastAt: currentAttempt.broadcastAt ?? new Date().toISOString(),\n },\n });\n });\n transactionHash = nextTransactionHash;\n return nextTransactionHash;\n };\n try {\n const tx = await persistence.broadcastPublication({\n designProjectEntityDid: state.identity.designProjectEntityDid,\n linkedResource,\n memo: `Publish Design POD ${release.releaseDigest}`,\n onBroadcast: (hash: string) => recordBroadcast(hash),\n });\n const returnedTransactionHash = requiredString(tx?.transactionHash, 'transactionHash');\n if (transactionHash && transactionHash !== returnedTransactionHash) {\n throw new Error('SignX confirmation returned a different transaction hash from the broadcast');\n }\n if (!transactionHash) recordBroadcast(returnedTransactionHash);\n } catch (error) {\n const errorTransactionHash =\n error && typeof error === 'object' && 'transactionHash' in error && typeof error.transactionHash === 'string' ? error.transactionHash : undefined;\n if (!transactionHash && errorTransactionHash) recordBroadcast(errorTransactionHash);\n const reconciliation = await verifyPublication();\n if (reconciliation.status === 'published') {\n const receipt = finalizePublication(reconciliation, transactionHash);\n return { releaseDigest: release.releaseDigest, packageRoot: persisted.packageRoot, domainCid: persisted.domainCid, resourceId: linkedResource.id, ...receipt };\n }\n throw new Error(\n `IXO publication outcome is awaiting authoritative linked-resource verification: ${error instanceof Error ? error.message : 'broadcast confirmation was lost'}`\n );\n }\n\n const verified = await verifyPublication();\n if (verified.status !== 'published') {\n throw new Error('IXO broadcast was submitted and is awaiting authoritative linked-resource verification');\n }\n const receipt = finalizePublication(verified, transactionHash!);\n return { releaseDigest: release.releaseDigest, packageRoot: persisted.packageRoot, domainCid: persisted.domainCid, resourceId: linkedResource.id, ...receipt };\n }\n);\n\nregister(\n {\n type: 'qi/blueprint.protocol-mint',\n can: 'blueprint/protocol-mint',\n sideEffect: true,\n confirmation: true,\n required: ['releaseDigest'],\n properties: {\n releaseDigest: { type: 'string', description: 'Exact published release digest whose package is unpacked into the protocol.' },\n designProjectEntityDid: { type: 'string', description: 'Pinned Design Project entity DID.' },\n title: { type: 'string', description: 'Name for the minted protocol entity. Defaults to the pinned method title.' },\n },\n output: [\n { path: 'protocolEntityDid', displayName: 'Protocol entity DID', type: 'string' },\n { path: 'entityType', displayName: 'Protocol entity type', type: 'string' },\n { path: 'templateCount', displayName: 'Operational templates', type: 'number' },\n { path: 'resourceCount', displayName: 'Linked resources', type: 'number' },\n { path: 'failures', displayName: 'Unpacking failures', type: 'array' },\n { path: 'transactionHash', displayName: 'IXO transaction hash', type: 'string' },\n { path: 'mintedAt', displayName: 'Minted at', type: 'string' },\n ],\n proof: { fields: ['protocolEntityDid'] },\n },\n async (inputs, ctx) => {\n await assertIdentity(inputs, ctx);\n const doc = requireDoc(ctx);\n const state = readDesignPodState(doc)!;\n const persistence = ctx.services.designPod;\n if (!persistence) throw new Error('Entity VFS Design POD service is not configured');\n const releaseDigest = requiredString(inputs.releaseDigest, 'releaseDigest');\n\n const report = (minted: NonNullable<DesignPodFlowStateV1['protocol']>) => ({\n protocolEntityDid: minted.entityDid,\n entityType: minted.entityType,\n templateCount: minted.templates.length,\n resourceCount: minted.resources.length,\n failures: minted.failures,\n ...(minted.transactionHash ? { transactionHash: minted.transactionHash } : {}),\n mintedAt: minted.mintedAt,\n });\n\n // Minting is not replayable: a second run would put a second entity on chain.\n // A finished record is the answer; an unfinished one is resumed into the\n // protocol it already created.\n if (state.protocol) {\n if (state.protocol.releaseDigest !== releaseDigest) throw new Error('This design project already minted a protocol from a different release');\n if (state.protocol.status === 'minted') return report(state.protocol);\n }\n const resumeEntityDid = state.protocol?.entityDid;\n if (state.release?.status !== 'published' || state.release.digest !== releaseDigest) {\n throw new Error('An authoritatively published release is required before its protocol can be minted');\n }\n\n const authority = captureDesignPodAuthority(ctx);\n const phaseCommitments = capturePhaseCommitments(state);\n const reviewAuthority = captureReviewAuthority(state);\n const blueprintAuthority = captureBlueprintAuthority(doc, state);\n const release = await compileDesignPodRelease(doc, {\n authority,\n verifyInvocation: persistence.verifyInvocation,\n verifyArtifactReceipt: persistence.verifyArtifactReceipt,\n });\n if (release.releaseDigest !== releaseDigest) throw new Error('releaseDigest is not the current independently reviewed release');\n\n const manifest = readDesignPodDefinition(doc)!;\n const stateMap = doc.getMap(DESIGN_POD_STATE_MAP_KEY);\n const result = await persistence.mintProtocol({\n designProjectEntityDid: state.identity.designProjectEntityDid,\n release,\n title: typeof inputs.title === 'string' && inputs.title.trim() ? inputs.title.trim() : manifest.title,\n resumeEntityDid,\n // Recorded before the package is unpacked: from here the entity exists on\n // chain, so a lost run must be resumable rather than repeatable.\n onEntityCreated: (protocol) =>\n stateMap.set('protocol', {\n ...protocol,\n status: 'minting',\n releaseDigest: release.releaseDigest,\n templates: [],\n resources: [],\n failures: [],\n mintedAt: new Date().toISOString(),\n } satisfies NonNullable<DesignPodFlowStateV1['protocol']>),\n });\n const minted: NonNullable<DesignPodFlowStateV1['protocol']> = {\n status: 'minted',\n entityDid: requiredString(result?.entityDid, 'mintProtocol.entityDid'),\n entityType: requiredString(result?.entityType, 'mintProtocol.entityType'),\n releaseDigest: release.releaseDigest,\n templates: Array.isArray(result?.templates) ? result.templates : [],\n resources: Array.isArray(result?.resources) ? result.resources : [],\n failures: Array.isArray(result?.failures) ? result.failures : [],\n // A resumed run creates no entity, so its create-tx hash survives only on\n // the record written by the interrupted one.\n ...(result?.transactionHash || state.protocol?.transactionHash ? { transactionHash: result?.transactionHash || state.protocol!.transactionHash } : {}),\n mintedAt: requiredString(result?.mintedAt, 'mintProtocol.mintedAt'),\n };\n\n doc.transact(() => {\n const map = stateMap;\n assertPhaseCommitments(map, phaseCommitments, 'protocol minting');\n assertReviewAuthority(map, reviewAuthority, 'protocol minting');\n assertBlueprintAuthority(doc, blueprintAuthority, 'protocol minting');\n const currentRelease = map.get('release') as { digest?: string; status?: string } | undefined;\n if (currentRelease?.digest !== release.releaseDigest || currentRelease.status !== 'published') {\n throw new Error('The published release changed while the protocol was being minted');\n }\n // The entity is already on chain — a concurrent mint recorded first wins and\n // this one is reported as a duplicate rather than silently overwritten.\n const recorded = map.get('protocol') as DesignPodFlowStateV1['protocol'];\n if (recorded && recorded.entityDid !== minted.entityDid) throw new Error('Another protocol was minted for this design project while this mint was running');\n map.set('protocol', minted);\n });\n return report(minted);\n }\n);\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { sha256Digest } from '../../digest';\nimport type { OutputSchemaField } from '../../types';\n\n/**\n * A DAO DAO proposal action in the legacy `{ type, data }` shape that the\n * consumer's `transformActionsToMsgs` converts into on-chain messages. Every\n * `qi/governance.*` proposal action emits these, so the editor never builds\n * cosmos messages itself and existing consumers (ixo-portal,\n * impacts-x-webapp) need no changes to support a new block.\n */\nexport interface LegacyProposalAction {\n type: string;\n data: Record<string, any>;\n}\n\n/**\n * Spec for one `qi/governance.*` proposal-creating action. The registered\n * action shares the whole create-proposal lifecycle (handler checks, core\n * address, title/description, proof guard, standard outputs) — the spec only\n * contributes input validation and the legacy proposal action(s) to wrap.\n */\nexport interface GovernanceProposalActionSpec {\n /** Action type, e.g. `qi/governance.nft.burn`. */\n type: string;\n /** UCAN-style ability string, e.g. `governance.nft/burn`. */\n can: string;\n /**\n * Validate inputs and build the legacy DAO DAO proposal action(s) this\n * proposal executes when passed. Throw with a clear message on invalid\n * input — the flow engine surfaces it as a failed run.\n */\n buildActions: (inputs: Record<string, any>) => LegacyProposalAction[];\n /** Fallback proposal title for templates authored before the name field existed. */\n defaultTitle: (inputs: Record<string, any>) => string;\n /** Fallback long-form description. Defaults to the title when omitted. */\n defaultDescription?: (inputs: Record<string, any>) => string;\n /** Extra action-specific fields copied into the runtime output. */\n buildExtraOutput?: (inputs: Record<string, any>) => Record<string, string>;\n /** Schema entries for the fields `buildExtraOutput` adds. */\n extraOutputSchema?: OutputSchemaField[];\n}\n\ntype JsonSchemaProperty = { type?: string | string[]; description?: string; items?: object; enum?: Array<string | number | boolean> };\n\nconst GOVERNANCE_REQUIRED_FIELDS: Record<string, string[]> = {\n 'qi/governance.authz.exec': ['authzExecActionType'],\n 'qi/governance.authz.grant': ['grantee', 'msgTypeUrl'],\n 'qi/governance.authz.revoke': ['grantee', 'msgTypeUrl'],\n 'qi/governance.chain-governance-vote': ['proposalId', 'vote'],\n 'qi/governance.contract.execute': ['address', 'message'],\n 'qi/governance.contract.instantiate': ['codeId', 'label', 'message'],\n 'qi/governance.contract.manage-cw20': ['adding', 'address'],\n 'qi/governance.contract.migrate': ['contract', 'codeId', 'msg'],\n 'qi/governance.contract.update-admin': ['contract', 'newAdmin'],\n 'qi/governance.custom-message': ['message'],\n 'qi/governance.dao.accept-to-marketplace': ['did', 'relayerNodeAddress', 'relayerNodeDid'],\n 'qi/governance.dao.admin-exec': ['targetCoreAddress', 'msgs'],\n 'qi/governance.dao.create-entity': ['typeUrl', 'value'],\n 'qi/governance.dao.join': ['entityDid', 'memberId'],\n 'qi/governance.dao.manage-storage': ['setting', 'key', 'value'],\n 'qi/governance.dao.manage-subdaos': [],\n 'qi/governance.dao.update-info': ['name'],\n 'qi/governance.member-proposal': ['operation', 'members'],\n 'qi/governance.nft.burn': ['collection', 'tokenId'],\n 'qi/governance.nft.manage-collections': ['adding', 'address'],\n 'qi/governance.nft.transfer': ['collection', 'tokenId', 'recipient'],\n 'qi/governance.staking.stake': ['stakeType', 'amount'],\n 'qi/governance.staking.stake-to-group': ['tokenContract', 'stakingContract', 'amount'],\n 'qi/governance.settings-proposal': ['votingPeriodHours', 'quorumPercent', 'thresholdPercent'],\n 'qi/governance.submission-config-proposal': ['anyoneCanPropose', 'depositRequired'],\n 'qi/governance.transaction.mint': ['recipient', 'amount'],\n 'qi/governance.transaction.send-funds': ['recipient', 'denom', 'amount'],\n 'qi/governance.transaction.perform-token-swap': ['tokenSwapContractAddress', 'selfPartyType', 'selfPartyDenomOrAddress', 'selfPartyAmount'],\n 'qi/governance.transaction.send-group-token': ['tokenContract', 'recipient', 'amount'],\n 'qi/governance.transaction.withdraw-token-swap': ['tokenSwapContractAddress'],\n 'qi/governance.validator.actions': ['validatorActionType'],\n};\n\nconst GOVERNANCE_FIELDS: Record<string, string[]> = {\n 'qi/governance.authz.exec': ['authzExecActionType', 'delegatorAddress', 'validatorAddress', 'validatorDstAddress', 'amount', 'custom'],\n 'qi/governance.authz.grant': ['grantee', 'msgTypeUrl'],\n 'qi/governance.authz.revoke': ['grantee', 'msgTypeUrl'],\n 'qi/governance.chain-governance-vote': ['proposalId', 'vote'],\n 'qi/governance.contract.execute': ['address', 'message', 'funds'],\n 'qi/governance.contract.instantiate': ['codeId', 'label', 'admin', 'message', 'funds'],\n 'qi/governance.contract.manage-cw20': ['adding', 'address'],\n 'qi/governance.contract.migrate': ['contract', 'codeId', 'msg'],\n 'qi/governance.contract.update-admin': ['contract', 'newAdmin'],\n 'qi/governance.custom-message': ['message'],\n 'qi/governance.dao.accept-to-marketplace': ['did', 'relayerNodeAddress', 'relayerNodeDid'],\n 'qi/governance.dao.admin-exec': ['targetCoreAddress', 'msgs'],\n 'qi/governance.dao.create-entity': ['typeUrl', 'value'],\n 'qi/governance.dao.join': ['entityDid', 'memberId'],\n 'qi/governance.dao.manage-storage': ['setting', 'key', 'value'],\n 'qi/governance.dao.manage-subdaos': ['toAdd', 'toRemove'],\n 'qi/governance.dao.update-info': ['name', 'daoDescription', 'imageUrl', 'automaticallyAddCw20s', 'automaticallyAddCw721s'],\n 'qi/governance.member-proposal': ['operation', 'members'],\n 'qi/governance.nft.burn': ['collection', 'tokenId'],\n 'qi/governance.nft.manage-collections': ['adding', 'address'],\n 'qi/governance.nft.transfer': ['collection', 'tokenId', 'recipient', 'executeSmartContract', 'smartContractMsg'],\n 'qi/governance.staking.stake': ['stakeType', 'validator', 'toValidator', 'amount'],\n 'qi/governance.staking.stake-to-group': ['tokenContract', 'stakingContract', 'amount'],\n 'qi/governance.settings-proposal': ['votingPeriodHours', 'quorumPercent', 'thresholdPercent', 'allowRevoting'],\n 'qi/governance.submission-config-proposal': ['anyoneCanPropose', 'depositRequired', 'depositAmount', 'depositRefundPolicy'],\n 'qi/governance.transaction.mint': ['recipient', 'amount'],\n 'qi/governance.transaction.send-funds': ['recipient', 'denom', 'amount'],\n 'qi/governance.transaction.perform-token-swap': ['tokenSwapContractAddress', 'selfPartyType', 'selfPartyDenomOrAddress', 'selfPartyAmount'],\n 'qi/governance.transaction.send-group-token': ['tokenContract', 'recipient', 'amount'],\n 'qi/governance.transaction.withdraw-token-swap': ['tokenSwapContractAddress'],\n 'qi/governance.validator.actions': ['validatorActionType', 'createMsg', 'editMsg'],\n};\n\nconst BOOLEAN_FIELDS = new Set(['adding', 'automaticallyAddCw20s', 'automaticallyAddCw721s', 'executeSmartContract', 'anyoneCanPropose', 'depositRequired', 'allowRevoting']);\nconst NUMBER_FIELDS = new Set(['codeId', 'vote', 'votingPeriodHours', 'quorumPercent', 'thresholdPercent']);\nconst ARRAY_FIELDS = new Set(['funds', 'msgs', 'toAdd', 'toRemove', 'members']);\nconst OBJECT_FIELDS = new Set(['value']);\n\nfunction governanceProperty(name: string): JsonSchemaProperty {\n if (BOOLEAN_FIELDS.has(name)) return { type: 'boolean' };\n if (NUMBER_FIELDS.has(name)) return { type: 'number' };\n if (ARRAY_FIELDS.has(name)) return { type: 'array', items: {} };\n if (OBJECT_FIELDS.has(name)) return { type: 'object' };\n return { type: 'string' };\n}\n\n/** Exact per-type schema catalogue for the shared governance family. */\nexport function governanceInputSchema(type: string, extraFields: Record<string, JsonSchemaProperty> = {}, requiredOverride?: string[]): object {\n const properties: Record<string, JsonSchemaProperty> = {\n coreAddress: { type: 'string', description: 'DAO core contract address.' },\n title: { type: 'string', description: 'Proposal title voters see.' },\n description: { type: 'string', description: 'Long-form proposal description voters see.' },\n };\n for (const field of GOVERNANCE_FIELDS[type] || []) properties[field] = governanceProperty(field);\n Object.assign(properties, extraFields);\n return {\n type: 'object',\n required: ['coreAddress', ...(requiredOverride || GOVERNANCE_REQUIRED_FIELDS[type] || [])],\n additionalProperties: false,\n properties,\n };\n}\n\nconst STANDARD_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'proposalTitle', displayName: 'Proposal Title', type: 'string', description: 'The proposal name voters see on-chain' },\n { path: 'proposalDescription', displayName: 'Proposal Description', type: 'string', description: 'The long-form description voters see on-chain' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n];\n\n/**\n * Register a `qi/governance.*` action that creates an on-chain DAO DAO\n * proposal. Mirrors the hand-rolled member/settings/send-funds actions:\n * the consumer's `createProposal` handler broadcasts the proposal against the\n * group's pre-propose module, and the returned proposal id is the proof of\n * execution.\n *\n * Common inputs every registered action accepts:\n * - coreAddress: DAO core contract address (required; the flow detail\n * resolves it from the current entity when the template leaves it blank).\n * - title / description: the proposal name and long-form description shown\n * to voters. Stored on-chain in the proposal itself, so anyone voting can\n * read what the proposal does. Falls back to the spec's defaults for\n * templates authored before these fields existed.\n */\nexport function registerGovernanceProposalAction(spec: GovernanceProposalActionSpec): void {\n registerAction({\n type: spec.type,\n can: spec.can,\n sideEffect: true,\n proof: { fields: ['proposalId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n inputSchema: governanceInputSchema(spec.type),\n\n outputSchema: [...STANDARD_OUTPUT_SCHEMA, ...(spec.extraOutputSchema || [])],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.getPreProposalContractAddress || !handlers.getGroupContractAddress || !handlers.getProposalContractAddress || !handlers.createProposal) {\n throw new Error('Governance proposal handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n if (!coreAddress) throw new Error('coreAddress is required');\n\n const actions = spec.buildActions(inputs);\n if (!actions.length) throw new Error('The proposal must contain at least one action');\n\n const title = String(inputs.title || '').trim() || spec.defaultTitle(inputs);\n const description = String(inputs.description || '').trim() || (spec.defaultDescription ? spec.defaultDescription(inputs) : title);\n\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({ coreAddress });\n const { groupContractAddress } = await handlers.getGroupContractAddress({ coreAddress });\n const { proposalContractAddress } = await handlers.getProposalContractAddress({ coreAddress });\n\n const proposalId = await handlers.createProposal({\n preProposalContractAddress,\n title,\n description,\n actions,\n coreAddress,\n groupContractAddress,\n });\n\n // Proof guard: a proposal id is the contract the consumer must return\n // when the proposal was actually broadcast. No id → treat as a failure.\n if (proposalId === undefined || proposalId === null || String(proposalId).trim() === '') {\n throw new Error('Proposal creation returned no proposal id. Check the handler logs.');\n }\n\n const createdAt = new Date().toISOString();\n const output = {\n proposalId: String(proposalId),\n proposalTitle: title,\n proposalDescription: description,\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n createdAt,\n ...(spec.buildExtraOutput ? spec.buildExtraOutput(inputs) : {}),\n };\n return {\n output,\n topicRecords: ctx.topic\n ? [\n {\n type: 'org.ixo.topic.proposal-receipt',\n id: sha256Digest({ topicId: ctx.topic.topicId, proposalContractAddress, proposalId }),\n version: 1,\n value: {\n event: 'created',\n actionType: spec.type,\n proposalId: String(proposalId),\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n proposalTitle: title,\n proposalDescriptionDigest: sha256Digest(description),\n createdAt,\n },\n },\n ]\n : undefined,\n };\n },\n });\n}\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { governanceInputSchema } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that changes the\n * membership of a DAO DAO group: add members, remove members, or change a\n * member's voting power. All three map onto a single cw4 `update_members`\n * message wrapped as a DAO proposal `UpdateMembers` action — cw4 upserts by\n * address, so re-adding an existing address with a new weight changes it and\n * a `remove` entry drops it.\n *\n * First of the `qi/governance.*` action family. Flow-panel reference:\n * `MembershipComposerStep` in impacts-x-web's PodSim FlowStepActionPane.\n *\n * @inputs\n * - coreAddress: DAO core contract address. TODO(governance): when empty in\n * flow mode, derive the current entity's governance group core address\n * (getEntityDid → getDAOGroups) instead of requiring it in template config.\n * - operation: 'add' | 'remove' | 'update-weight'\n * - members: Array<{ address: string; weight?: number }>\n * - title / description: optional; sensible defaults derived per operation.\n */\n\ntype GovernanceMemberOperation = 'add' | 'remove' | 'update-weight';\n\nconst VALID_OPERATIONS: GovernanceMemberOperation[] = ['add', 'remove', 'update-weight'];\n\ninterface RawMember {\n address?: string;\n addr?: string;\n weight?: number | string;\n}\n\nfunction defaultTitle(operation: GovernanceMemberOperation, count: number): string {\n const noun = count === 1 ? 'member' : 'members';\n switch (operation) {\n case 'add':\n return `Add ${count} ${noun}`;\n case 'remove':\n return `Remove ${count} ${noun}`;\n case 'update-weight':\n return `Update voting power for ${count} ${noun}`;\n }\n}\n\nregisterAction({\n type: 'qi/governance.member-proposal',\n can: 'governance/member-proposal',\n sideEffect: true,\n proof: { fields: ['proposalId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n inputSchema: governanceInputSchema('qi/governance.member-proposal'),\n\n outputSchema: [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'proposalTitle', displayName: 'Proposal Title', type: 'string', description: 'The proposal name voters see on-chain' },\n { path: 'proposalDescription', displayName: 'Proposal Description', type: 'string', description: 'The long-form description voters see on-chain' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'operation', displayName: 'Operation', type: 'string', description: 'add | remove | update-weight' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n ],\n\n // Mirrors run()'s throw-preamble (there is no inputSchema to declare\n // requiredness on): coreAddress, operation and a non-empty members list.\n getMissingInputs: (inputs) => {\n const missing: string[] = [];\n if (!String(inputs.coreAddress || '').trim()) missing.push('coreAddress');\n if (!String(inputs.operation || '').trim()) missing.push('operation');\n if (!Array.isArray(inputs.members) || inputs.members.length === 0) missing.push('members');\n return missing;\n },\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.getPreProposalContractAddress || !handlers.getGroupContractAddress || !handlers.getProposalContractAddress || !handlers.createProposal) {\n throw new Error('Governance proposal handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n // TODO(governance): when coreAddress is empty in flow mode, resolve the\n // current entity's governance group core address rather than throwing.\n if (!coreAddress) throw new Error('coreAddress is required');\n\n const operation = String(inputs.operation || '').trim() as GovernanceMemberOperation;\n if (!VALID_OPERATIONS.includes(operation)) {\n throw new Error(`operation must be one of: ${VALID_OPERATIONS.join(', ')}`);\n }\n\n const rawMembers: RawMember[] = Array.isArray(inputs.members) ? inputs.members : [];\n if (rawMembers.length === 0) throw new Error('At least one member is required');\n\n const normalized = rawMembers.map((m) => ({\n addr: String(m.address || m.addr || '').trim(),\n weight: Number(m.weight ?? 0),\n }));\n if (normalized.some((m) => !m.addr)) throw new Error('Every member needs an address');\n\n const addrs = normalized.map((m) => m.addr);\n if (new Set(addrs).size !== addrs.length) throw new Error('Duplicate member addresses are not allowed');\n\n // cw4 update_members upserts by address:\n // add / update-weight → { addr, weight } entries (existing addr + new weight = change)\n // remove → { addr } entries\n let add: Array<{ addr: string; weight: number }> = [];\n let remove: Array<{ addr: string }> = [];\n\n if (operation === 'remove') {\n remove = normalized.map((m) => ({ addr: m.addr }));\n } else {\n if (normalized.some((m) => !Number.isFinite(m.weight) || m.weight <= 0)) {\n throw new Error('Voting power must be a positive number');\n }\n add = normalized.map((m) => ({ addr: m.addr, weight: Math.trunc(m.weight) }));\n }\n\n const title = String(inputs.title || '').trim() || defaultTitle(operation, normalized.length);\n const description = String(inputs.description || '').trim() || title;\n\n const updateMembersAction = { type: 'UpdateMembers', data: { add, remove } };\n\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({ coreAddress });\n const { groupContractAddress } = await handlers.getGroupContractAddress({ coreAddress });\n const { proposalContractAddress } = await handlers.getProposalContractAddress({ coreAddress });\n\n const proposalId = await handlers.createProposal({\n preProposalContractAddress,\n title,\n description,\n actions: [updateMembersAction],\n coreAddress,\n groupContractAddress,\n });\n\n // Proof guard: a proposal id is the contract that the consumer must return\n // when the proposal was actually broadcast. No id → treat as a failure.\n if (proposalId === undefined || proposalId === null || String(proposalId).trim() === '') {\n throw new Error('Proposal creation returned no proposal id. Check the handler logs.');\n }\n\n return {\n output: {\n proposalId: String(proposalId),\n proposalTitle: title,\n proposalDescription: description,\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n operation,\n createdAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { governanceInputSchema } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that updates a DAO DAO\n * POD's voting rules: voting period, quorum, pass threshold, and whether\n * members may change their vote while voting is open.\n * Maps onto a single `UpdateVotingConfig` proposal action — once the proposal\n * passes, the voting module's config is replaced.\n *\n * Second of the `qi/governance.*` action family. Flow-panel reference:\n * `GovernanceComposerStep` in impacts-x-web's PodSim FlowStepActionPane.\n *\n * @inputs\n * - coreAddress: DAO core contract address. TODO(governance): when empty in\n * flow mode, derive the current entity's governance group core address.\n * - votingPeriodHours: voting window in hours.\n * - quorumPercent / thresholdPercent: 0–100.\n * - allowRevoting: boolean.\n * - title / description: optional; sensible defaults.\n *\n * A veto threshold is intentionally not an input: the deployed\n * dao_proposal_single contract has no veto config, so one can never reach\n * the chain. Any `vetoThresholdPercent` supplied by older templates is\n * ignored.\n */\n\nfunction clampPercent(value: unknown, label: string, { allowZero = false } = {}): number {\n const n = Number(value);\n if (!Number.isFinite(n)) throw new Error(`${label} must be a number`);\n if (n < 0 || n > 100) throw new Error(`${label} must be between 0 and 100`);\n if (!allowZero && n <= 0) throw new Error(`${label} must be greater than 0`);\n return n;\n}\n\nregisterAction({\n type: 'qi/governance.settings-proposal',\n can: 'governance/settings-proposal',\n sideEffect: true,\n proof: { fields: ['proposalId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n inputSchema: governanceInputSchema('qi/governance.settings-proposal'),\n\n outputSchema: [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'proposalTitle', displayName: 'Proposal Title', type: 'string', description: 'The proposal name voters see on-chain' },\n { path: 'proposalDescription', displayName: 'Proposal Description', type: 'string', description: 'The long-form description voters see on-chain' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n ],\n\n // Mirrors run()'s throw-preamble (there is no inputSchema to declare\n // requiredness on): coreAddress and the three numeric voting settings.\n getMissingInputs: (inputs) => {\n const missing: string[] = [];\n if (!String(inputs.coreAddress || '').trim()) missing.push('coreAddress');\n for (const name of ['votingPeriodHours', 'quorumPercent', 'thresholdPercent']) {\n const value = inputs[name];\n if (value === undefined || value === null || String(value).trim() === '') missing.push(name);\n }\n return missing;\n },\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.getPreProposalContractAddress || !handlers.getGroupContractAddress || !handlers.getProposalContractAddress || !handlers.createProposal) {\n throw new Error('Governance proposal handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n // TODO(governance): when coreAddress is empty in flow mode, resolve the\n // current entity's governance group core address rather than throwing.\n if (!coreAddress) throw new Error('coreAddress is required');\n\n const votingPeriodHours = Number(inputs.votingPeriodHours);\n if (!Number.isFinite(votingPeriodHours) || votingPeriodHours <= 0) {\n throw new Error('votingPeriodHours must be a positive number');\n }\n\n const quorumPercent = clampPercent(inputs.quorumPercent, 'quorumPercent', { allowZero: true });\n const thresholdPercent = clampPercent(inputs.thresholdPercent, 'thresholdPercent');\n\n const allowRevoting = Boolean(inputs.allowRevoting);\n\n const data = {\n // Group creation instantiates the proposal module with\n // only_members_execute: true — preserve that policy on updates.\n onlyMembersExecute: true,\n thresholdType: '%' as const,\n thresholdPercentage: thresholdPercent,\n quorumEnabled: quorumPercent > 0,\n quorumType: '%' as const,\n quorumPercentage: quorumPercent,\n proposalDuration: Math.trunc(votingPeriodHours),\n proposalDurationUnits: 'hours' as const,\n allowRevoting,\n };\n\n const updateVotingConfigAction = { type: 'UpdateVotingConfig', data };\n\n const title = String(inputs.title || '').trim() || 'Update governance settings';\n const description = String(inputs.description || '').trim() || \"Updates the POD's voting rules once the proposal passes.\";\n\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({ coreAddress });\n const { groupContractAddress } = await handlers.getGroupContractAddress({ coreAddress });\n const { proposalContractAddress } = await handlers.getProposalContractAddress({ coreAddress });\n\n const proposalId = await handlers.createProposal({\n preProposalContractAddress,\n title,\n description,\n actions: [updateVotingConfigAction],\n coreAddress,\n groupContractAddress,\n });\n\n // Proof guard: a proposal id is the contract the consumer must return when\n // the proposal was actually broadcast. No id → treat as a failure.\n if (proposalId === undefined || proposalId === null || String(proposalId).trim() === '') {\n throw new Error('Proposal creation returned no proposal id. Check the handler logs.');\n }\n\n return {\n output: {\n proposalId: String(proposalId),\n proposalTitle: title,\n proposalDescription: description,\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n createdAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that updates a DAO DAO\n * group's proposal submission rules: whether anyone (vs members only) may\n * submit proposals, and the deposit required with each submission. Maps\n * onto a single `UpdatePreProposeConfig` proposal action — the consumer\n * turns it into an `update_config` execute on the pre-propose module.\n *\n * The on-chain update replaces BOTH fields at once. Groups are created\n * members-only, so `anyoneCanPropose` defaults to false — updating the\n * deposit must never silently open submission to everyone (see the legacy\n * proposal block's actionRegistry for the same policy).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - anyoneCanPropose: whether non-members may submit proposals.\n * - depositRequired: whether a deposit is required to submit a proposal.\n * - depositAmount: deposit in uixo base units (the UI collects whole IXO\n * and converts; the deposit token is fixed to native uixo for now).\n * - depositRefundPolicy: 'always' | 'only_passed' | 'never'.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\nconst REFUND_POLICIES = ['always', 'only_passed', 'never'] as const;\ntype RefundPolicy = (typeof REFUND_POLICIES)[number];\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.submission-config-proposal',\n can: 'governance/submission-config-proposal',\n\n buildActions: (inputs) => {\n const anyoneCanPropose = Boolean(inputs.anyoneCanPropose);\n const depositRequired = Boolean(inputs.depositRequired);\n\n let amount = '0';\n let refundPolicy: RefundPolicy = 'always';\n if (depositRequired) {\n amount = String(inputs.depositAmount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('depositAmount must be a positive whole number in uixo base units');\n }\n const policy = String(inputs.depositRefundPolicy || '').trim();\n if (!REFUND_POLICIES.includes(policy as RefundPolicy)) {\n throw new Error(\"depositRefundPolicy must be one of 'always', 'only_passed' or 'never'\");\n }\n refundPolicy = policy as RefundPolicy;\n }\n\n return [\n {\n type: 'UpdatePreProposeConfig',\n data: {\n depositRequired,\n // Deposit token fixed to the chain's native IXO (uixo) for now.\n depositInfo: { amount, type: 'native', denomOrAddress: 'uixo', refundPolicy },\n anyoneCanPropose,\n },\n },\n ];\n },\n\n defaultTitle: () => 'Update proposal submission rules',\n defaultDescription: () => 'Updates who may submit proposals and the required deposit once the proposal passes.',\n\n buildExtraOutput: (inputs) => {\n const depositRequired = Boolean(inputs.depositRequired);\n return {\n anyoneCanPropose: String(Boolean(inputs.anyoneCanPropose)),\n depositRequired: String(depositRequired),\n depositAmount: depositRequired ? String(inputs.depositAmount || '') : '0',\n depositRefundPolicy: depositRequired ? String(inputs.depositRefundPolicy || '') : 'always',\n };\n },\n extraOutputSchema: [\n { path: 'anyoneCanPropose', displayName: 'Anyone Can Propose', type: 'string', description: 'Whether non-members may submit proposals after the update' },\n { path: 'depositRequired', displayName: 'Deposit Required', type: 'string', description: 'Whether a deposit is required to submit a proposal' },\n { path: 'depositAmount', displayName: 'Deposit Amount', type: 'string', description: 'Required deposit in uixo base units' },\n { path: 'depositRefundPolicy', displayName: 'Deposit Refund Policy', type: 'string', description: 'What happens to the deposit after voting ends' },\n ],\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { governanceInputSchema } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that sends funds from a\n * DAO DAO POD's treasury to a recipient address. Maps onto a single\n * `Spend` proposal action — once the proposal passes, the treasury transfers\n * the funds.\n *\n * First of the `qi/governance.transaction.*` sub-family (treasury / asset\n * transactions; more coming — send-nft, swap, stake, …). Flow-panel\n * reference: `TransactionComposerStep` in impacts-x-web's PodSim\n * FlowStepActionPane, narrowed here to the only thing it does today: send\n * funds.\n *\n * @inputs\n * - coreAddress: DAO core contract address. TODO(governance): when empty in\n * flow mode, derive the current entity's governance group core address.\n * - recipient: bech32 (ixo1…) destination address.\n * - denom: token denom to send (from the treasury balances). Only denoms\n * with a known exponent are accepted (currently uixo/IXO) so the display\n * amount can be converted to base units correctly.\n * - amount: number to send, in the token's display units.\n * - title / description: optional; sensible defaults.\n */\nregisterAction({\n type: 'qi/governance.transaction.send-funds',\n can: 'governance.transaction/send-funds',\n sideEffect: true,\n proof: { fields: ['proposalId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n inputSchema: governanceInputSchema('qi/governance.transaction.send-funds'),\n\n outputSchema: [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'proposalTitle', displayName: 'Proposal Title', type: 'string', description: 'The proposal name voters see on-chain' },\n { path: 'proposalDescription', displayName: 'Proposal Description', type: 'string', description: 'The long-form description voters see on-chain' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'recipient', displayName: 'Recipient', type: 'string', description: 'Destination address of the spend' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n ],\n\n // Mirrors run()'s throw-preamble (there is no inputSchema to declare\n // requiredness on): coreAddress, recipient, denom and amount.\n getMissingInputs: (inputs) => {\n const missing: string[] = [];\n for (const name of ['coreAddress', 'recipient', 'denom']) {\n if (!String(inputs[name] || '').trim()) missing.push(name);\n }\n const amount = inputs.amount;\n if (amount === undefined || amount === null || String(amount).trim() === '') missing.push('amount');\n return missing;\n },\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.getPreProposalContractAddress || !handlers.getGroupContractAddress || !handlers.getProposalContractAddress || !handlers.createProposal) {\n throw new Error('Governance proposal handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n // TODO(governance): when coreAddress is empty in flow mode, resolve the\n // current entity's governance group core address rather than throwing.\n if (!coreAddress) throw new Error('coreAddress is required');\n\n const recipient = String(inputs.recipient || '').trim();\n if (!recipient) throw new Error('recipient is required');\n\n const denom = String(inputs.denom || '').trim();\n if (!denom) throw new Error('denom is required');\n\n const amount = Number(inputs.amount);\n if (!Number.isFinite(amount) || amount <= 0) throw new Error('amount must be greater than 0');\n\n // The Spend message needs the amount in the token's smallest unit\n // (1 IXO = 1,000,000 uixo). The input is in display units, so convert\n // using the denom's exponent — and refuse denoms whose exponent we don't\n // know rather than sending a silently wrong amount.\n const KNOWN_DENOMS: Record<string, { symbol: string; exponent: number }> = {\n uixo: { symbol: 'IXO', exponent: 6 },\n };\n const tokenInfo = KNOWN_DENOMS[denom];\n if (!tokenInfo) {\n throw new Error(`Sending ${denom} is not supported yet — only IXO transfers are currently available`);\n }\n const baseAmount = BigInt(Math.round(amount * 10 ** tokenInfo.exponent)).toString();\n\n const spendAction = { type: 'Spend', data: { to: recipient, denom, amount: baseAmount } };\n\n const title = String(inputs.title || '').trim() || `Send ${amount} ${tokenInfo.symbol} to ${recipient}`;\n const description = String(inputs.description || '').trim() || 'Sends funds from the POD treasury once the proposal passes.';\n\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({ coreAddress });\n const { groupContractAddress } = await handlers.getGroupContractAddress({ coreAddress });\n const { proposalContractAddress } = await handlers.getProposalContractAddress({ coreAddress });\n\n const proposalId = await handlers.createProposal({\n preProposalContractAddress,\n title,\n description,\n actions: [spendAction],\n coreAddress,\n groupContractAddress,\n });\n\n // Proof guard: a proposal id is the contract the consumer must return when\n // the proposal was actually broadcast. No id → treat as a failure.\n if (proposalId === undefined || proposalId === null || String(proposalId).trim() === '') {\n throw new Error('Proposal creation returned no proposal id. Check the handler logs.');\n }\n\n return {\n output: {\n proposalId: String(proposalId),\n proposalTitle: title,\n proposalDescription: description,\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n recipient,\n createdAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that transfers cw20\n * group tokens held by the DAO treasury to a recipient. Maps onto a single\n * `SendGroupToken` proposal action — the consumer turns it into a cw20\n * `transfer` execute on the token contract.\n *\n * Part of the `qi/governance.transaction.*` sub-family (treasury / asset\n * transactions).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - tokenContract: cw20 token contract address to transfer from.\n * - recipient: bech32 (ixo1…) destination address.\n * - amount: token amount in the token's base units (cw20 amounts are raw\n * integer strings; exponent varies per token, so no display conversion).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.transaction.send-group-token',\n can: 'governance.transaction/send-group-token',\n\n buildActions: (inputs) => {\n const contract = String(inputs.tokenContract || '').trim();\n if (!contract) throw new Error('tokenContract is required');\n\n const toAddress = String(inputs.recipient || '').trim();\n if (!toAddress) throw new Error('recipient is required');\n\n const amount = String(inputs.amount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('amount must be a positive whole number in the token’s base units');\n }\n\n return [{ type: 'SendGroupToken', data: { contract, toAddress, amount } }];\n },\n\n defaultTitle: (inputs) => `Send ${inputs.amount} group tokens to ${inputs.recipient}`,\n defaultDescription: () => 'Transfers group tokens from the treasury once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ recipient: String(inputs.recipient || ''), tokenContract: String(inputs.tokenContract || '') }),\n extraOutputSchema: [\n { path: 'recipient', displayName: 'Recipient', type: 'string', description: 'Destination address of the transfer' },\n { path: 'tokenContract', displayName: 'Token Contract', type: 'string', description: 'The cw20 token contract transferred from' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that mints new\n * governance tokens to a recipient. Maps onto a single `Mint` proposal\n * action — the consumer turns it into a cw20 `mint` execute on the group's\n * governance token contract, so it only works for groups with a governance\n * token (token-staking groups, not member-weight groups).\n *\n * Part of the `qi/governance.transaction.*` sub-family (treasury / asset\n * transactions).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - recipient: bech32 (ixo1…) destination address the tokens are minted to.\n * - amount: amount to mint in the governance token's base units (cw20 mint\n * amounts are raw integer strings; exponent varies per token, so no\n * display conversion).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.transaction.mint',\n can: 'governance.transaction/mint',\n\n buildActions: (inputs) => {\n const to = String(inputs.recipient || '').trim();\n if (!to) throw new Error('recipient is required');\n\n // The consumer feeds this straight into a cw20 `mint` execute\n // (`action.data.amount.toString()`), which requires a raw integer string\n // in the token's base units — a float or exponent-notation number would\n // produce an invalid message.\n const amount = String(inputs.amount ?? '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('amount must be a positive whole number in the token’s base units');\n }\n\n return [{ type: 'Mint', data: { to, amount } }];\n },\n\n defaultTitle: (inputs) => `Mint ${inputs.amount} governance tokens to ${inputs.recipient}`,\n defaultDescription: () => 'Mints new governance tokens to the recipient once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ recipient: String(inputs.recipient || ''), amount: String(inputs.amount || '') }),\n extraOutputSchema: [\n { path: 'recipient', displayName: 'Recipient', type: 'string', description: 'Destination address the tokens are minted to' },\n { path: 'amount', displayName: 'Amount', type: 'string', description: 'Number of governance tokens minted' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that funds the group's\n * side of a cw-token-swap contract. Maps onto a single `PerformTokenSwap`\n * proposal action — the consumer turns it into a `provide` execute (native\n * funds attached, or a cw20 `send`) on the swap contract.\n *\n * Part of the `qi/governance.transaction.*` sub-family (treasury / asset\n * transactions).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - tokenSwapContractAddress: the cw-token-swap contract to fund.\n * - selfPartyType: what the group provides — 'native' or 'cw20'.\n * - selfPartyDenomOrAddress: the native denom (e.g. uixo) or cw20 token\n * contract address of the provided token.\n * - selfPartyAmount: amount in the token's base units (raw integer string;\n * exponent varies per token, so no display conversion).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.transaction.perform-token-swap',\n can: 'governance.transaction/perform-token-swap',\n\n buildActions: (inputs) => {\n const tokenSwapContractAddress = String(inputs.tokenSwapContractAddress || '').trim();\n if (!tokenSwapContractAddress) throw new Error('tokenSwapContractAddress is required');\n\n const type = String(inputs.selfPartyType || '').trim();\n if (type !== 'native' && type !== 'cw20') throw new Error(\"selfPartyType must be 'native' or 'cw20'\");\n\n const denomOrAddress = String(inputs.selfPartyDenomOrAddress || '').trim();\n if (!denomOrAddress) throw new Error('selfPartyDenomOrAddress is required');\n\n const amount = String(inputs.selfPartyAmount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('selfPartyAmount must be a positive whole number in the token’s base units');\n }\n\n return [\n {\n type: 'PerformTokenSwap',\n data: { contractChosen: true, tokenSwapContractAddress, selfParty: { type, denomOrAddress, amount } },\n },\n ];\n },\n\n defaultTitle: (inputs) => `Fund token swap ${inputs.tokenSwapContractAddress}`,\n defaultDescription: () => 'Sends the group’s side of the token swap to the swap contract once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n tokenSwapContractAddress: String(inputs.tokenSwapContractAddress || ''),\n selfPartyDenomOrAddress: String(inputs.selfPartyDenomOrAddress || ''),\n selfPartyAmount: String(inputs.selfPartyAmount || ''),\n }),\n extraOutputSchema: [\n { path: 'tokenSwapContractAddress', displayName: 'Swap Contract', type: 'string', description: 'The cw-token-swap contract funded' },\n { path: 'selfPartyDenomOrAddress', displayName: 'Token Denom / Address', type: 'string', description: 'The native denom or cw20 address the group provides' },\n { path: 'selfPartyAmount', displayName: 'Amount', type: 'string', description: 'Amount provided, in the token’s base units' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that withdraws the\n * group's funds from a cw-token-swap contract before the counterparty pays\n * in. Maps onto a single `WithdrawTokenSwap` proposal action — the consumer\n * turns it into a `withdraw` execute on the swap contract.\n *\n * Part of the `qi/governance.transaction.*` sub-family (treasury / asset\n * transactions).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - tokenSwapContractAddress: the cw-token-swap contract to withdraw from.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.transaction.withdraw-token-swap',\n can: 'governance.transaction/withdraw-token-swap',\n\n buildActions: (inputs) => {\n const tokenSwapContractAddress = String(inputs.tokenSwapContractAddress || '').trim();\n if (!tokenSwapContractAddress) throw new Error('tokenSwapContractAddress is required');\n\n return [{ type: 'WithdrawTokenSwap', data: { contractChosen: true, tokenSwapContractAddress } }];\n },\n\n defaultTitle: (inputs) => `Withdraw from token swap ${inputs.tokenSwapContractAddress}`,\n defaultDescription: () => 'Returns the group’s funds from the token swap contract once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ tokenSwapContractAddress: String(inputs.tokenSwapContractAddress || '') }),\n extraOutputSchema: [{ path: 'tokenSwapContractAddress', displayName: 'Swap Contract', type: 'string', description: 'The cw-token-swap contract withdrawn from' }],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that stakes the group\n * treasury's IXO with a validator — or unstakes, restakes and claims\n * rewards. Maps onto a single `Stake` proposal action — the consumer turns\n * it into the matching cosmos message (MsgDelegate, MsgUndelegate,\n * MsgBeginRedelegate or MsgWithdrawDelegatorReward) signed by the DAO core.\n *\n * Part of the `qi/governance.staking.*` sub-family (treasury staking).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - stakeType: the operation — delegate, undelegate, redelegate or\n * withdraw_delegator_reward (values match the legacy `StakeType` enum).\n * - validator: validator operator (ixovaloper1…) address; the source\n * validator for redelegations.\n * - toValidator: destination validator address (redelegations only).\n * - amount: uixo amount in base units (1 IXO = 1,000,000 uixo; the UI\n * collects IXO display units and converts). Ignored for reward claims.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\nconst STAKE_TYPES = ['delegate', 'undelegate', 'redelegate', 'withdraw_delegator_reward'] as const;\n\n/** uixo base units → IXO display units, for the default proposal title. */\nconst displayIxo = (amount: unknown): string => {\n const base = Number(amount);\n return Number.isFinite(base) ? String(base / 1e6) : String(amount || '');\n};\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.staking.stake',\n can: 'governance.staking/stake',\n\n buildActions: (inputs) => {\n const stakeType = String(inputs.stakeType || '').trim();\n if (!STAKE_TYPES.includes(stakeType as (typeof STAKE_TYPES)[number])) {\n throw new Error('stakeType must be delegate, undelegate, redelegate or withdraw_delegator_reward');\n }\n\n const validator = String(inputs.validator || '').trim();\n if (!validator) throw new Error('validator is required');\n\n const isRedelegate = stakeType === 'redelegate';\n const toValidator = String(inputs.toValidator || '').trim();\n if (isRedelegate && !toValidator) throw new Error('toValidator is required for redelegations');\n\n // Reward claims carry no amount; every other operation needs a positive\n // whole number of uixo (the UI converts from IXO display units).\n let amount = '0';\n if (stakeType !== 'withdraw_delegator_reward') {\n amount = String(inputs.amount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('amount must be a positive whole number of uixo (base units)');\n }\n }\n\n return [{ type: 'Stake', data: { stakeType, validator, toValidator: isRedelegate ? toValidator : '', amount, denom: 'uixo' } }];\n },\n\n // buildActions runs first, so the stake type is always a valid option here.\n defaultTitle: (inputs) => {\n switch (String(inputs.stakeType)) {\n case 'undelegate':\n return `Unstake ${displayIxo(inputs.amount)} IXO from ${inputs.validator}`;\n case 'redelegate':\n return `Restake ${displayIxo(inputs.amount)} IXO from ${inputs.validator} to ${inputs.toValidator}`;\n case 'withdraw_delegator_reward':\n return `Claim staking rewards from ${inputs.validator}`;\n default:\n return `Stake ${displayIxo(inputs.amount)} IXO with ${inputs.validator}`;\n }\n },\n defaultDescription: () => 'Executes the staking operation from the POD treasury once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n stakeType: String(inputs.stakeType || ''),\n validator: String(inputs.validator || ''),\n amount: String(inputs.amount || ''),\n }),\n extraOutputSchema: [\n { path: 'stakeType', displayName: 'Stake Type', type: 'string', description: 'The staking operation (delegate, undelegate, redelegate, withdraw_delegator_reward)' },\n { path: 'validator', displayName: 'Validator', type: 'string', description: 'The validator the operation targets (source for redelegations)' },\n { path: 'amount', displayName: 'Amount', type: 'string', description: 'The uixo amount staked, in base units' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that stakes cw20 tokens\n * held by the DAO treasury into a group's staking contract. Maps onto a\n * single `StakeToGroup` proposal action — the consumer turns it into a cw20\n * `send` execute on the token contract with an embedded `{stake:{}}` hook\n * the staking contract runs on receipt.\n *\n * Part of the `qi/governance.staking.*` sub-family (treasury staking).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - tokenContract: cw20 token contract address the tokens are sent from.\n * - stakingContract: cw20-stake staking contract that receives the tokens.\n * - amount: token amount in the token's base units (cw20 amounts are raw\n * integer strings; exponent varies per token, so no display conversion).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.staking.stake-to-group',\n can: 'governance.staking/stake-to-group',\n\n buildActions: (inputs) => {\n const tokenContract = String(inputs.tokenContract || '').trim();\n if (!tokenContract) throw new Error('tokenContract is required');\n\n const stakingContract = String(inputs.stakingContract || '').trim();\n if (!stakingContract) throw new Error('stakingContract is required');\n\n const amount = String(inputs.amount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('amount must be a positive whole number in the token’s base units');\n }\n\n return [{ type: 'StakeToGroup', data: { tokenContract, stakingContract, amount } }];\n },\n\n defaultTitle: (inputs) => `Stake ${inputs.amount} tokens to the group`,\n defaultDescription: () => 'Stakes treasury tokens into the group staking contract once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ tokenContract: String(inputs.tokenContract || ''), stakingContract: String(inputs.stakingContract || '') }),\n extraOutputSchema: [\n { path: 'tokenContract', displayName: 'Token Contract', type: 'string', description: 'The cw20 token contract the tokens are sent from' },\n { path: 'stakingContract', displayName: 'Staking Contract', type: 'string', description: 'The staking contract the tokens are staked into' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that grants an address\n * authorization to execute a message type on the POD's behalf. Maps onto\n * a single `AuthzGrant` proposal action — the consumer builds a\n * `GenericAuthorization` for the message type with a 1-year expiry, with\n * the group as the granter.\n *\n * Part of the `qi/governance.authz.*` sub-family (authorizations).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - grantee: bech32 (ixo1…) address that receives the authorization.\n * - msgTypeUrl: fully-qualified message type URL the grantee may execute,\n * e.g. `/cosmos.bank.v1beta1.MsgSend`.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.authz.grant',\n can: 'governance.authz/grant',\n\n buildActions: (inputs) => {\n const grantee = String(inputs.grantee || '').trim();\n if (!grantee) throw new Error('grantee is required');\n\n const msgTypeUrl = String(inputs.msgTypeUrl || '').trim();\n if (!msgTypeUrl) throw new Error('msgTypeUrl is required');\n if (!msgTypeUrl.startsWith('/')) {\n throw new Error('msgTypeUrl must be a fully-qualified message type URL starting with \"/\"');\n }\n\n return [{ type: 'AuthzGrant', data: { typeUrl: '/cosmos.authz.v1beta1.MsgGrant', value: { grantee, msgTypeUrl } } }];\n },\n\n defaultTitle: (inputs) => `Grant ${inputs.msgTypeUrl} authorization to ${inputs.grantee}`,\n defaultDescription: () => 'Authorizes the grantee to execute the message type on the group’s behalf (1-year expiry) once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ grantee: String(inputs.grantee || ''), msgTypeUrl: String(inputs.msgTypeUrl || '') }),\n extraOutputSchema: [\n { path: 'grantee', displayName: 'Grantee', type: 'string', description: 'Address that receives the authorization' },\n { path: 'msgTypeUrl', displayName: 'Message Type URL', type: 'string', description: 'The message type the grantee may execute' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that revokes a\n * previously granted authorization from an address. Maps onto a single\n * `AuthzRevoke` proposal action — the consumer turns it into a\n * `MsgRevoke` for the message type, with the group as the granter.\n *\n * Part of the `qi/governance.authz.*` sub-family (authorizations).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - grantee: bech32 (ixo1…) address whose authorization is revoked.\n * - msgTypeUrl: fully-qualified message type URL of the grant to revoke,\n * e.g. `/cosmos.bank.v1beta1.MsgSend`.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.authz.revoke',\n can: 'governance.authz/revoke',\n\n buildActions: (inputs) => {\n const grantee = String(inputs.grantee || '').trim();\n if (!grantee) throw new Error('grantee is required');\n\n const msgTypeUrl = String(inputs.msgTypeUrl || '').trim();\n if (!msgTypeUrl) throw new Error('msgTypeUrl is required');\n if (!msgTypeUrl.startsWith('/')) {\n throw new Error('msgTypeUrl must be a fully-qualified message type URL starting with \"/\"');\n }\n\n return [{ type: 'AuthzRevoke', data: { typeUrl: '/cosmos.authz.v1beta1.MsgRevoke', value: { grantee, msgTypeUrl } } }];\n },\n\n defaultTitle: (inputs) => `Revoke ${inputs.msgTypeUrl} authorization from ${inputs.grantee}`,\n defaultDescription: () => 'Revokes the grantee’s authorization to execute the message type on the group’s behalf once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ grantee: String(inputs.grantee || ''), msgTypeUrl: String(inputs.msgTypeUrl || '') }),\n extraOutputSchema: [\n { path: 'grantee', displayName: 'Grantee', type: 'string', description: 'Address whose authorization is revoked' },\n { path: 'msgTypeUrl', displayName: 'Message Type URL', type: 'string', description: 'The message type of the revoked grant' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that makes the group\n * execute a message it was previously authorized to run (authz exec). Maps\n * onto a single `AuthzExec` proposal action whose data matches the legacy\n * `AuthzExecData` shape — the consumer turns the selected sub-object into a\n * `MsgExec`-wrapped staking / distribution / custom message.\n *\n * Part of the `qi/governance.authz.*` sub-family (authorizations).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - authzExecActionType: one of the message type URLs below, or `custom`.\n * - delegatorAddress / validatorAddress: staking + claim-rewards ops.\n * - validatorDstAddress: redelegate destination validator.\n * - amount: staking amount in uixo base units (raw integer string).\n * - custom: raw JSON array of encoded msgs (custom mode only).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\n/**\n * Mirrors `AuthzExecActionTypes` in `src/mantine/context/types.ts` — the\n * exact type URLs the consumer's `transformActionsToMsgs` switches on. Kept\n * local so the core registry stays independent of the UI layer.\n */\nconst AUTHZ_EXEC_ACTION_TYPES = {\n delegate: '/cosmos.staking.v1beta1.MsgDelegate',\n undelegate: '/cosmos.staking.v1beta1.MsgUndelegate',\n redelegate: '/cosmos.staking.v1beta1.MsgBeginRedelegate',\n claimRewards: '/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward',\n custom: 'custom',\n} as const;\n\nconst ACTION_LABELS: Record<string, string> = {\n [AUTHZ_EXEC_ACTION_TYPES.delegate]: 'delegate',\n [AUTHZ_EXEC_ACTION_TYPES.undelegate]: 'undelegate',\n [AUTHZ_EXEC_ACTION_TYPES.redelegate]: 'redelegate',\n [AUTHZ_EXEC_ACTION_TYPES.claimRewards]: 'claim-rewards',\n [AUTHZ_EXEC_ACTION_TYPES.custom]: 'custom',\n};\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.authz.exec',\n can: 'governance.authz/exec',\n\n buildActions: (inputs) => {\n const actionType = String(inputs.authzExecActionType || '').trim();\n const known = Object.values(AUTHZ_EXEC_ACTION_TYPES) as string[];\n if (!known.includes(actionType)) {\n throw new Error(`authzExecActionType must be one of: ${known.join(', ')}`);\n }\n\n const delegator = String(inputs.delegatorAddress || '').trim();\n const validator = String(inputs.validatorAddress || '').trim();\n const validatorDst = String(inputs.validatorDstAddress || '').trim();\n const amount = String(inputs.amount || '').trim();\n\n const requireStakingFields = () => {\n if (!delegator) throw new Error('delegatorAddress is required');\n if (!validator) throw new Error('validatorAddress is required');\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('amount must be a positive whole number in uixo base units');\n }\n };\n\n // Build only the selected sub-object; the others stay empty objects like\n // the legacy proposal block's defaults so `AuthzExecData` stays complete.\n const data: Record<string, any> = {\n authzExecActionType: actionType,\n delegate: {},\n undelegate: {},\n redelegate: {},\n claimRewards: {},\n custom: '',\n };\n\n // The consumer protobuf-encodes the selected sub-object with cosmjs-types\n // (`encodeRawProtobufMsg`), whose generated encoders read camelCase field\n // names — snake_case keys (as the legacy form's placeholders suggested)\n // would encode empty messages.\n switch (actionType) {\n case AUTHZ_EXEC_ACTION_TYPES.delegate:\n requireStakingFields();\n data.delegate = { delegatorAddress: delegator, validatorAddress: validator, amount: { denom: 'uixo', amount } };\n break;\n case AUTHZ_EXEC_ACTION_TYPES.undelegate:\n requireStakingFields();\n data.undelegate = { delegatorAddress: delegator, validatorAddress: validator, amount: { denom: 'uixo', amount } };\n break;\n case AUTHZ_EXEC_ACTION_TYPES.redelegate:\n requireStakingFields();\n if (!validatorDst) throw new Error('validatorDstAddress is required');\n data.redelegate = { delegatorAddress: delegator, validatorSrcAddress: validator, validatorDstAddress: validatorDst, amount: { denom: 'uixo', amount } };\n break;\n case AUTHZ_EXEC_ACTION_TYPES.claimRewards:\n if (!delegator) throw new Error('delegatorAddress is required');\n if (!validator) throw new Error('validatorAddress is required');\n data.claimRewards = { delegatorAddress: delegator, validatorAddress: validator };\n break;\n case AUTHZ_EXEC_ACTION_TYPES.custom: {\n const custom = String(inputs.custom || '').trim();\n if (!custom) throw new Error('custom is required');\n let parsed: unknown;\n try {\n parsed = JSON.parse(custom);\n } catch {\n throw new Error('custom must be valid JSON');\n }\n if (!Array.isArray(parsed) || parsed.length === 0) {\n throw new Error('custom must be a non-empty JSON array of encoded msgs');\n }\n data.custom = custom;\n break;\n }\n }\n\n return [{ type: 'AuthzExec', data }];\n },\n\n defaultTitle: (inputs) => `Execute authorized ${ACTION_LABELS[String(inputs.authzExecActionType || '').trim()] || 'authz'} action`,\n defaultDescription: () => 'Executes a message the group was previously authorized to run once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n authzExecActionType: String(inputs.authzExecActionType || ''),\n validatorAddress: String(inputs.validatorAddress || ''),\n }),\n extraOutputSchema: [\n { path: 'authzExecActionType', displayName: 'Exec Action Type', type: 'string', description: 'The executed message type URL (or `custom`)' },\n { path: 'validatorAddress', displayName: 'Validator Address', type: 'string', description: 'The validator targeted by staking ops (empty for custom)' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that casts the group\n * treasury's vote on a COSMOS CHAIN governance proposal (cosmos.gov\n * MsgVote) — not a DAO proposal. Maps onto a single `GovernanceVote`\n * proposal action — the consumer turns it into a MsgVote signed by the DAO\n * core once the proposal passes.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - proposalId: chain governance proposal number (digits).\n * - vote: cosmos.gov vote option number — 1 = Yes, 2 = Abstain, 3 = No,\n * 4 = No with veto.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\nconst VOTE_LABELS: Record<number, string> = { 1: 'Yes', 2: 'Abstain', 3: 'No', 4: 'No with veto' };\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.chain-governance-vote',\n can: 'governance/chain-governance-vote',\n\n buildActions: (inputs) => {\n const proposalId = String(inputs.proposalId || '').trim();\n if (!/^\\d+$/.test(proposalId)) {\n throw new Error('proposalId must be a chain governance proposal number (digits only)');\n }\n\n const vote = Number(inputs.vote);\n if (!VOTE_LABELS[vote]) {\n throw new Error('vote must be 1 (Yes), 2 (Abstain), 3 (No) or 4 (No with veto)');\n }\n\n return [{ type: 'GovernanceVote', data: { proposalId, vote } }];\n },\n\n // buildActions runs first, so the vote is always a valid option here.\n defaultTitle: (inputs) => `Vote ${VOTE_LABELS[Number(inputs.vote)]} on chain governance proposal #${inputs.proposalId}`,\n defaultDescription: () => \"Casts the group's vote on the chain governance proposal once this proposal passes.\",\n\n buildExtraOutput: (inputs) => ({\n chainProposalId: String(inputs.proposalId || ''),\n voteOption: VOTE_LABELS[Number(inputs.vote)] || String(inputs.vote || ''),\n }),\n extraOutputSchema: [\n { path: 'chainProposalId', displayName: 'Chain Proposal ID', type: 'string', description: 'The chain governance proposal the POD votes on' },\n { path: 'voteOption', displayName: 'Vote Option', type: 'string', description: 'The vote cast (Yes, Abstain, No, No with veto)' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that links this group\n * as a member of another entity. Maps onto a single `Join` proposal action —\n * the consumer turns it into a `MsgAddLinkedEntity` that records the member\n * on the joined entity's IID document, signed by the group's core address.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode). Passed through as the Join action's\n * signer.\n * - entityDid: DID of the entity being joined.\n * - memberId: the member entity's DID/id recorded as the linked entity —\n * typically this group's own entity DID.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.join',\n can: 'governance.dao/join',\n\n buildActions: (inputs) => {\n const id = String(inputs.entityDid || '').trim();\n if (!id) throw new Error('entityDid is required');\n\n const address = String(inputs.memberId || '').trim();\n if (!address) throw new Error('memberId is required');\n\n // The factory validated coreAddress before calling buildActions; the Join\n // action records it as the signer of the MsgAddLinkedEntity.\n const coreAddress = String(inputs.coreAddress || '').trim();\n\n return [{ type: 'Join', data: { id, coreAddress, address } }];\n },\n\n defaultTitle: (inputs) => `Join entity ${inputs.entityDid}`,\n defaultDescription: (inputs) => `Links ${inputs.memberId} as a member of ${inputs.entityDid} once the proposal passes.`,\n\n buildExtraOutput: (inputs) => ({ entityDid: String(inputs.entityDid || ''), memberId: String(inputs.memberId || '') }),\n extraOutputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The entity the group joined' },\n { path: 'memberId', displayName: 'Member ID', type: 'string', description: 'The member DID/id recorded as the linked entity' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that updates the DAO's\n * public info. Maps onto a single `UpdateInfo` proposal action — the\n * consumer turns it into a dao_core `update_config` execute. The config is\n * replaced in full, so every field is submitted every time (the consumer\n * nulls an empty image_url).\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - name: the DAO's display name.\n * - daoDescription: the DAO's public description — distinct from the\n * proposal description voters read (that one only describes this change).\n * - imageUrl: optional logo/banner URL. Empty → nulled by the consumer.\n * - automaticallyAddCw20s / automaticallyAddCw721s: whether tokens/NFTs\n * received by the DAO are auto-registered in the treasury.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.update-info',\n can: 'governance.dao/update-info',\n\n buildActions: (inputs) => {\n const name = String(inputs.name || '').trim();\n if (!name) throw new Error('name is required');\n\n const daoDescription = String(inputs.daoDescription || '').trim();\n const imageUrl = String(inputs.imageUrl || '').trim();\n\n return [\n {\n type: 'UpdateInfo',\n data: {\n name,\n description: daoDescription,\n automatically_add_cw20s: inputs.automaticallyAddCw20s === true || inputs.automaticallyAddCw20s === 'true',\n automatically_add_cw721s: inputs.automaticallyAddCw721s === true || inputs.automaticallyAddCw721s === 'true',\n image_url: imageUrl || null,\n },\n },\n ];\n },\n\n defaultTitle: (inputs) => `Update DAO info to “${inputs.name}”`,\n defaultDescription: () => 'Replaces the DAO name, description, image and auto-add settings once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ daoName: String(inputs.name || '') }),\n extraOutputSchema: [{ path: 'daoName', displayName: 'DAO Name', type: 'string', description: 'The DAO display name the proposal sets' }],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that recognises or\n * removes SubDAOs of this DAO. Maps onto a single `ManageSubDaos` proposal\n * action — the consumer turns it into a dao_core `update_sub_daos` execute.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - toAdd: SubDAO core addresses to recognise (strings, or `{ addr }` /\n * `{ address }` objects from templated inputs).\n * - toRemove: SubDAO core addresses to remove, same accepted shapes.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\n/** Accept string entries or `{ addr }` / `{ address }` objects from templates. */\nfunction normalizeAddresses(value: unknown): string[] {\n return (Array.isArray(value) ? value : []).map((entry: any) => String(typeof entry === 'string' ? entry : entry?.addr || entry?.address || '').trim());\n}\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.manage-subdaos',\n can: 'governance.dao/manage-subdaos',\n\n buildActions: (inputs) => {\n const toAdd = normalizeAddresses(inputs.toAdd);\n const toRemove = normalizeAddresses(inputs.toRemove);\n\n if (toAdd.some((addr) => !addr) || toRemove.some((addr) => !addr)) {\n throw new Error('Every SubDAO entry needs an address');\n }\n if (toAdd.length + toRemove.length === 0) {\n throw new Error('Add or remove at least one SubDAO');\n }\n\n const all = [...toAdd, ...toRemove];\n if (new Set(all).size !== all.length) throw new Error('Duplicate SubDAO addresses are not allowed');\n\n // Note the asymmetric key names the consumer expects: additions use\n // `addr` (dao_core SubDao entries), removals use `address`.\n return [\n {\n type: 'ManageSubDaos',\n data: {\n toAdd: toAdd.map((addr) => ({ addr })),\n toRemove: toRemove.map((address) => ({ address })),\n },\n },\n ];\n },\n\n defaultTitle: (inputs) => {\n const added = normalizeAddresses(inputs.toAdd).length;\n const removed = normalizeAddresses(inputs.toRemove).length;\n return `Add ${added} and remove ${removed} SubDAOs`;\n },\n defaultDescription: () => 'Updates the set of SubDAOs this DAO recognises once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n addedCount: String(normalizeAddresses(inputs.toAdd).length),\n removedCount: String(normalizeAddresses(inputs.toRemove).length),\n }),\n extraOutputSchema: [\n { path: 'addedCount', displayName: 'SubDAOs Added', type: 'string', description: 'Number of SubDAOs the proposal recognises' },\n { path: 'removedCount', displayName: 'SubDAOs Removed', type: 'string', description: 'Number of SubDAOs the proposal removes' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that sets or removes a\n * key/value item in the DAO's on-chain storage. Maps onto a single\n * `ManageStorageItems` proposal action — the consumer turns it into a\n * dao_core `set_item` (setting) or `remove_item` execute.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - setting: true → set the item, false → remove it.\n * - key: the storage key.\n * - value: the value to store. Required when setting, ignored on remove.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.manage-storage',\n can: 'governance.dao/manage-storage',\n\n buildActions: (inputs) => {\n const setting = inputs.setting === true || inputs.setting === 'true';\n\n const key = String(inputs.key || '').trim();\n if (!key) throw new Error('key is required');\n\n const value = String(inputs.value || '').trim();\n if (setting && !value) throw new Error('value is required when setting a storage item');\n\n return [{ type: 'ManageStorageItems', data: { setting, key, value: setting ? value : '' } }];\n },\n\n defaultTitle: (inputs) => {\n const setting = inputs.setting === true || inputs.setting === 'true';\n return setting ? `Set storage item “${inputs.key}”` : `Remove storage item “${inputs.key}”`;\n },\n defaultDescription: () => \"Updates the DAO's on-chain key/value storage once the proposal passes.\",\n\n buildExtraOutput: (inputs) => ({\n storageKey: String(inputs.key || ''),\n storageAction: inputs.setting === true || inputs.setting === 'true' ? 'set' : 'remove',\n }),\n extraOutputSchema: [\n { path: 'storageKey', displayName: 'Storage Key', type: 'string', description: 'The storage key the proposal targets' },\n { path: 'storageAction', displayName: 'Storage Action', type: 'string', description: 'set | remove' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that executes arbitrary\n * messages on a SubDAO this group is the admin of. Maps onto a single\n * `DaoAdminExec` proposal action — the consumer turns it into an\n * `execute_admin_msgs` execute on the TARGET dao_core, so the action's\n * `coreAddress` is the SubDAO's core address, not this group's.\n *\n * Advanced block: the messages are raw CosmWasm/cosmos messages the SubDAO\n * executes verbatim.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: THIS group's DAO core contract address (blank → resolved\n * from the current entity in flow mode). The proposal is created here.\n * - targetCoreAddress: core address of the SubDAO the admin messages run on.\n * - msgs: JSON array of messages to execute (array, or a JSON string that\n * parses to one).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.admin-exec',\n can: 'governance.dao/admin-exec',\n\n buildActions: (inputs) => {\n const targetCoreAddress = String(inputs.targetCoreAddress || '').trim();\n if (!targetCoreAddress) throw new Error('targetCoreAddress is required');\n\n let msgs = inputs.msgs;\n if (typeof msgs === 'string') {\n try {\n msgs = JSON.parse(msgs);\n } catch {\n throw new Error('msgs must be valid JSON');\n }\n }\n if (!Array.isArray(msgs) || msgs.length === 0) {\n throw new Error('msgs must be a non-empty JSON array of messages');\n }\n\n // data.coreAddress is the TARGET SubDAO core the admin messages execute\n // on — the proposal itself lives on this group's core (inputs.coreAddress).\n return [{ type: 'DaoAdminExec', data: { coreAddress: targetCoreAddress, msgs } }];\n },\n\n defaultTitle: (inputs) => `Execute admin messages on ${inputs.targetCoreAddress}`,\n defaultDescription: () => 'Executes the listed admin messages on the target SubDAO once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ targetCoreAddress: String(inputs.targetCoreAddress || '') }),\n extraOutputSchema: [{ path: 'targetCoreAddress', displayName: 'Target Core Address', type: 'string', description: 'The SubDAO core address the admin messages execute on' }],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that accepts an entity\n * into the marketplace. Maps onto a single `AcceptToMarketplace` proposal\n * action — the consumer turns it into a `MsgUpdateEntityVerified` that marks\n * the entity verified. The group must be the entity's relayer node for the\n * message to succeed.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - did: DID of the entity to mark verified.\n * - relayerNodeDid: DID of the relayer node vouching for the entity.\n * - relayerNodeAddress: bech32 (ixo1…) address of the relayer node.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.accept-to-marketplace',\n can: 'governance.dao/accept-to-marketplace',\n\n buildActions: (inputs) => {\n const did = String(inputs.did || '').trim();\n if (!did) throw new Error('did is required');\n\n const relayerNodeDid = String(inputs.relayerNodeDid || '').trim();\n if (!relayerNodeDid) throw new Error('relayerNodeDid is required');\n\n const relayerNodeAddress = String(inputs.relayerNodeAddress || '').trim();\n if (!relayerNodeAddress) throw new Error('relayerNodeAddress is required');\n\n return [{ type: 'AcceptToMarketplace', data: { did, relayerNodeDid, relayerNodeAddress } }];\n },\n\n defaultTitle: (inputs) => `Accept ${inputs.did} to the marketplace`,\n defaultDescription: () => 'Marks the entity as verified on the marketplace once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ entityDid: String(inputs.did || ''), relayerNodeDid: String(inputs.relayerNodeDid || '') }),\n extraOutputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The entity marked verified' },\n { path: 'relayerNodeDid', displayName: 'Relayer Node DID', type: 'string', description: 'The relayer node vouching for the entity' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that broadcasts a raw\n * entity-creation message when it passes. Maps onto a single `CreateEntity`\n * proposal action — the consumer wraps it as a stargate message, typically\n * `/ixo.entity.v1beta1.MsgCreateEntity`.\n *\n * Advanced block: the message value is passed through verbatim, so the\n * author is responsible for a well-formed message body.\n *\n * Part of the `qi/governance.dao.*` sub-family (DAO management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - typeUrl: fully-qualified message type url. Defaults to\n * `/ixo.entity.v1beta1.MsgCreateEntity` when blank.\n * - value: the message body (JSON object, or a JSON string that parses to\n * one).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\nconst DEFAULT_TYPE_URL = '/ixo.entity.v1beta1.MsgCreateEntity';\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.dao.create-entity',\n can: 'governance.dao/create-entity',\n\n buildActions: (inputs) => {\n const typeUrl = String(inputs.typeUrl || '').trim() || DEFAULT_TYPE_URL;\n if (!typeUrl.startsWith('/')) throw new Error('typeUrl must be a fully-qualified message type url starting with “/”');\n\n let value = inputs.value;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value);\n } catch {\n throw new Error('value must be valid JSON');\n }\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('value must be a JSON object with the message fields');\n }\n\n return [{ type: 'CreateEntity', data: { typeUrl, value } }];\n },\n\n defaultTitle: () => 'Create entity',\n defaultDescription: (inputs) => `Broadcasts a ${String(inputs.typeUrl || '').trim() || DEFAULT_TYPE_URL} message once the proposal passes.`,\n\n buildExtraOutput: (inputs) => ({ typeUrl: String(inputs.typeUrl || '').trim() || DEFAULT_TYPE_URL }),\n extraOutputSchema: [{ path: 'typeUrl', displayName: 'Message Type URL', type: 'string', description: 'The stargate message type the proposal broadcasts' }],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that burns an NFT held\n * by the DAO treasury. Maps onto a single `BurnNft` proposal action — the\n * consumer turns it into a cw721 `burn` execute on the collection contract.\n *\n * Part of the `qi/governance.nft.*` sub-family (treasury NFT management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - collection: cw721 collection contract address holding the token.\n * - tokenId: id of the token to burn.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.nft.burn',\n can: 'governance.nft/burn',\n\n buildActions: (inputs) => {\n const collection = String(inputs.collection || '').trim();\n if (!collection) throw new Error('collection is required');\n\n const tokenId = String(inputs.tokenId || '').trim();\n if (!tokenId) throw new Error('tokenId is required');\n\n return [{ type: 'BurnNft', data: { collection, tokenId } }];\n },\n\n defaultTitle: (inputs) => `Burn NFT ${inputs.tokenId} from ${inputs.collection}`,\n defaultDescription: () => 'Permanently burns the NFT from the treasury once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ collection: String(inputs.collection || ''), tokenId: String(inputs.tokenId || '') }),\n extraOutputSchema: [\n { path: 'collection', displayName: 'Collection', type: 'string', description: 'The cw721 collection contract the token is burned from' },\n { path: 'tokenId', displayName: 'Token ID', type: 'string', description: 'The id of the burned token' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that transfers an NFT\n * held by the DAO treasury to a recipient. Maps onto a single `TransferNft`\n * proposal action — the consumer turns it into a cw721 `transfer_nft`\n * execute, or a `send_nft` carrying the JSON msg when the recipient is a\n * smart contract that should be executed on receipt.\n *\n * Part of the `qi/governance.nft.*` sub-family (treasury NFT management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - collection: cw721 collection contract address holding the token.\n * - tokenId: id of the token to transfer.\n * - recipient: bech32 (ixo1…) destination address (wallet or contract).\n * - executeSmartContract: when true the consumer sends `send_nft` with\n * `smartContractMsg`; otherwise a plain `transfer_nft`.\n * - smartContractMsg: JSON execute msg for the receiving contract (required\n * and must parse when executeSmartContract is true).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.nft.transfer',\n can: 'governance.nft/transfer',\n\n buildActions: (inputs) => {\n const collection = String(inputs.collection || '').trim();\n if (!collection) throw new Error('collection is required');\n\n const tokenId = String(inputs.tokenId || '').trim();\n if (!tokenId) throw new Error('tokenId is required');\n\n const recipient = String(inputs.recipient || '').trim();\n if (!recipient) throw new Error('recipient is required');\n\n const executeSmartContract = inputs.executeSmartContract === true || inputs.executeSmartContract === 'true';\n // The consumer JSON.stringifies smartContractMsg before base64-encoding it\n // into the send_nft hook — so it must be the PARSED object, not the JSON\n // string (a string would double-encode and the contract would reject it).\n let smartContractMsg: unknown = '';\n if (executeSmartContract) {\n const raw = String(inputs.smartContractMsg || '').trim();\n if (!raw) throw new Error('smartContractMsg is required when executeSmartContract is enabled');\n try {\n smartContractMsg = JSON.parse(raw);\n } catch {\n throw new Error('smartContractMsg must be valid JSON');\n }\n }\n\n return [{ type: 'TransferNft', data: { collection, tokenId, recipient, executeSmartContract, smartContractMsg } }];\n },\n\n defaultTitle: (inputs) => `Transfer NFT ${inputs.tokenId} to ${inputs.recipient}`,\n defaultDescription: () => 'Transfers the NFT from the treasury once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n collection: String(inputs.collection || ''),\n tokenId: String(inputs.tokenId || ''),\n recipient: String(inputs.recipient || ''),\n }),\n extraOutputSchema: [\n { path: 'collection', displayName: 'Collection', type: 'string', description: 'The cw721 collection contract the token is transferred from' },\n { path: 'tokenId', displayName: 'Token ID', type: 'string', description: 'The id of the transferred token' },\n { path: 'recipient', displayName: 'Recipient', type: 'string', description: 'Destination address of the transfer' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that tracks or untracks\n * an NFT collection in the DAO treasury. Maps onto a single `ManageCw721`\n * proposal action — the consumer turns it into an `update_cw721_list`\n * execute on the dao_core contract.\n *\n * Part of the `qi/governance.nft.*` sub-family (treasury NFT management).\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - adding: true → track (add) the collection in the treasury;\n * false → untrack (remove) it.\n * - address: cw721 collection contract address to track or untrack.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.nft.manage-collections',\n can: 'governance.nft/manage-collections',\n\n buildActions: (inputs) => {\n const address = String(inputs.address || '').trim();\n if (!address) throw new Error('address is required');\n\n const adding = inputs.adding === true || inputs.adding === 'true';\n\n return [{ type: 'ManageCw721', data: { adding, address } }];\n },\n\n defaultTitle: (inputs) => {\n const adding = inputs.adding === true || inputs.adding === 'true';\n return `${adding ? 'Track' : 'Untrack'} NFT collection ${inputs.address}`;\n },\n defaultDescription: () => 'Updates the NFT collections tracked in the treasury once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n adding: String(inputs.adding === true || inputs.adding === 'true'),\n address: String(inputs.address || ''),\n }),\n extraOutputSchema: [\n { path: 'adding', displayName: 'Adding', type: 'string', description: 'Whether the collection is tracked (true) or untracked (false)' },\n { path: 'address', displayName: 'Collection Address', type: 'string', description: 'The cw721 collection contract tracked or untracked' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that executes an\n * arbitrary message on a smart contract as the DAO. Maps onto a single\n * `Execute` proposal action — the consumer turns it into a\n * `MsgExecuteContract` from the DAO core, parsing the message with JSON5.\n *\n * Part of the `qi/governance.contract.*` sub-family (smart contracts).\n * Advanced: a malformed message fails on-chain when the proposal executes.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - address: the smart contract address to execute against.\n * - message: the execute message as a JSON string (validated with strict\n * JSON here; the consumer parses it with JSON5, a superset).\n * - funds: optional native coins attached to the execute, each\n * `{ denom, amount }` with the amount in base units.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.contract.execute',\n can: 'governance.contract/execute',\n\n buildActions: (inputs) => {\n const address = String(inputs.address || '').trim();\n if (!address) throw new Error('address is required');\n\n const message = String(inputs.message || '').trim();\n if (!message) throw new Error('message is required');\n try {\n JSON.parse(message);\n } catch {\n throw new Error('message must be a valid JSON object');\n }\n\n const rawFunds = Array.isArray(inputs.funds) ? inputs.funds : [];\n const funds = rawFunds.map((fund: any) => {\n const denom = String(fund?.denom || '').trim();\n if (!denom) throw new Error('every attached fund needs a denom');\n const amount = String(fund?.amount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('every attached fund amount must be a positive whole number in base units');\n }\n return { denom, amount };\n });\n\n return [{ type: 'Execute', data: { address, message, funds } }];\n },\n\n defaultTitle: (inputs) => `Execute a message on contract ${inputs.address}`,\n defaultDescription: () => 'Executes the message on the smart contract as the DAO once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ contractAddress: String(inputs.address || '') }),\n extraOutputSchema: [{ path: 'contractAddress', displayName: 'Contract Address', type: 'string', description: 'The smart contract the message executes on' }],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that instantiates a new\n * smart contract from an uploaded code id, with the DAO as the sender. Maps\n * onto a single `Instantiate` proposal action — the consumer turns it into\n * a `MsgInstantiateContract` from the DAO core, parsing the init message\n * with JSON5.\n *\n * Part of the `qi/governance.contract.*` sub-family (smart contracts).\n * Advanced: a wrong code id or malformed init message fails on-chain when\n * the proposal executes.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - codeId: the uploaded wasm code id to instantiate (positive integer).\n * - label: human-readable label stored on the new contract.\n * - admin: optional address allowed to migrate the new contract (blank →\n * no admin, the contract is immutable).\n * - message: the init message as a JSON string (validated with strict JSON\n * here; the consumer parses it with JSON5, a superset).\n * - funds: optional native coins sent to the new contract, each\n * `{ denom, amount }` with the amount in base units.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.contract.instantiate',\n can: 'governance.contract/instantiate',\n\n buildActions: (inputs) => {\n const codeId = Number(inputs.codeId);\n if (!Number.isInteger(codeId) || codeId <= 0) throw new Error('codeId must be a positive whole number');\n\n const label = String(inputs.label || '').trim();\n if (!label) throw new Error('label is required');\n\n // The consumer builds MsgInstantiateContract with `sender: admin`, so a\n // blank admin would produce an invalid message. Default to the group's\n // core address — the natural owner of contracts the group deploys.\n const admin = String(inputs.admin || '').trim() || String(inputs.coreAddress || '').trim();\n if (!admin) throw new Error('admin is required (defaults to the group core address)');\n\n const message = String(inputs.message || '').trim();\n if (!message) throw new Error('message is required');\n try {\n JSON.parse(message);\n } catch {\n throw new Error('message must be a valid JSON object');\n }\n\n const rawFunds = Array.isArray(inputs.funds) ? inputs.funds : [];\n const funds = rawFunds.map((fund: any) => {\n const denom = String(fund?.denom || '').trim();\n if (!denom) throw new Error('every attached fund needs a denom');\n const amount = String(fund?.amount || '').trim();\n if (!/^\\d+$/.test(amount) || BigInt(amount) <= 0n) {\n throw new Error('every attached fund amount must be a positive whole number in base units');\n }\n return { denom, amount };\n });\n\n return [{ type: 'Instantiate', data: { admin, codeId, label, message, funds } }];\n },\n\n defaultTitle: (inputs) => `Instantiate code ${inputs.codeId} as “${inputs.label}”`,\n defaultDescription: () => 'Instantiates a new smart contract from the code id once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ codeId: String(inputs.codeId || ''), contractLabel: String(inputs.label || '') }),\n extraOutputSchema: [\n { path: 'codeId', displayName: 'Code ID', type: 'string', description: 'The wasm code id instantiated' },\n { path: 'contractLabel', displayName: 'Contract Label', type: 'string', description: 'The label stored on the new contract' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that migrates a smart\n * contract the DAO administers to a new code id. Maps onto a single\n * `Migrate` proposal action — the consumer turns it into a\n * `MsgMigrateContract` from the DAO core, parsing the migrate msg with\n * JSON5.\n *\n * Part of the `qi/governance.contract.*` sub-family (smart contracts).\n * Advanced: only works when the DAO is the contract's admin, and a wrong\n * code id fails on-chain when the proposal executes.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - contract: the smart contract address to migrate.\n * - codeId: the new wasm code id to migrate to (positive integer).\n * - msg: the migrate msg as a JSON string, usually `{}` (validated with\n * strict JSON here; the consumer parses it with JSON5, a superset).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.contract.migrate',\n can: 'governance.contract/migrate',\n\n buildActions: (inputs) => {\n const contract = String(inputs.contract || '').trim();\n if (!contract) throw new Error('contract is required');\n\n const codeId = Number(inputs.codeId);\n if (!Number.isInteger(codeId) || codeId <= 0) throw new Error('codeId must be a positive whole number');\n\n const msg = String(inputs.msg || '').trim();\n if (!msg) throw new Error('msg is required (use {} for contracts whose migrate entry point takes no data)');\n try {\n JSON.parse(msg);\n } catch {\n throw new Error('msg must be a valid JSON object');\n }\n\n return [{ type: 'Migrate', data: { contract, codeId, msg } }];\n },\n\n defaultTitle: (inputs) => `Migrate contract ${inputs.contract} to code ${inputs.codeId}`,\n defaultDescription: () => 'Migrates the smart contract to the new code id once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ contractAddress: String(inputs.contract || ''), codeId: String(inputs.codeId || '') }),\n extraOutputSchema: [\n { path: 'contractAddress', displayName: 'Contract Address', type: 'string', description: 'The smart contract migrated' },\n { path: 'codeId', displayName: 'Code ID', type: 'string', description: 'The wasm code id migrated to' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that transfers admin\n * rights over a smart contract the DAO administers to a new address. Maps\n * onto a single `UpdateAdmin` proposal action — the consumer turns it into\n * a `MsgUpdateAdmin` from the DAO core.\n *\n * Part of the `qi/governance.contract.*` sub-family (smart contracts).\n * Only works when the DAO is the contract's current admin; handing the\n * admin away means the DAO can no longer migrate the contract.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - contract: the smart contract address whose admin changes.\n * - newAdmin: bech32 (ixo1…) address that becomes the contract's admin.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.contract.update-admin',\n can: 'governance.contract/update-admin',\n\n buildActions: (inputs) => {\n const contract = String(inputs.contract || '').trim();\n if (!contract) throw new Error('contract is required');\n\n const newAdmin = String(inputs.newAdmin || '').trim();\n if (!newAdmin) throw new Error('newAdmin is required');\n\n return [{ type: 'UpdateAdmin', data: { contract, newAdmin } }];\n },\n\n defaultTitle: (inputs) => `Update admin of ${inputs.contract} to ${inputs.newAdmin}`,\n defaultDescription: () => 'Transfers admin rights over the smart contract once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ contractAddress: String(inputs.contract || ''), newAdmin: String(inputs.newAdmin || '') }),\n extraOutputSchema: [\n { path: 'contractAddress', displayName: 'Contract Address', type: 'string', description: 'The smart contract whose admin changed' },\n { path: 'newAdmin', displayName: 'New Admin', type: 'string', description: 'The address that becomes the contract admin' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that tracks or untracks\n * a cw20 token in the DAO treasury. Maps onto a single `ManageCw20`\n * proposal action — the consumer turns it into an `update_cw20_list`\n * execute on the dao_core contract.\n *\n * Part of the `qi/governance.contract.*` sub-family (smart contracts).\n * Tracking only changes what the treasury displays — it never moves tokens.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - adding: true to track the token in the treasury, false to untrack it.\n * - address: the cw20 token contract address to track or untrack.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.contract.manage-cw20',\n can: 'governance.contract/manage-cw20',\n\n buildActions: (inputs) => {\n const rawAdding = inputs.adding;\n const adding = rawAdding === true || rawAdding === 'true' ? true : rawAdding === false || rawAdding === 'false' ? false : null;\n if (adding === null) throw new Error('adding must be true (track the token) or false (untrack it)');\n\n const address = String(inputs.address || '').trim();\n if (!address) throw new Error('address is required');\n\n return [{ type: 'ManageCw20', data: { adding, address } }];\n },\n\n defaultTitle: (inputs) => {\n const adding = inputs.adding === true || inputs.adding === 'true';\n return `${adding ? 'Track' : 'Untrack'} cw20 token ${inputs.address} in the treasury`;\n },\n defaultDescription: () => 'Updates the treasury’s cw20 token list once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({\n tokenContract: String(inputs.address || ''),\n adding: inputs.adding === true || inputs.adding === 'true' ? 'true' : 'false',\n }),\n extraOutputSchema: [\n { path: 'tokenContract', displayName: 'Token Contract', type: 'string', description: 'The cw20 token contract tracked or untracked' },\n { path: 'adding', displayName: 'Tracking', type: 'string', description: \"'true' when the token was tracked, 'false' when untracked\" },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that performs a\n * validator operation with the POD's validator account. Maps onto a\n * single `ValidatorActions` proposal action — the consumer turns it into\n * the matching stargate message (MsgWithdrawValidatorCommission,\n * MsgCreateValidator, MsgEditValidator or MsgUnjail) signed by the DAO\n * core. Withdraw-commission and unjail take no message body: the consumer\n * fills in the POD's validator address automatically.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - validatorActionType: full cosmos typeUrl of the operation (values match\n * the legacy `ValidatorActionType` enum in src/mantine/context/types.ts).\n * - createMsg: MsgCreateValidator body as JSON (CreateValidator only).\n * - editMsg: MsgEditValidator body as JSON (EditValidator only).\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\n\n// Full typeUrls, mirroring the legacy `ValidatorActionType` enum.\nconst VALIDATOR_ACTION_LABELS: Record<string, string> = {\n '/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission': 'Withdraw validator commission',\n '/cosmos.staking.v1beta1.MsgCreateValidator': 'Create validator',\n '/cosmos.staking.v1beta1.MsgEditValidator': 'Edit validator',\n '/cosmos.slashing.v1beta1.MsgUnjail': 'Unjail validator',\n};\n\nregisterGovernanceProposalAction({\n type: 'qi/governance.validator.actions',\n can: 'governance.validator/actions',\n\n buildActions: (inputs) => {\n const validatorActionType = String(inputs.validatorActionType || '').trim();\n if (!VALIDATOR_ACTION_LABELS[validatorActionType]) {\n throw new Error('validatorActionType must be one of the supported typeUrls (MsgWithdrawValidatorCommission, MsgCreateValidator, MsgEditValidator, MsgUnjail)');\n }\n\n const isCreate = validatorActionType === '/cosmos.staking.v1beta1.MsgCreateValidator';\n const isEdit = validatorActionType === '/cosmos.staking.v1beta1.MsgEditValidator';\n\n let createMsg = '';\n if (isCreate) {\n createMsg = String(inputs.createMsg || '').trim();\n if (!createMsg) throw new Error('createMsg is required for MsgCreateValidator');\n try {\n JSON.parse(createMsg);\n } catch {\n throw new Error('createMsg must be valid JSON');\n }\n }\n\n let editMsg = '';\n if (isEdit) {\n editMsg = String(inputs.editMsg || '').trim();\n if (!editMsg) throw new Error('editMsg is required for MsgEditValidator');\n try {\n JSON.parse(editMsg);\n } catch {\n throw new Error('editMsg must be valid JSON');\n }\n }\n\n return [{ type: 'ValidatorActions', data: { validatorActionType, createMsg, editMsg } }];\n },\n\n // buildActions runs first, so the action type is always a valid option here.\n defaultTitle: (inputs) => `Validator action: ${VALIDATOR_ACTION_LABELS[String(inputs.validatorActionType)] || inputs.validatorActionType}`,\n defaultDescription: () => \"Executes the validator operation with the POD's validator account once the proposal passes.\",\n\n buildExtraOutput: (inputs) => ({\n validatorActionType: String(inputs.validatorActionType || ''),\n validatorActionLabel: VALIDATOR_ACTION_LABELS[String(inputs.validatorActionType)] || '',\n }),\n extraOutputSchema: [\n { path: 'validatorActionType', displayName: 'Validator Action Type', type: 'string', description: 'The full cosmos typeUrl of the validator operation' },\n { path: 'validatorActionLabel', displayName: 'Validator Action', type: 'string', description: 'Human-readable name of the validator operation' },\n ],\n});\n","import { registerGovernanceProposalAction } from './_shared';\n\n/**\n * @description Create an on-chain governance proposal that executes a raw\n * cosmos message exactly as written. Maps onto a single `Custom` proposal\n * action — the consumer parses the JSON (JSON5 is tolerated on the consumer\n * side, but this action validates strict JSON) into a CosmosMsg\n * (`{\"bank\":…}`, `{\"wasm\":…}`, `{\"stargate\":…}`, …) the DAO core executes\n * when the proposal passes. An expert escape hatch for anything the typed\n * blocks don't cover.\n *\n * @inputs\n * - coreAddress: DAO core contract address (blank → resolved from the\n * current entity in flow mode).\n * - message: the raw cosmos message as a JSON object string.\n * - title / description: the proposal name and long-form description voters\n * see; required in the UI, with defaults for legacy templates.\n */\nregisterGovernanceProposalAction({\n type: 'qi/governance.custom-message',\n can: 'governance/custom-message',\n\n buildActions: (inputs) => {\n const message = String(inputs.message || '').trim();\n if (!message) throw new Error('message is required');\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (err) {\n throw new Error(`message must be valid JSON: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('message must be a JSON object — a single cosmos msg like {\"bank\":…}, {\"wasm\":…} or {\"stargate\":…}');\n }\n\n return [{ type: 'Custom', data: { message } }];\n },\n\n defaultTitle: () => 'Execute custom message',\n defaultDescription: () => 'Executes the raw cosmos message exactly as written once the proposal passes.',\n\n buildExtraOutput: (inputs) => ({ message: String(inputs.message || '') }),\n extraOutputSchema: [{ path: 'message', displayName: 'Message', type: 'string', description: 'The raw JSON cosmos message the proposal executes' }],\n});\n","import { sha256Digest } from '../digest';\nimport { doneWhenCompleted, registerAction } from '../registry';\n\nconst SENSITIVE_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization', 'x-api-key']);\nconst MUTATING_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];\nconst REQUEST_METHODS = [...MUTATING_METHODS, 'GET', 'HEAD'];\n\nfunction publicHttpUrl(raw: unknown): string {\n const value = String(raw || '').trim();\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error('HTTP endpoint must be an absolute URL');\n }\n if (url.protocol !== 'https:') throw new Error('HTTP Actions require an HTTPS endpoint');\n if (url.username || url.password) throw new Error('Credentials must not be embedded in an HTTP endpoint');\n const host = url.hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (\n host === 'localhost' ||\n host.endsWith('.localhost') ||\n host.endsWith('.local') ||\n host === '::1' ||\n host.startsWith('fc') ||\n host.startsWith('fd') ||\n host.startsWith('fe80:') ||\n /^127\\./.test(host) ||\n /^10\\./.test(host) ||\n /^169\\.254\\./.test(host) ||\n /^192\\.168\\./.test(host) ||\n /^172\\.(1[6-9]|2\\d|3[01])\\./.test(host) ||\n host === '0.0.0.0'\n ) {\n throw new Error('HTTP endpoint must not resolve to a local, private, link-local, or metadata address');\n }\n return url.toString();\n}\n\nfunction safeHeaders(raw: unknown): Record<string, string> {\n if (raw === undefined || raw === null) return {};\n // An array used to be read as \"no headers\", silently, which is why a header\n // typed into the block's key/value table never reached the request: the rows\n // arrive as `[{key, value}]` and this answered `{}`. `normalizeHttpInputs`\n // converts them before anything reads them, so an array here is a caller\n // that skipped it.\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new Error('Request headers must be a name/value object');\n }\n const headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (SENSITIVE_HEADERS.has(key.toLowerCase())) {\n throw new Error(`Sensitive header '${key}' must be supplied through a host-managed credential binding, not Action input`);\n }\n headers[key] = String(value);\n }\n return headers;\n}\n\nconst INPUT_PROPERTIES = {\n endpoint: { type: 'string', format: 'uri', description: 'Public HTTPS request URL. Either endpoint or url is required.' },\n url: { type: 'string', format: 'uri', description: 'Legacy alias for endpoint.' },\n method: { type: 'string', description: 'HTTP method.' },\n headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Non-secret request headers. Authorization and cookies are rejected.' },\n body: { description: 'Request body for a mutating HTTP request.' },\n};\n\nconst OUTPUT_SCHEMA = [\n { path: 'requestId', displayName: 'Request ID', type: 'string' as const, description: 'Host invocation identifier.' },\n { path: 'status', displayName: 'HTTP Status', type: 'number' as const },\n { path: 'responseDigest', displayName: 'Response Digest', type: 'string' as const, description: 'Digest of the response body.' },\n { path: 'data', displayName: 'Response Data', type: 'object' as const, description: 'Full result retained in the Flow timeline, not copied into Topic state.' },\n { path: 'response', displayName: 'Response JSON', type: 'string' as const },\n { path: 'traceReference', displayName: 'Trace Reference', type: 'string' as const },\n];\n\n/** The five properties `qi/http.fetch` and `qi/http.request` declare. */\nconst CONTRACT_INPUT_KEYS = ['endpoint', 'url', 'method', 'headers', 'body'] as const;\n\nfunction keyValueRows(value: unknown): Record<string, unknown> | null {\n if (!Array.isArray(value)) return null;\n const result: Record<string, unknown> = {};\n for (const entry of value) {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;\n const row = entry as Record<string, unknown>;\n if (typeof row.key !== 'string') return null;\n // A blank name is an empty row in the authoring table, not a header.\n if (!row.key.trim()) continue;\n result[row.key] = row.value ?? '';\n }\n return result;\n}\n\n/**\n * An HTTP block's authored inputs, in the shape its contract describes.\n *\n * The block stores `headers` and `body` as `KeyValuePair[]` — that is what its\n * authoring table produces, and what lands in the flow document. The contract\n * above declares `headers` as a name/value object, and `additionalProperties:\n * false` over five properties, so the authored form fails its own schema:\n * `$.headers has an invalid type`. Nothing converted between the two shapes;\n * `safeHeaders` discarded arrays, which hid it here and let authored headers\n * go missing, and the flow manager validates before executing, so there the\n * step failed outright and parked its run.\n *\n * One owner for that conversion, called by every executor. The flow manager\n * mirrors it in `apps/flow-runner/src/http-action.ts` — it cannot import this\n * registry — and the two must agree, or the browser and the oracle send\n * different requests for the same block.\n *\n * An empty table becomes no property at all rather than `{}`, so a block that\n * sets nothing is indistinguishable from one that never had the field.\n */\nexport function normalizeHttpInputs(inputs: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of CONTRACT_INPUT_KEYS) {\n const value = inputs[key];\n if (value === undefined) continue;\n if (key === 'headers' || key === 'body') {\n const rows = keyValueRows(value);\n if (rows) {\n if (Object.keys(rows).length > 0) result[key] = rows;\n continue;\n }\n }\n result[key] = value;\n }\n return result;\n}\n\nfunction missingEndpoint(inputs: Record<string, unknown>): string[] {\n return String(inputs.endpoint || inputs.url || '').trim() ? [] : ['endpoint'];\n}\n\nregisterAction({\n type: 'qi/http.fetch',\n can: 'http/fetch',\n sideEffect: false,\n proof: { fields: ['responseDigest'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: [],\n additionalProperties: false,\n properties: { ...INPUT_PROPERTIES, method: { type: 'string', enum: ['GET', 'HEAD'], default: 'GET' } },\n },\n getMissingInputs: missingEndpoint,\n outputSchema: OUTPUT_SCHEMA,\n run: async (rawInputs, ctx) => {\n const inputs = normalizeHttpInputs(rawInputs);\n const url = publicHttpUrl(inputs.endpoint ?? inputs.url);\n const method = String(inputs.method || 'GET').toUpperCase();\n if (method !== 'GET' && method !== 'HEAD') throw new Error('qi/http.fetch permits GET or HEAD only');\n const headers = safeHeaders(inputs.headers);\n const service = ctx.services.http;\n if (service) {\n const result = await service.request({\n url,\n method,\n headers,\n security: { denyPrivateNetworks: true, maxRedirects: 0, stripSensitiveHeadersOnRedirect: true },\n });\n const responseDigest = result.responseDigest || sha256Digest(result.data);\n return {\n output: {\n requestId: result.requestId || responseDigest,\n status: result.status,\n responseDigest,\n data: result.data,\n response: JSON.stringify(result.data, null, 2),\n traceReference: result.traceReference || '',\n },\n };\n }\n const response = await fetch(url, { method, headers, redirect: 'error' });\n const text = method === 'HEAD' ? '' : await response.text();\n let data: unknown = text;\n try {\n data = text ? JSON.parse(text) : {};\n } catch {\n // Retain non-JSON response text in the Flow timeline.\n }\n const responseDigest = sha256Digest(data);\n return {\n output: {\n requestId: responseDigest,\n status: response.status,\n responseDigest,\n data,\n response: typeof data === 'string' ? data : JSON.stringify(data, null, 2),\n traceReference: '',\n },\n };\n },\n});\n\nregisterAction({\n type: 'qi/http.request',\n can: 'http/request',\n sideEffect: true,\n proof: { fields: ['requestId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: [],\n additionalProperties: false,\n properties: {\n ...INPUT_PROPERTIES,\n method: {\n type: 'string',\n enum: REQUEST_METHODS,\n default: 'GET',\n description:\n 'POST/PUT/PATCH/DELETE for mutations. GET/HEAD remain accepted for legacy Flows but use the same confirmation and receipt policy; new read Actions should use qi/http.fetch.',\n },\n },\n },\n getMissingInputs: missingEndpoint,\n outputSchema: OUTPUT_SCHEMA,\n run: async (rawInputs, ctx) => {\n const inputs = normalizeHttpInputs(rawInputs);\n const service = ctx.services.http;\n if (!service) throw new Error('Mutating HTTP requests require the host HTTP service; native fetch is not permitted');\n const url = publicHttpUrl(inputs.endpoint ?? inputs.url);\n const method = String(inputs.method || 'GET').toUpperCase();\n if (!REQUEST_METHODS.includes(method)) throw new Error(`qi/http.request method must be one of ${REQUEST_METHODS.join(', ')}`);\n const result = await service.request({\n url,\n method,\n headers: safeHeaders(inputs.headers),\n body: inputs.body,\n security: { denyPrivateNetworks: true, maxRedirects: 0, stripSensitiveHeadersOnRedirect: true },\n });\n const responseDigest = result.responseDigest || sha256Digest(result.data);\n const requestId = result.requestId || sha256Digest({ url, method, status: result.status, responseDigest });\n return {\n output: { requestId, status: result.status, responseDigest, data: result.data, response: JSON.stringify(result.data, null, 2), traceReference: result.traceReference || '' },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/email.send',\n can: 'email/send',\n sideEffect: true,\n proof: { fields: ['messageId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'email/send',\n\n // Email send is autonomous-enough to be triggered by another block's event.\n // When wired as a listener, the assignee on the email block is DM'd to\n // invoke it for each pending event. See docs/flow-engine/events-and-triggers-plan.md §3.6.\n eligibleForEventTrigger: true,\n\n inputSchema: {\n type: 'object',\n required: ['to', 'templateName'],\n properties: {\n to: { type: 'string', description: 'Recipient email address.' },\n templateName: { type: 'string', description: 'The email template to send. A template is required — either templateName or its alias template must be provided.' },\n template: { type: 'string', description: 'Alias for templateName; the template id to send. Either template or templateName satisfies the template requirement.' },\n subject: { type: 'string', description: 'Email subject line.' },\n templateVersion: { type: 'string', description: 'Optional specific version of the template to render.' },\n variables: { type: 'object', description: 'Template variables to interpolate; may be passed as an object or a JSON string.' },\n cc: { type: 'string', description: 'Carbon-copy recipient address.' },\n bcc: { type: 'string', description: 'Blind-carbon-copy recipient address.' },\n replyTo: { type: 'string', description: 'Reply-to address for the email.' },\n },\n },\n\n outputSchema: [\n { path: 'messageId', displayName: 'Message ID', type: 'string', description: 'The unique ID of the sent email' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'Timestamp when the email was sent' },\n ],\n\n // run() accepts `template` OR `templateName` for the template — the\n // schema's required array can't express the alias, so mirror the OR here.\n getMissingInputs: (inputs) => {\n const missing: string[] = [];\n if (!String(inputs.to || '').trim()) missing.push('to');\n if (!String(inputs.template || '').trim() && !String(inputs.templateName || '').trim()) missing.push('templateName');\n return missing;\n },\n run: async (inputs, ctx) => {\n if (!ctx.services.email) {\n throw new Error('Email service not configured');\n }\n\n const { to, subject, template, templateName, templateVersion, variables, cc, bcc, replyTo } = inputs;\n const resolvedTemplate = template || templateName;\n\n if (!resolvedTemplate) throw new Error('No template selected');\n if (!to) throw new Error('Recipient (to) is required');\n\n // variables may be a JSON string from the config editor — parse if needed\n let resolvedVariables = variables;\n if (typeof resolvedVariables === 'string') {\n try {\n resolvedVariables = JSON.parse(resolvedVariables);\n } catch {\n resolvedVariables = {};\n }\n }\n\n const result = await ctx.services.email.send({\n to,\n subject,\n template: resolvedTemplate,\n templateVersion,\n variables: resolvedVariables,\n cc,\n bcc,\n replyTo,\n });\n\n return {\n output: {\n messageId: result.messageId,\n sentAt: result.sentAt || new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { sha256Digest } from '../digest';\n\nregisterAction({\n type: 'qi/human.checkbox.set',\n can: 'human/checkbox',\n sideEffect: true,\n proof: { fields: ['attestationId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\n\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n checked: { type: 'boolean', description: 'Whether the checkbox should be checked (defaults to true).' },\n },\n },\n outputSchema: [\n { path: 'checked', displayName: 'Checked', type: 'boolean' },\n { path: 'attestationId', displayName: 'Attestation ID', type: 'string', description: 'Proof identifier for the human checkbox attestation.' },\n { path: 'attestedAt', displayName: 'Attested At', type: 'string' },\n { path: 'attestedBy', displayName: 'Attested By', type: 'string' },\n ],\n\n run: async (inputs, ctx) => {\n // Default to true — \"executing\" a checkbox means checking it\n const checked = inputs.checked !== undefined ? !!inputs.checked : true;\n const attestedAt = new Date().toISOString();\n const attestationId = sha256Digest({ action: 'qi/human.checkbox.set', checked, actorDid: ctx.actorDid, flowId: ctx.flowId, nodeId: ctx.nodeId, attestedAt });\n return { output: { checked, attestationId, attestedAt, attestedBy: ctx.actorDid } };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { sha256Digest } from '../digest';\n\nfunction normalizeAnswers(rawAnswers: unknown): Record<string, unknown> {\n if (rawAnswers == null) {\n return {};\n }\n\n if (typeof rawAnswers === 'string') {\n try {\n const parsed = JSON.parse(rawAnswers) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error();\n }\n return parsed as Record<string, unknown>;\n } catch {\n throw new Error('answers must be a valid JSON object');\n }\n }\n\n if (typeof rawAnswers !== 'object' || Array.isArray(rawAnswers)) {\n throw new Error('answers must be an object');\n }\n\n return rawAnswers as Record<string, unknown>;\n}\n\nfunction registerFormSubmitAction(type: string, can?: string): void {\n registerAction({\n type,\n can,\n sideEffect: true,\n proof: { fields: ['submissionId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\n // Additive: makes the form an event SOURCE so downstream blocks can\n // auto-trigger on submission (e.g. form → send email). Nothing existing\n // consumes this; it only enables new event wiring.\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n answers: { type: 'object', description: 'Form answers as an object or JSON-string object; also read from form.answers.' },\n },\n },\n outputSchema: [\n { path: 'form.answers', displayName: 'Form Answers JSON', type: 'string', description: 'JSON stringified form answers, matching form block runtime output.' },\n { path: 'answers', displayName: 'Form Answers', type: 'object', description: 'Parsed form answers object for convenience.' },\n { path: 'submissionId', displayName: 'Submission ID', type: 'string', description: 'Stable proof identifier for this submission.' },\n { path: 'answersDigest', displayName: 'Answers Digest', type: 'string', description: 'Content digest; safe to place in a Topic receipt.' },\n { path: 'submittedAt', displayName: 'Submitted At', type: 'string' },\n { path: 'submittedBy', displayName: 'Submitted By', type: 'string' },\n ],\n events: [\n {\n name: 'form.submitted',\n displayName: 'Form submitted',\n description: 'Fires when the human submits the form. Payload carries the parsed answers.',\n payloadSchema: [{ path: 'answers', displayName: 'Form Answers', type: 'object' }],\n pendingDisplayFields: ['answers'],\n },\n ],\n run: async (inputs, ctx) => {\n const answers = normalizeAnswers(inputs.answers ?? inputs.form?.answers);\n const answersJson = JSON.stringify(answers);\n const submittedAt = new Date().toISOString();\n const answersDigest = sha256Digest(answers);\n const submissionId = sha256Digest({ type, flowId: ctx.flowId, sessionRunId: ctx.sessionRunId || '', nodeId: ctx.nodeId, submittedAt, answersDigest });\n\n return {\n output: {\n form: {\n answers: answersJson,\n },\n answers,\n submissionId,\n answersDigest,\n submittedAt,\n submittedBy: ctx.actorDid,\n },\n events: [{ name: 'form.submitted', payload: { answers } }],\n };\n },\n });\n}\n\n// Canonical action type that aligns with the form block naming.\nregisterFormSubmitAction('qi/form.submit', 'form/submit');\n// Backward-compatible alias for existing saved flows.\nregisterFormSubmitAction('qi/human.form.submit', 'human/form');\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { createRunTerminalAuthorizationProof } from '../../flowEngine/terminalAuthorization';\n\nregisterAction({\n type: 'qi/flow.run.start',\n can: 'flow/run.start',\n sideEffect: true,\n proof: { fields: ['runId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/run.start',\n executionOwner: 'agent',\n inputSchema: {\n type: 'object',\n properties: {\n label: { type: 'string' },\n },\n },\n outputSchema: [\n { path: 'runId', displayName: 'Session run id', type: 'string' },\n { path: 'eventId', displayName: 'Started event id', type: 'string' },\n { path: 'startedAt', displayName: 'Started at', type: 'number' },\n { path: 'sessionId', displayName: 'Session ID', type: 'string' },\n { path: 'flowRevision', displayName: 'Flow revision', type: 'string' },\n { path: 'topicBindingId', displayName: 'Topic binding ID', type: 'string' },\n ],\n events: [\n {\n name: 'flow.run.started',\n displayName: 'Flow run started',\n description: 'Emitted when a pinned Flow run starts; it does not change Topic status.',\n payloadSchema: [\n { path: 'runId', displayName: 'Run ID', type: 'string' },\n { path: 'topicBindingId', displayName: 'Topic binding ID', type: 'string' },\n ],\n },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.flowRuns?.start) {\n throw new Error('flowRuns.start handler not available');\n }\n const lifecycle = await ctx.services.flowRuns.start({\n actorDid: ctx.actorDid,\n flowId: ctx.flowId,\n flowUri: ctx.flowUri,\n ...(typeof inputs.label === 'string' && inputs.label ? { label: inputs.label } : {}),\n });\n const output = {\n ...lifecycle,\n sessionId: lifecycle.runId,\n flowRevision: ctx.flowRevision || '',\n topicBindingId: ctx.topic?.bindingId || '',\n };\n return { output, events: [{ name: 'flow.run.started', payload: { runId: lifecycle.runId, topicBindingId: output.topicBindingId } }] };\n },\n});\n\nregisterAction({\n type: 'qi/flow.run.close',\n can: 'flow/run.close',\n sideEffect: true,\n proof: { fields: ['status'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n requiresSignedInvocation: true,\n executionOwner: 'agent',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n properties: {\n allowIncomplete: { type: 'boolean' },\n cancel: { type: 'boolean' },\n reason: { type: 'string' },\n terminalSummary: {\n type: 'object',\n additionalProperties: { type: 'boolean' },\n description: 'Runtime-computed completion projection bound into the signed terminal invocation.',\n },\n },\n },\n outputSchema: [\n { path: 'status', displayName: 'Terminal status', type: 'string' },\n { path: 'eventId', displayName: 'Terminal event id', type: 'string' },\n { path: 'closedAt', displayName: 'Closed at', type: 'number' },\n { path: 'cancelledAt', displayName: 'Cancelled at', type: 'number' },\n { path: 'runId', displayName: 'Session run ID', type: 'string' },\n { path: 'flowRevision', displayName: 'Flow revision', type: 'string' },\n { path: 'topicBindingId', displayName: 'Topic binding ID', type: 'string' },\n ],\n events: [\n {\n name: 'flow.run.closed',\n displayName: 'Flow run closed',\n description: 'Emitted when the Flow run closes; Topic resolution remains an explicit, separate Action.',\n payloadSchema: [\n { path: 'runId', displayName: 'Run ID', type: 'string' },\n { path: 'status', displayName: 'Status', type: 'string' },\n { path: 'topicBindingId', displayName: 'Topic binding ID', type: 'string' },\n ],\n },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.sessionRunId) {\n throw new Error('flow/run.close requires an explicit session run id');\n }\n if (!ctx.services.flowRuns) {\n throw new Error('flowRuns lifecycle handler not available');\n }\n const proof = ctx.executionProof;\n if (!proof?.invocationCid || !proof.invocation) {\n throw new Error('flow/run.close requires the exact signed Flow invocation');\n }\n const authorization = createRunTerminalAuthorizationProof({\n invocationCid: proof.invocationCid,\n invocation: proof.invocation,\n actorDid: ctx.actorDid,\n actionBlockId: ctx.nodeId,\n inputDigest: proof.inputDigest,\n actionInputs: { ...inputs },\n capability: { ...proof.capability },\n proofCids: [...proof.proofCids],\n });\n if (inputs.cancel === true) {\n const lifecycle = await ctx.services.flowRuns.cancel({\n actorDid: ctx.actorDid,\n flowId: ctx.flowId,\n flowUri: ctx.flowUri,\n runId: ctx.sessionRunId,\n ...(typeof inputs.reason === 'string' && inputs.reason ? { reason: inputs.reason } : {}),\n authorization,\n });\n const output = { ...lifecycle, runId: ctx.sessionRunId, flowRevision: ctx.flowRevision || '', topicBindingId: ctx.topic?.bindingId || '' };\n return {\n output,\n events: [{ name: 'flow.run.closed', payload: { runId: ctx.sessionRunId, status: lifecycle.status, topicBindingId: output.topicBindingId } }],\n };\n }\n const lifecycle = await ctx.services.flowRuns.close({\n actorDid: ctx.actorDid,\n flowId: ctx.flowId,\n flowUri: ctx.flowUri,\n runId: ctx.sessionRunId,\n allowIncomplete: inputs.allowIncomplete === true,\n authorization,\n });\n const output = { ...lifecycle, runId: ctx.sessionRunId, flowRevision: ctx.flowRevision || '', topicBindingId: ctx.topic?.bindingId || '' };\n return {\n output,\n events: [{ name: 'flow.run.closed', payload: { runId: ctx.sessionRunId, status: lifecycle.status, topicBindingId: output.topicBindingId } }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/notification.push',\n can: 'notification/push',\n sideEffect: true,\n proof: { fields: ['messageId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'notify/send',\n inputSchema: {\n type: 'object',\n required: ['to'],\n properties: {\n channel: { type: 'string', description: 'Delivery channel for the notification.' },\n to: { type: 'array', description: 'Recipient(s); a single value or array, at least one required.' },\n cc: { type: 'array', description: 'CC recipients.' },\n bcc: { type: 'array', description: 'BCC recipients.' },\n subject: { type: 'string', description: 'Notification subject.' },\n body: { type: 'string', description: 'Notification body content.' },\n bodyType: { type: 'string', description: \"Body format: 'text' or 'html'.\" },\n from: { type: 'string', description: 'Sender address.' },\n replyTo: { type: 'string', description: 'Reply-to address.' },\n },\n },\n outputSchema: [\n { path: 'messageId', displayName: 'Message ID', type: 'string', description: 'Provider or host notification identifier.' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'ISO timestamp supplied by the provider or host.' },\n ],\n\n run: async (inputs, ctx) => {\n if (!ctx.services.notify) {\n throw new Error('Notification service not configured');\n }\n\n const { channel, to, cc, bcc, subject, body, bodyType, from, replyTo } = inputs;\n\n if (!to || (Array.isArray(to) && to.length === 0)) {\n throw new Error('At least one recipient is required');\n }\n\n const result = await ctx.services.notify.send({\n channel,\n to: Array.isArray(to) ? to : [to],\n cc,\n bcc,\n subject,\n body,\n bodyType,\n from,\n replyTo,\n });\n\n return {\n output: {\n messageId: result.messageId,\n sentAt: result.sentAt || new Date().toISOString(),\n },\n };\n },\n});\n","import type { ActionContext, ActionResult } from '../../types';\n\n/**\n * Group execution — \"act as the DAO DAO group\" — for work blocks (claim,\n * evaluate-claim, bid, evaluate-bid, collection lifecycle, collection users).\n *\n * When a user chooses to act on behalf of their governance group instead of\n * their own account, the block does NOT broadcast the side effect directly.\n * Instead:\n *\n * 1. The consumer prepares the SAME on-chain message(s) with the group's\n * core address as the actor (agent / grantee) and returns them\n * protobuf-encoded (`EncodedProposalMsg`), so the editor stays\n * codec-free.\n * 2. The editor wraps them in an on-chain governance proposal via\n * `handlers.createGroupExecutionProposal` — the user signs only the\n * proposal creation (they must be a member of the group).\n * 3. The run returns `awaiting_readback`: the block is NOT complete and\n * downstream blocks stay gated. The FlowDetail polls the proposal and\n * reconciles the block to `completed` (with the same outputs a direct\n * signature would have produced) once the proposal passes and executes —\n * or `failed` when it is rejected.\n *\n * Off-chain side effects that a proposal cannot execute (Matrix bot calls —\n * bid submission, bid status updates) run as a `finalize` step: the\n * initiating user's client performs them after the proposal executes, with\n * the group's approval recorded on-chain in the proposal itself.\n */\n\n/** A protobuf message pre-encoded by the consumer: `value` is base64 bytes. */\nexport interface EncodedProposalMsg {\n typeUrl: string;\n value: string;\n}\n\n/** readBack.kind marking a run that awaits a group proposal's execution. */\nexport const GROUP_PROPOSAL_READBACK_KIND = 'group-proposal';\n\n/** Common inputs every group-executable action accepts on top of its own. */\nexport interface GroupExecutionInputs {\n /** True (or 'true') → act as the group instead of the current user. */\n actAsGroup?: boolean | string;\n /** DAO core contract address of the group being acted for. */\n groupCoreAddress?: string;\n /** Proposal name shown to voters. Required in group mode. */\n proposalTitle?: string;\n /** Long-form proposal description shown to voters. Required in group mode. */\n proposalDescription?: string;\n}\n\nexport function isGroupExecution(inputs: Record<string, any>): boolean {\n return inputs?.actAsGroup === true || inputs?.actAsGroup === 'true';\n}\n\n/** Validate and pull the group-execution params out of merged inputs. */\nexport function requireGroupExecutionParams(inputs: Record<string, any>): { coreAddress: string; title: string; description: string } {\n const coreAddress = String(inputs.groupCoreAddress || '').trim();\n if (!coreAddress) throw new Error('groupCoreAddress is required when acting as a POD');\n const title = String(inputs.proposalTitle || '').trim();\n if (!title) throw new Error('proposalTitle is required when acting as a POD — voters must see what they are approving');\n const description = String(inputs.proposalDescription || '').trim();\n if (!description) throw new Error('proposalDescription is required when acting as a POD — voters must see what they are approving');\n return { coreAddress, title, description };\n}\n\nexport interface ProposeGroupExecutionParams {\n coreAddress: string;\n title: string;\n description: string;\n /** Pre-encoded chain messages the proposal executes when it passes. May be\n * empty for approval-only proposals whose side effect is a finalize step. */\n msgs: EncodedProposalMsg[];\n /**\n * The output fields the block will complete with once the proposal\n * executes — the same shape a direct signature would have produced, so\n * downstream references keep working.\n */\n expectedOutput: Record<string, any>;\n /**\n * Optional finalize step key for off-chain side effects the proposal cannot\n * execute (e.g. 'bid.submit' → the initiating user's client submits the\n * Matrix bid after the group approves). Resolved by the FlowDetail's\n * read-back driver.\n */\n finalize?: string;\n /** Params the finalize step needs, persisted in readBack metadata. */\n finalizeParams?: Record<string, any>;\n /**\n * Event name to emit (with the completed output as payload) when the block\n * completes via read-back — keeps listener blocks working in group mode\n * (e.g. the claim block's 'submitted' event).\n */\n completionEvent?: string;\n}\n\n/**\n * Create the group proposal and return the `awaiting_readback` ActionResult.\n * Call from an action's `run()` after `isGroupExecution(inputs)` matched and\n * the action-specific messages were prepared.\n */\nexport async function proposeGroupExecution(ctx: ActionContext, params: ProposeGroupExecutionParams): Promise<ActionResult> {\n const handlers = ctx.handlers as any;\n if (!handlers?.createGroupExecutionProposal) {\n throw new Error('Group execution is not available: the host does not implement createGroupExecutionProposal');\n }\n\n const { coreAddress, title, description, msgs, expectedOutput, finalize, finalizeParams, completionEvent } = params;\n\n const { proposalId, proposalContractAddress } = await handlers.createGroupExecutionProposal({\n coreAddress,\n title,\n description,\n msgs,\n });\n\n if (proposalId === undefined || proposalId === null || String(proposalId).trim() === '') {\n throw new Error('POD proposal creation returned no proposal id. Check the handler logs.');\n }\n\n return {\n output: {\n ...expectedOutput,\n groupExecution: true,\n groupCoreAddress: coreAddress,\n groupProposalId: String(proposalId),\n groupProposalContractAddress: String(proposalContractAddress || ''),\n proposalTitle: title,\n proposalDescription: description,\n },\n completion: {\n state: 'awaiting_readback',\n readBack: {\n kind: GROUP_PROPOSAL_READBACK_KIND,\n proposalId: String(proposalId),\n proposalContractAddress: String(proposalContractAddress || ''),\n coreAddress,\n expectedOutput,\n ...(completionEvent ? { completionEvent } : {}),\n ...(finalize ? { finalize, finalizeParams: finalizeParams || {} } : {}),\n },\n },\n };\n}\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { BidRunInputs } from './types';\n\nfunction normalizeBidRole(role: string): 'SA' | 'EA' {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n if (normalized === 'service_agent' || normalized === 'sa') return 'SA';\n if (normalized === 'evaluation_agent' || normalized === 'ea') return 'EA';\n throw new Error('Invalid bid role. Expected service_agent or evaluation_agent');\n}\n\nregisterAction<BidRunInputs>({\n type: 'qi/bid.submit',\n can: 'bid/submit',\n sideEffect: true,\n proof: { fields: ['bidId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n inputSchema: {\n type: 'object',\n required: ['collectionId', 'role', 'surveyAnswers'],\n properties: {\n collectionId: { type: 'string', description: 'Claim collection identifier the bid is submitted against.' },\n role: { type: 'string', description: 'Bid role: service_agent or evaluation_agent.' },\n surveyAnswers: { type: 'object', description: 'Survey answers object (or a JSON string parsed to an object) attached to the bid.' },\n deedDid: { type: 'string', description: 'Optional deed/entity DID associated with the bid.' },\n },\n },\n outputSchema: [\n { path: 'bidId', displayName: 'Bid ID', type: 'string', description: 'The submitted bid identifier' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'role', displayName: 'Role', type: 'string', description: 'Submitted role (service_agent or evaluation_agent)' },\n { path: 'submitterDid', displayName: 'Submitter DID', type: 'string', description: 'Actor DID that submitted the bid' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier if provided' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.bid;\n if (!service) {\n throw new Error('Bid service not configured');\n }\n\n const collectionId = String(inputs.collectionId || '').trim();\n const roleInput = String(inputs.role || '').trim();\n let surveyAnswers = inputs.surveyAnswers;\n const deedDid = String(inputs.deedDid || '').trim();\n\n if (!collectionId) throw new Error('collectionId is required');\n if (!roleInput) throw new Error('role is required');\n if (typeof surveyAnswers === 'string') {\n try {\n surveyAnswers = JSON.parse(surveyAnswers);\n } catch {\n throw new Error('surveyAnswers must be a valid JSON object');\n }\n }\n\n if (!surveyAnswers || typeof surveyAnswers !== 'object' || Array.isArray(surveyAnswers)) {\n throw new Error('surveyAnswers must be an object');\n }\n\n const chainRole = normalizeBidRole(roleInput);\n\n // ---- Act as the DAO group: propose first, submit after approval --------\n // A bid is a Matrix bid-bot submission — a proposal cannot execute it\n // on-chain. Group mode therefore creates an APPROVAL proposal (no\n // messages, the bid content in the description); once the group passes\n // it, the initiating user's client performs the actual bid submission as\n // the finalize step, with the group's approval recorded on-chain.\n if (isGroupExecution(inputs)) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: [],\n expectedOutput: {\n bidId: '',\n collectionId,\n role: roleInput,\n submitterDid: coreAddress,\n deedDid,\n },\n finalize: 'bid.submit',\n finalizeParams: {\n collectionId,\n role: chainRole,\n surveyAnswers,\n entityDid: deedDid || undefined,\n // The bid bot records the bid under the POD's identity so the\n // approval grants the claim authorization to the POD, not the\n // member who submitted on its behalf.\n onBehalfOfAddress: coreAddress,\n },\n });\n }\n\n const submission = await service.submitBid({\n collectionId,\n role: chainRole,\n surveyAnswers,\n entityDid: deedDid || undefined,\n });\n\n const bidId = String((submission as any)?.claimId || (submission as any)?.bidId || (submission as any)?.id || '');\n if (!bidId) {\n throw new Error('submitBid returned no bid identifier');\n }\n\n return {\n output: {\n bidId,\n collectionId,\n role: roleInput,\n submitterDid: ctx.actorDid || '',\n deedDid,\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { EvaluateBidRunInputs } from './types';\n\ntype Decision = 'approve' | 'reject';\n\nfunction normalizeDecision(value: string): Decision {\n const normalized = String(value || '')\n .trim()\n .toLowerCase();\n if (normalized === 'approve' || normalized === 'reject') {\n return normalized;\n }\n throw new Error('decision must be either approve or reject');\n}\n\nfunction isServiceAgentRole(role: string): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'service_agent' || normalized === 'sa';\n}\n\nfunction isEvaluationAgentRole(role: string): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'evaluation_agent' || normalized === 'ea';\n}\n\nregisterAction<EvaluateBidRunInputs>({\n type: 'qi/bid.evaluate',\n can: 'bid/evaluate',\n // Superseded by qi/collection.users (IXO-2586) — not offered to authors\n // anymore; kept registered so existing flows and templates still work.\n hiddenFromAuthoring: true,\n sideEffect: true,\n proof: { fields: ['bidId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: [\n { path: 'bidId', displayName: 'Bid ID', type: 'string', description: 'Evaluated bid identifier' },\n { path: 'decision', displayName: 'Decision', type: 'string', description: 'approve or reject' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'approved or rejected' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that evaluated the bid' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string', description: 'ISO timestamp of evaluation' },\n { path: 'reason', displayName: 'Reason', type: 'string', description: 'Rejection reason when decision is reject' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'role', displayName: 'Role', type: 'string', description: 'Applicant role' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'applicantDid', displayName: 'Applicant DID', type: 'string', description: 'Applicant DID' },\n { path: 'applicantAddress', displayName: 'Applicant Address', type: 'string', description: 'Applicant wallet address' },\n ],\n inputSchema: {\n type: 'object',\n required: ['decision', 'bidId', 'collectionId', 'deedDid', 'role', 'applicantDid', 'applicantAddress'],\n properties: {\n decision: { type: 'string', description: 'Evaluation decision: approve or reject.' },\n bidId: { type: 'string', description: 'Identifier of the bid being evaluated.' },\n collectionId: { type: 'string', description: 'Claim collection identifier.' },\n deedDid: { type: 'string', description: 'Deed (entity) DID.' },\n role: { type: 'string', description: 'Applicant role: service_agent (sa) or evaluation_agent (ea).' },\n applicantDid: { type: 'string', description: 'Applicant DID.' },\n applicantAddress: { type: 'string', description: 'Applicant wallet address.' },\n adminAddress: { type: 'string', description: 'Entity admin account address; required when decision is approve.' },\n maxAmounts: { type: 'string', description: 'JSON-encoded per-claim max amounts for the evaluation_agent approval.' },\n reason: { type: 'string', description: 'Rejection reason; required when decision is reject.' },\n },\n },\n run: async (inputs, ctx) => {\n const service = ctx.services.bid;\n if (!service) {\n throw new Error('Bid service not configured');\n }\n\n const decision = normalizeDecision(inputs.decision);\n const bidId = String(inputs.bidId || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n const role = String(inputs.role || '').trim();\n const applicantDid = String(inputs.applicantDid || '').trim();\n const applicantAddress = String(inputs.applicantAddress || '').trim();\n\n if (!bidId) throw new Error('bidId is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!deedDid) throw new Error('deedDid is required');\n if (!role) throw new Error('role is required');\n if (!applicantDid) throw new Error('applicantDid is required');\n if (!applicantAddress) throw new Error('applicantAddress is required');\n\n // ---- Act as the DAO group: propose instead of broadcasting directly ----\n // Approve: the authz-grant chain messages go in the proposal (the GROUP\n // must hold the entity owner's authorization to grant); the Matrix bid\n // status update runs as the finalize step after execution. Reject is\n // Matrix-only, so it is an approval proposal whose finalize performs the\n // rejection.\n if (isGroupExecution(inputs)) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const expectedOutput = {\n bidId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n evaluatedByDid: coreAddress,\n evaluatedAt: new Date().toISOString(),\n reason: decision === 'reject' ? String(inputs.reason || '') : '',\n collectionId,\n role,\n deedDid,\n applicantDid,\n applicantAddress,\n };\n\n if (decision === 'approve') {\n const adminAddress = String(inputs.adminAddress || '').trim();\n if (!adminAddress) throw new Error('adminAddress is required when decision is approve');\n if (!isServiceAgentRole(role) && !isEvaluationAgentRole(role)) {\n throw new Error('Invalid role for evaluation. Expected service_agent or evaluation_agent');\n }\n const groupHandlers = ctx.handlers as any;\n if (typeof groupHandlers?.prepareGroupAgentApplicationApproval !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupAgentApplicationApproval');\n }\n let maxAmounts = inputs.maxAmounts;\n if (typeof maxAmounts === 'string' && maxAmounts.trim()) {\n try {\n maxAmounts = JSON.parse(maxAmounts);\n } catch {\n throw new Error('maxAmounts must be valid JSON when provided');\n }\n }\n const prepared = await groupHandlers.prepareGroupAgentApplicationApproval({\n groupAddress: coreAddress,\n deedDid,\n collectionId,\n adminAddress,\n role: isServiceAgentRole(role) ? 'service_agent' : 'evaluation_agent',\n applicantAddress,\n agentQuota: isServiceAgentRole(role) ? 30 : 10,\n maxAmounts: Array.isArray(maxAmounts) ? maxAmounts : undefined,\n });\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: prepared.msgs || [],\n expectedOutput,\n finalize: 'bid.approve',\n finalizeParams: { bidId, collectionId, did: applicantDid, entityDid: deedDid },\n });\n }\n\n const reason = String(inputs.reason || '').trim();\n if (!reason) throw new Error('reason is required when decision is reject');\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: [],\n expectedOutput,\n finalize: 'bid.reject',\n finalizeParams: { bidId, collectionId, did: deedDid, reason, entityDid: deedDid },\n });\n }\n\n if (decision === 'approve') {\n const adminAddress = String(inputs.adminAddress || '').trim();\n if (!adminAddress) {\n throw new Error('adminAddress is required when decision is approve');\n }\n\n if (isServiceAgentRole(role)) {\n await service.approveServiceAgentApplication({\n adminAddress,\n collectionId,\n agentQuota: 30,\n deedDid,\n currentUserAddress: applicantAddress,\n });\n } else if (isEvaluationAgentRole(role)) {\n let maxAmounts = inputs.maxAmounts;\n if (typeof maxAmounts === 'string') {\n try {\n maxAmounts = JSON.parse(maxAmounts);\n } catch {\n throw new Error('maxAmounts must be valid JSON when provided');\n }\n }\n\n await service.approveEvaluatorApplication({\n adminAddress,\n collectionId,\n deedDid,\n evaluatorAddress: applicantAddress,\n agentQuota: 10,\n maxAmounts: Array.isArray(maxAmounts) ? maxAmounts : undefined,\n });\n } else {\n throw new Error('Invalid role for evaluation. Expected service_agent or evaluation_agent');\n }\n\n await service.approveBid({\n bidId,\n collectionId,\n did: applicantDid,\n entityDid: deedDid,\n });\n } else {\n const reason = String(inputs.reason || '').trim();\n if (!reason) {\n throw new Error('reason is required when decision is reject');\n }\n await service.rejectBid({\n bidId,\n collectionId,\n did: deedDid,\n reason,\n entityDid: deedDid,\n });\n }\n\n return {\n output: {\n bidId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n evaluatedByDid: ctx.actorDid || '',\n evaluatedAt: new Date().toISOString(),\n reason: decision === 'reject' ? String(inputs.reason || '') : '',\n collectionId,\n role,\n deedDid,\n applicantDid,\n applicantAddress,\n },\n };\n },\n});\n","import { registerAction, neverDone } from '../../registry';\nimport { sha256Digest } from '../../digest';\nimport type { ActionEventDefinition, OutputSchemaField } from '../../types';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport { prefixSurveyAnswerSchema } from './surveySchema';\nimport type { ClaimRunInputs } from './types';\n\nconst BASELINE_OUTPUT: OutputSchemaField[] = [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'The submitted claim identifier' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'Submission transaction hash' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'submittedByDid', displayName: 'Submitted By DID', type: 'string', description: 'Actor DID that submitted the claim' },\n { path: 'submittedAt', displayName: 'Submitted At', type: 'string', description: 'ISO timestamp of submission' },\n];\n\nregisterAction<ClaimRunInputs>({\n type: 'qi/claim.submit',\n can: 'claim/submit',\n sideEffect: true,\n // Dynamic resolvers predate merge-by-default and intentionally control\n // the full vocabulary (e.g. returning [] to hide the static baseline).\n dynamicResolutionMode: 'replace',\n proof: { fields: ['claimId'] },\n done: neverDone,\n // Repeatable: a collection accepts many claims over the flow's life (e.g. a\n // monthly submission). Never latches to a terminal Done. See cardinality.\n cardinality: 'many',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['deedDid', 'collectionId', 'adminAddress', 'surveyAnswers'],\n properties: {\n deedDid: { type: 'string', description: 'The entity/deed DID that owns the claim collection.' },\n collectionId: { type: 'string', description: 'The claim collection to submit into.' },\n adminAddress: { type: 'string', description: \"The claim collection admin's chain address.\" },\n surveyAnswers: { type: 'object', description: \"The claim's answer data (the submitted form); may be passed as an object or a JSON string.\" },\n pin: { type: 'string', description: 'Verification PIN; requested at runtime if omitted.' },\n },\n },\n // Static fallback — used until a collection is picked and the survey\n // schema is materialised. `getDynamicOutputSchema` takes over after that.\n outputSchema: BASELINE_OUTPUT,\n /**\n * Per-block output schema — same shape as `run()`'s `output`. Picks up the\n * materialised survey schema so the DataInput reference picker can surface\n * `output.surveyAnswers.<question>` alongside the baseline claim fields.\n */\n getDynamicOutputSchema: (inputs): OutputSchemaField[] => {\n const schema: OutputSchemaField[] = Array.isArray((inputs as any)?.surveyAnswersSchema) ? (inputs as any).surveyAnswersSchema : [];\n if (schema.length === 0) return BASELINE_OUTPUT;\n return [...BASELINE_OUTPUT, ...prefixSurveyAnswerSchema(schema)];\n },\n /**\n * Per-block event resolver. Returns `[]` until a claim collection has been\n * picked in template mode (which is when we can materialise the survey's\n * answer schema into inputs). Once present, emits a `submitted` event with\n * baseline claim fields plus `surveyAnswers.<question>` for every question\n * in the survey template — letting listener blocks consume typed refs like\n * `${sourceBlock.payload.surveyAnswers.email}`.\n */\n getDynamicEvents: (inputs): ActionEventDefinition[] => {\n const schema: OutputSchemaField[] = Array.isArray((inputs as any)?.surveyAnswersSchema) ? (inputs as any).surveyAnswersSchema : [];\n if (schema.length === 0) return [];\n\n const surveyFields = prefixSurveyAnswerSchema(schema);\n return [\n {\n name: 'submitted',\n displayName: 'Claim submitted',\n description: 'Fires when a claim is submitted to this collection. Payload includes the submitted survey answers, fully typed to the collection survey.',\n payloadSchema: [...BASELINE_OUTPUT, ...surveyFields],\n pendingDisplayFields: ['claimId', 'submittedAt'],\n },\n ];\n },\n run: async (inputs, ctx) => {\n const service = ctx.services.claim;\n if (!service) {\n throw new Error('Claim service not configured');\n }\n\n const deedDid = String(inputs.deedDid || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const adminAddress = String(inputs.adminAddress || '').trim();\n\n if (!deedDid) throw new Error('deedDid is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!adminAddress) throw new Error('adminAddress is required');\n\n let surveyAnswers = inputs.surveyAnswers;\n if (typeof surveyAnswers === 'string') {\n try {\n surveyAnswers = JSON.parse(surveyAnswers);\n } catch {\n throw new Error('surveyAnswers must be valid JSON');\n }\n }\n\n if (!surveyAnswers || typeof surveyAnswers !== 'object' || Array.isArray(surveyAnswers)) {\n throw new Error('surveyAnswers must be an object');\n }\n\n let pin = String(inputs.pin || '').trim();\n if (!pin) {\n pin = await service.requestPin({\n title: 'Verify Identity',\n description: 'Enter your PIN to submit the claim',\n submitText: 'Verify',\n });\n }\n if (!pin) {\n throw new Error('PIN is required to submit claim');\n }\n\n // ---- Act as the DAO group: propose instead of broadcasting directly ----\n // The off-chain prep (credential + Matrix upload) still runs as the user;\n // the on-chain MsgSubmitClaim is built with the GROUP as the agent and\n // wrapped in a governance proposal. claimId (the Matrix CID) is known at\n // prepare time, so downstream references resolve once the proposal\n // executes and the block completes via read-back.\n if (isGroupExecution(inputs)) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const handlers = ctx.handlers as any;\n if (typeof handlers?.prepareGroupClaimSubmission !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupClaimSubmission');\n }\n const prepared = await handlers.prepareGroupClaimSubmission({\n surveyData: surveyAnswers,\n deedDid,\n entityDid: deedDid,\n collectionId,\n adminAddress,\n pin,\n groupAddress: coreAddress,\n });\n const claimId = String(prepared?.claimId || '').trim();\n if (!claimId) throw new Error('prepareGroupClaimSubmission returned no claim identifier');\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: prepared.msgs || [],\n expectedOutput: {\n claimId,\n transactionHash: '',\n collectionId,\n deedDid,\n submittedByDid: coreAddress,\n submittedAt: new Date().toISOString(),\n surveyAnswers: surveyAnswers as Record<string, unknown>,\n },\n completionEvent: 'submitted',\n });\n }\n\n const result = await service.submitClaim({\n surveyData: surveyAnswers,\n deedDid,\n entityDid: deedDid,\n collectionId,\n adminAddress,\n pin,\n });\n\n const claimId = String((result as any)?.claimId || (result as any)?.id || '');\n if (!claimId) {\n throw new Error('submitClaim returned no claim identifier');\n }\n\n const transactionHash = String((result as any)?.transactionHash || '');\n const submittedByDid = ctx.actorDid || '';\n const submittedAt = new Date().toISOString();\n // Include the submitted answers in `output` — that's what downstream\n // blocks reference as `${thisBlock.output.surveyAnswers.<question>}` and\n // is also what the DataInput picker surfaces via `getDynamicOutputSchema`.\n const output = {\n claimId,\n transactionHash,\n collectionId,\n deedDid,\n submittedByDid,\n submittedAt,\n surveyAnswers: surveyAnswers as Record<string, unknown>,\n };\n\n return {\n output,\n topicRecords: ctx.topic\n ? [\n {\n type: 'org.ixo.topic.claim-submission',\n id: sha256Digest({ topicId: ctx.topic.topicId, collectionId, claimId }),\n version: 1,\n value: {\n claimId,\n collectionId,\n deedDid,\n submittedByDid,\n submittedAt,\n transactionHash,\n submissionDigest: sha256Digest(surveyAnswers),\n },\n },\n ]\n : undefined,\n events: [\n {\n name: 'submitted',\n payload: output,\n },\n ],\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport { sha256Digest } from '../../digest';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { ActionDoneContract, ActionEventDefinition, OutputSchemaField } from '../../types';\nimport { buildXeroInvoiceWorkKey, upsertXeroWorkItemForEditor } from '../../../xeroWorkItems';\nimport { prefixSurveyAnswerSchema } from '../claim/surveySchema';\nimport type { EvaluateClaimRunInputs } from './types';\nimport { PENDING_CLAIM_SNAPSHOT_SOURCE, fetchPendingClaimSnapshot, readPendingClaimSnapshot, type PendingClaimSnapshot } from './pendingClaims';\n\nconst PENDING_SNAPSHOT_OUTPUT: OutputSchemaField[] = [\n { path: 'pendingClaimCount', displayName: 'Pending Claims', type: 'number', description: 'Claims still awaiting evaluation as of the last check' },\n { path: 'pendingCheckedAt', displayName: 'Pending Checked At', type: 'number', description: 'Unix ms of the last pending-claims check' },\n { path: 'collectionClosed', displayName: 'Collection Closed', type: 'boolean', description: 'The collection no longer accepts claims' },\n];\n\n/**\n * Done is \"no pending claims as of the last check\", read from the snapshot\n * stored on the block. The fold never touches Blocksync; `check` is the one\n * explicit read, invoked after an evaluation, when the block is opened, and\n * on a close attempt. A completed entry whose collection refills goes back\n * to active (`reopenable`), it is not a contradicted completion.\n */\nconst evaluateClaimDone: ActionDoneContract<EvaluateClaimRunInputs> = {\n isDone: (state) => state.state === 'completed' && readPendingClaimSnapshot(state.output)?.pendingClaimCount === 0,\n reopenable: true,\n check: async ({ inputs, actionState, ctx }) => {\n if (actionState.state !== 'completed') {\n return { done: false, source: PENDING_CLAIM_SNAPSHOT_SOURCE, reason: 'No claim has been evaluated in this session yet.' };\n }\n const collectionId = String(inputs.collectionId || actionState.output?.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || actionState.output?.deedDid || '').trim();\n if (!collectionId) {\n return { done: 'unknown', source: PENDING_CLAIM_SNAPSHOT_SOURCE, reason: 'No collection is configured for this block.' };\n }\n try {\n const snapshot = await fetchPendingClaimSnapshot(ctx.handlers, { collectionId, deedDid }, ctx.now);\n return {\n done: snapshot.pendingClaimCount === 0,\n source: PENDING_CLAIM_SNAPSHOT_SOURCE,\n output: { ...snapshot },\n ...(snapshot.pendingClaimCount > 0 ? { reason: `${snapshot.pendingClaimCount} claim(s) still await evaluation.` } : {}),\n };\n } catch (error) {\n return {\n done: 'unknown',\n source: PENDING_CLAIM_SNAPSHOT_SOURCE,\n reason: error instanceof Error ? error.message : 'Pending claims could not be read.',\n };\n }\n },\n};\n\nconst BASELINE_OUTPUT: OutputSchemaField[] = [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'Evaluated claim identifier' },\n { path: 'decision', displayName: 'Decision', type: 'string', description: 'approve or reject' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'approved or rejected' },\n { path: 'verificationProof', displayName: 'Verification Proof', type: 'string', description: 'UDID URL proof if generated' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'On-chain evaluation transaction hash' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection identifier' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Deed identifier' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that evaluated the claim' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string', description: 'ISO timestamp of evaluation' },\n ...PENDING_SNAPSHOT_OUTPUT,\n];\n\nconst BASELINE_APPROVED_EVENT: OutputSchemaField[] = [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'Approved claim identifier' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that approved the claim' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string' },\n { path: 'verificationProof', displayName: 'Verification Proof', type: 'string' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'On-chain approval transaction hash — proof of payout' },\n];\n\nconst BASELINE_REJECTED_EVENT: OutputSchemaField[] = [\n { path: 'claimId', displayName: 'Claim ID', type: 'string', description: 'Rejected claim identifier' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string' },\n { path: 'evaluatedByDid', displayName: 'Evaluated By DID', type: 'string', description: 'Actor DID that rejected the claim' },\n { path: 'evaluatedAt', displayName: 'Evaluated At', type: 'string' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'On-chain rejection transaction hash' },\n];\n\ntype Decision = 'approve' | 'reject';\n\nfunction normalizeDecision(value: unknown): Decision {\n const normalized = String(value || '')\n .trim()\n .toLowerCase();\n if (normalized === 'approve' || normalized === 'reject') {\n return normalized;\n }\n throw new Error('decision must be either approve or reject');\n}\n\nfunction toStatus(decision: Decision): number {\n return decision === 'approve' ? 1 : 2;\n}\n\nfunction isEvaluatorRole(role: unknown): boolean {\n const normalized = String(role || '')\n .trim()\n .toLowerCase();\n return normalized === 'ea' || normalized === 'evaluation_agent';\n}\n\n/**\n * Template inputs pass through the reference resolver, so a boolean flag may\n * arrive as a real boolean or a serialised string. Anything else is false.\n */\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value === 'number') return value === 1;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'on';\n }\n return false;\n}\n\nconst XERO_INVOICE_DEFAULT_KEYS = ['Type', 'Status', 'CurrencyCode', 'tenant_id', 'ContactID', 'ContactName', 'AccountCode'] as const;\n\n/**\n * §4.2 `invoiceDefaults` — template-level pins for the contracted\n * xero-oracle. Only non-empty pins are carried; `Type` defaults to ACCREC and\n * `Status` to DRAFT (the phase-1 rule — the oracle hard-forces this after\n * extraction, but the payload states it explicitly).\n */\nfunction buildXeroInvoiceDefaults(raw: unknown): Record<string, string> {\n const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n const defaults: Record<string, string> = {};\n for (const key of XERO_INVOICE_DEFAULT_KEYS) {\n const value = String(source[key] ?? '').trim();\n if (value) defaults[key] = value;\n }\n if (!defaults.Type) defaults.Type = 'ACCREC';\n if (!defaults.Status) defaults.Status = 'DRAFT';\n return defaults;\n}\n\nregisterAction<EvaluateClaimRunInputs>({\n type: 'qi/claim.evaluate',\n can: 'claim/evaluate',\n sideEffect: true,\n // Dynamic resolvers predate merge-by-default and intentionally control\n // the full vocabulary (e.g. returning [] to hide the static baseline).\n dynamicResolutionMode: 'replace',\n proof: { fields: ['claimId'] },\n done: evaluateClaimDone,\n // Repeatable: an evaluator processes many claims over the flow's life. Done\n // is a snapshot (\"no pending claims as of the last check\") that reopens when\n // the collection refills; the session close is what makes it permanent.\n cardinality: 'many',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n // Static fallback — used until a collection is picked and the survey\n // schema is materialised. `getDynamicOutputSchema` takes over after that.\n outputSchema: BASELINE_OUTPUT,\n /**\n * Per-block output schema. Surfaces `output.surveyAnswers.<question>`\n * alongside the baseline evaluation fields once the template author has\n * picked a collection and the survey schema has been materialised into\n * inputs. Lets DataInput pickers reference typed survey fields downstream.\n */\n getDynamicOutputSchema: (inputs): OutputSchemaField[] => {\n const schema: OutputSchemaField[] = Array.isArray((inputs as any)?.surveyAnswersSchema) ? (inputs as any).surveyAnswersSchema : [];\n if (schema.length === 0) return BASELINE_OUTPUT;\n return [...BASELINE_OUTPUT, ...prefixSurveyAnswerSchema(schema)];\n },\n events: [\n {\n name: 'approved',\n displayName: 'Approved',\n description: 'Fires when an evaluator approves the claim.',\n payloadSchema: BASELINE_APPROVED_EVENT,\n pendingDisplayFields: ['claimId', 'evaluatedAt'],\n },\n {\n name: 'rejected',\n displayName: 'Rejected',\n description: 'Fires when an evaluator rejects the claim.',\n payloadSchema: BASELINE_REJECTED_EVENT,\n pendingDisplayFields: ['claimId', 'evaluatedAt'],\n },\n ],\n /**\n * Per-block event schema — same idea as `getDynamicOutputSchema`. Adds the\n * survey-answer fields to both `approved` and `rejected` event payloads\n * so listener blocks (e.g. `qi/xero.invoice.create`) can reference\n * `${sourceBlock.payload.surveyAnswers.<field>}` with typed paths.\n */\n getDynamicEvents: (inputs): ActionEventDefinition[] => {\n const schema: OutputSchemaField[] = Array.isArray((inputs as any)?.surveyAnswersSchema) ? (inputs as any).surveyAnswersSchema : [];\n const surveyFields = schema.length > 0 ? prefixSurveyAnswerSchema(schema) : [];\n return [\n {\n name: 'approved',\n displayName: 'Approved',\n description: 'Fires when an evaluator approves the claim.',\n payloadSchema: [...BASELINE_APPROVED_EVENT, ...surveyFields],\n pendingDisplayFields: ['claimId', 'evaluatedAt'],\n },\n {\n name: 'rejected',\n displayName: 'Rejected',\n description: 'Fires when an evaluator rejects the claim.',\n payloadSchema: [...BASELINE_REJECTED_EVENT, ...surveyFields],\n pendingDisplayFields: ['claimId', 'evaluatedAt'],\n },\n ];\n },\n inputSchema: {\n type: 'object',\n required: ['decision', 'claimId', 'collectionId', 'deedDid', 'adminAddress'],\n properties: {\n decision: { type: 'string', description: 'Evaluation decision: approve or reject.' },\n claimId: { type: 'string', description: 'Identifier of the claim being evaluated.' },\n collectionId: { type: 'string', description: 'Claim collection identifier.' },\n deedDid: { type: 'string', description: 'Deed (entity) DID.' },\n adminAddress: { type: 'string', description: 'Entity admin account address for the on-chain evaluation.' },\n amount: { type: 'object', description: 'Payout coin (denom + amount); accepts a JSON string, object, or array.' },\n createUdid: { type: 'boolean', description: 'Whether to generate and sign a verification UDID proof.' },\n capabilityCid: { type: 'string', description: 'Capability CID used when creating the UDID; defaults to deedDid.' },\n rubricAuthority: { type: 'string', description: 'Rubric authority used when creating the UDID; defaults to deedDid.' },\n rubricId: { type: 'string', description: 'Rubric identifier used when creating the UDID; defaults to deedDid.' },\n granteeAddress: { type: 'string', description: 'Evaluator address; resolves to the current user when omitted.' },\n verificationProof: { type: 'string', description: 'Pre-existing verification proof URL; skips UDID creation when set.' },\n traceCid: { type: 'string', description: 'Trace CID passed through to the UDID.' },\n items: { type: 'array', description: 'Evaluation items passed through to the UDID.' },\n patch: { type: 'object', description: 'Patch object passed through to the UDID.' },\n xeroOracleInvoiceOnApprove: { type: 'boolean', description: 'Create a Xero draft invoice via the contracted xero-oracle when a claim is approved.' },\n xeroInvoiceDefaults: {\n type: 'object',\n description: 'Optional template-level Xero invoice defaults (Type, Status, CurrencyCode, tenant_id, ContactID, ContactName) pinned into the invoice work payload.',\n },\n claimSnapshot: { type: 'object', description: 'Claim snapshot used to build the Xero invoice work payload.' },\n },\n },\n run: async (inputs, ctx) => {\n const service = ctx.services.claim;\n if (!service) {\n throw new Error('Claim service not configured');\n }\n\n const decision = normalizeDecision(inputs.decision);\n const claimId = String(inputs.claimId || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n const adminAddress = String(inputs.adminAddress || '').trim();\n\n if (!claimId) throw new Error('claimId is required');\n if (!collectionId) throw new Error('collectionId is required');\n if (!deedDid) throw new Error('deedDid is required');\n if (!adminAddress) throw new Error('adminAddress is required');\n\n // Action-level authorization guard: evaluator role is required. When\n // acting as the DAO group, the GROUP's account is the evaluating agent —\n // it must hold the evaluator authorization, not the initiating user.\n const handlers = ctx.handlers;\n const groupMode = isGroupExecution(inputs);\n const actorAddress = groupMode ? String(inputs.groupCoreAddress || '').trim() : String(ctx.actorDid || service.getCurrentUser?.()?.address || '').trim();\n if (!actorAddress) {\n throw new Error('Unable to resolve actor address for evaluator authorization');\n }\n\n if (typeof handlers?.getUserRoles !== 'function') {\n throw new Error('Evaluator authorization check unavailable (getUserRoles handler missing)');\n }\n\n const roles = await handlers.getUserRoles({\n userAddress: actorAddress,\n adminAddress,\n deedDid,\n collectionIds: [collectionId],\n });\n\n const roleForCollection = Array.isArray(roles) ? roles.find((r: any) => r?.collectionId === collectionId)?.role : undefined;\n if (!isEvaluatorRole(roleForCollection)) {\n throw new Error('Not authorized: evaluator role required to evaluate claims for this collection');\n }\n\n // Host's evaluateClaim takes a single Coin. Inputs may be supplied as a\n // JSON string, an object, or (legacy) an array — we accept all three but\n // collapse to the first coin for the on-chain call.\n let amount = inputs.amount;\n if (typeof amount === 'string' && amount.trim()) {\n try {\n amount = JSON.parse(amount);\n } catch {\n throw new Error('amount must be valid JSON when provided as string');\n }\n }\n\n const normalizeCoin = (coin: any) => {\n if (!coin || typeof coin !== 'object' || Array.isArray(coin)) return null;\n const denom = String(coin.denom || '').trim();\n const tokenAmount = String(coin.amount || '').trim();\n if (!denom || !tokenAmount) return null;\n return { denom, amount: tokenAmount };\n };\n\n let normalizedCoin: { denom: string; amount: string } | undefined;\n if (Array.isArray(amount)) {\n const coins = amount.map(normalizeCoin).filter((coin): coin is { denom: string; amount: string } => !!coin);\n if (coins.length !== amount.length) {\n throw new Error('amount must contain valid coin objects with denom and amount');\n }\n normalizedCoin = coins[0];\n } else if (amount != null) {\n const coin = normalizeCoin(amount);\n if (!coin) {\n throw new Error('amount must be a coin object with denom and amount');\n }\n normalizedCoin = coin;\n }\n\n let verificationProof = String(inputs.verificationProof || '').trim();\n const shouldCreateUdid = Boolean(inputs.createUdid);\n\n if (!verificationProof && shouldCreateUdid && service.createUdid) {\n const pin = await service.requestPin({\n title: 'Sign Evaluation Result',\n description: 'Enter your PIN to sign the evaluation UDID',\n submitText: 'Sign',\n });\n\n if (!pin) {\n throw new Error('PIN is required to sign evaluation proof');\n }\n\n const udid = await service.createUdid({\n claimCid: claimId,\n deedDid,\n collectionId,\n capabilityCid: String(inputs.capabilityCid || deedDid),\n rubricAuthority: String(inputs.rubricAuthority || deedDid),\n rubricId: String(inputs.rubricId || deedDid),\n outcome: toStatus(decision),\n tag: decision === 'approve' ? 'approved' : 'rejected',\n issuerType: 'user',\n pin,\n traceCid: inputs.traceCid,\n items: inputs.items,\n patch: inputs.patch as Record<string, any> | undefined,\n });\n\n verificationProof = String((udid as any)?.url || (udid as any)?.cid || '');\n }\n\n // ---- Act as the DAO group: propose instead of broadcasting directly ----\n if (groupMode) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const groupHandlers = ctx.handlers as any;\n if (typeof groupHandlers?.prepareGroupClaimEvaluation !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupClaimEvaluation');\n }\n const prepared = await groupHandlers.prepareGroupClaimEvaluation({\n groupAddress: coreAddress,\n deedDid,\n claimId,\n collectionId,\n adminAddress,\n status: toStatus(decision),\n verificationProof,\n amount: normalizedCoin,\n });\n\n // Best-effort survey answers for the expected output, same as the\n // direct path does after broadcast.\n let expectedSurveyAnswers: Record<string, unknown> = {};\n try {\n const getClaimData = groupHandlers?.getClaimData;\n if (typeof getClaimData === 'function') {\n const claim = await getClaimData(collectionId, claimId, { entityDid: deedDid });\n const candidate = claim?.credentialSubject ?? claim?.surveyAnswers ?? claim;\n if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {\n expectedSurveyAnswers = candidate as Record<string, unknown>;\n }\n }\n } catch {\n // Survey fields are nice-to-have on the evaluation output.\n }\n\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: prepared.msgs || [],\n expectedOutput: {\n claimId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n verificationProof,\n transactionHash: '',\n collectionId,\n deedDid,\n evaluatedByDid: coreAddress,\n evaluatedAt: new Date().toISOString(),\n surveyAnswers: expectedSurveyAnswers,\n },\n completionEvent: 'evaluated',\n });\n }\n\n const currentUser = service.getCurrentUser();\n const granteeAddress = String((inputs.granteeAddress as string) || currentUser?.address || '').trim();\n if (!granteeAddress) {\n throw new Error('granteeAddress could not be resolved');\n }\n\n const broadcastResult = await service.evaluateClaim(granteeAddress, deedDid, {\n claimId,\n collectionId,\n adminAddress,\n status: toStatus(decision),\n verificationProof,\n amount: normalizedCoin,\n });\n const transactionHash = String(broadcastResult?.transactionHash || '');\n\n // Fetch the claim's survey answers so listener blocks (and the action's\n // own output) carry typed `surveyAnswers.<field>` paths matching\n // `getDynamicOutputSchema` / `getDynamicEvents`. Best-effort: if the\n // handler isn't wired or the fetch fails we still emit the evaluation\n // event — listeners just won't see survey fields.\n let claimData: any = null;\n let surveyAnswers: Record<string, unknown> = {};\n try {\n const getClaimData = handlers?.getClaimData;\n if (typeof getClaimData === 'function') {\n claimData = await getClaimData(collectionId, claimId, { entityDid: deedDid });\n const candidate = claimData?.credentialSubject ?? claimData?.surveyAnswers ?? claimData;\n if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {\n surveyAnswers = candidate as Record<string, unknown>;\n }\n }\n } catch {\n // Swallow — survey fields are nice-to-have on the evaluation output.\n }\n\n // The \"is there more work?\" snapshot, taken right after the broadcast so\n // the run record carries it and the session summary can fold Done without\n // a Blocksync read. Best-effort: a failed read stores no snapshot, so the\n // block folds as not done until its next refresh records one.\n let pendingSnapshot: PendingClaimSnapshot | null = null;\n try {\n pendingSnapshot = await fetchPendingClaimSnapshot(handlers, { collectionId, deedDid }, Date.now());\n } catch {\n pendingSnapshot = null;\n }\n\n const evaluatedByDid = ctx.actorDid || granteeAddress;\n const evaluatedAt = new Date().toISOString();\n const output = {\n claimId,\n decision,\n status: decision === 'approve' ? 'approved' : 'rejected',\n verificationProof,\n transactionHash,\n collectionId,\n deedDid,\n evaluatedByDid,\n evaluatedAt,\n surveyAnswers,\n ...(pendingSnapshot ?? {}),\n };\n\n // ── Xero oracle invoice work (§4.1/§4.2) ──\n // When the template author enabled \"Xero oracle invoice on approval\",\n // an approval upserts a pending invoice work item into the flow doc's\n // `xeroWorkItems` map. Flow-manager's tick scans for these, contracts the\n // xero-oracle, and sends `originalPayload` by value (injecting the\n // top-level `idempotencyKey` at contract time — it is NOT part of the\n // payload written here). One item per approved claim per evaluation\n // block; re-approvals re-upsert the same key and `mergeItem` protects\n // completed items.\n if (decision === 'approve' && isTruthyFlag(inputs.xeroOracleInvoiceOnApprove)) {\n const flowId = String(ctx.flowId || ctx.flowUri || 'flow');\n const claimSnapshot =\n inputs.claimSnapshot && typeof inputs.claimSnapshot === 'object' && !Array.isArray(inputs.claimSnapshot) ? (inputs.claimSnapshot as Record<string, any>) : undefined;\n\n // Materialised survey schema, as available to this action: prefer\n // questions carried on the claim snapshot, falling back to the\n // template's materialised `surveyAnswersSchema`.\n const surveyQuestions: unknown[] = Array.isArray(claimSnapshot?.surveyQuestions)\n ? claimSnapshot.surveyQuestions\n : Array.isArray((inputs as any)?.surveyAnswersSchema)\n ? (inputs as any).surveyAnswersSchema\n : [];\n\n const idempotencyKey = buildXeroInvoiceWorkKey({ flowId, evaluationBlockId: ctx.nodeId, claimId });\n const originalPayload: Record<string, any> = {\n claim: { claimId, collectionId, deedDid },\n surveyQuestions,\n surveyAnswers,\n evaluation: {\n decision,\n // Left out when the evaluation carries no payout coin. Writing the\n // key with `undefined` puts a member into the flow document that\n // JSON has no spelling for, and Yjs keeps it: flow-manager's\n // bounded action view refused the whole record with\n // `INVALID_RECORD: Non-JSON value`, so the work item sat pending and\n // the invoice was never contracted.\n ...(normalizedCoin ? { amount: normalizedCoin } : {}),\n evaluatedByDid,\n evaluatedAt,\n verificationProof,\n transactionHash,\n },\n invoiceDefaults: buildXeroInvoiceDefaults(inputs.xeroInvoiceDefaults),\n };\n\n upsertXeroWorkItemForEditor(ctx.editor, {\n id: idempotencyKey,\n kind: 'invoice.create',\n status: 'pending',\n assignedBlockId: ctx.nodeId,\n idempotencyKey,\n source: {\n claimId,\n evaluationBlockId: ctx.nodeId,\n deedDid,\n collectionId,\n },\n originalPayload,\n reviewPayload: originalPayload,\n provenance: {\n createdAt: Date.now(),\n createdByDid: ctx.actorDid,\n templateBlockId: ctx.nodeId,\n evaluationOutput: output,\n claimSnapshot,\n },\n attempts: [],\n });\n }\n\n // Emit a semantic event so listeners can be wired to approval/rejection\n // outcomes specifically. The runtime persists these as part of the run\n // record and the reconciliation loop turns them into pending invocations\n // on subscribed listener blocks. See docs/flow-engine/events-and-triggers-plan.md.\n const eventName = decision === 'approve' ? 'approved' : 'rejected';\n const eventPayload =\n decision === 'approve'\n ? {\n claimId,\n collectionId,\n deedDid,\n evaluatedByDid,\n evaluatedAt,\n verificationProof,\n transactionHash,\n surveyAnswers,\n }\n : {\n claimId,\n collectionId,\n deedDid,\n evaluatedByDid,\n evaluatedAt,\n transactionHash,\n surveyAnswers,\n };\n\n return {\n output,\n topicRecords: ctx.topic\n ? [\n {\n type: 'org.ixo.topic.claim-evaluation',\n id: sha256Digest({ topicId: ctx.topic.topicId, collectionId, claimId, evaluatedAt, decision }),\n version: 1,\n value: {\n claimId,\n collectionId,\n deedDid,\n decision,\n evaluatedByDid,\n evaluatedAt,\n verificationProof,\n transactionHash,\n evidenceDigest: sha256Digest(surveyAnswers),\n },\n evidenceReferences: verificationProof ? [verificationProof] : [],\n },\n ]\n : undefined,\n events: [{ name: eventName, payload: eventPayload }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { sha256Digest } from '../digest';\n\nregisterAction({\n type: 'qi/proposal.create',\n can: 'proposal/create',\n sideEffect: true,\n proof: { fields: ['proposalId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n inputSchema: {\n type: 'object',\n required: ['coreAddress', 'title', 'description'],\n properties: {\n coreAddress: { type: 'string', description: 'The DAO core contract address.' },\n title: { type: 'string', description: 'The proposal title.' },\n description: { type: 'string', description: 'The proposal description.' },\n actions: { type: 'array', description: 'Optional proposal actions (array or JSON string array).' },\n },\n },\n\n outputSchema: [\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The on-chain proposal identifier' },\n { path: 'status', displayName: 'Proposal Status', type: 'string', description: 'Current proposal status (open, passed, rejected, executed, etc.)' },\n { path: 'proposalContractAddress', displayName: 'Proposal Contract Address', type: 'string', description: 'The proposal module contract address' },\n { path: 'coreAddress', displayName: 'Core Address', type: 'string', description: 'The DAO core contract address' },\n { path: 'createdAt', displayName: 'Created At', type: 'string', description: 'ISO timestamp of proposal creation' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.getPreProposalContractAddress || !handlers.getGroupContractAddress || !handlers.getProposalContractAddress || !handlers.createProposal) {\n throw new Error('Governance proposal handlers not available');\n }\n\n const coreAddress = String(inputs.coreAddress || '').trim();\n const title = String(inputs.title || '').trim();\n const description = String(inputs.description || '').trim();\n\n if (!coreAddress) throw new Error('coreAddress is required');\n if (!title) throw new Error('title is required');\n if (!description) throw new Error('description is required');\n\n let actions: any[] = [];\n if (inputs.actions) {\n if (typeof inputs.actions === 'string') {\n try {\n actions = JSON.parse(inputs.actions);\n } catch {\n throw new Error('actions must be valid JSON array');\n }\n } else if (Array.isArray(inputs.actions)) {\n actions = inputs.actions;\n }\n }\n\n // Get pre-proposal and group contract addresses\n const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({\n coreAddress,\n });\n\n const { groupContractAddress } = await handlers.getGroupContractAddress({\n coreAddress,\n });\n\n const { proposalContractAddress } = await handlers.getProposalContractAddress({\n coreAddress,\n });\n\n const params = {\n preProposalContractAddress,\n title,\n description,\n actions: actions.length > 0 ? actions : undefined,\n coreAddress,\n groupContractAddress,\n };\n\n const proposalId = await handlers.createProposal(params);\n\n return {\n output: {\n proposalId: String(proposalId),\n status: 'open',\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n createdAt: new Date().toISOString(),\n },\n topicRecords: ctx.topic\n ? [\n {\n type: 'org.ixo.topic.proposal-receipt',\n id: sha256Digest({ topicId: ctx.topic.topicId, proposalContractAddress, proposalId }),\n version: 1,\n value: {\n event: 'created',\n proposalId: String(proposalId),\n proposalContractAddress: proposalContractAddress || '',\n coreAddress,\n title,\n descriptionDigest: sha256Digest(description),\n status: 'open',\n },\n },\n ]\n : undefined,\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { sha256Digest } from '../digest';\n\nregisterAction({\n type: 'qi/proposal.vote',\n can: 'proposal/vote',\n sideEffect: true,\n proof: { fields: ['votedAt'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n inputSchema: {\n type: 'object',\n required: ['proposalId', 'vote', 'proposalContractAddress'],\n properties: {\n proposalId: { type: 'number', description: 'The proposal number to vote on.' },\n vote: { type: 'string', description: 'The vote to cast: yes, no, or abstain.' },\n proposalContractAddress: { type: 'string', description: 'The proposal module contract address.' },\n rationale: { type: 'string', description: 'Optional rationale provided with the vote.' },\n },\n },\n\n outputSchema: [\n { path: 'vote', displayName: 'Vote', type: 'string', description: 'The vote cast (yes, no, abstain)' },\n { path: 'rationale', displayName: 'Rationale', type: 'string', description: 'Optional rationale provided with the vote' },\n { path: 'proposalId', displayName: 'Proposal ID', type: 'string', description: 'The proposal that was voted on' },\n { path: 'votedAt', displayName: 'Voted At', type: 'string', description: 'ISO timestamp of when the vote was cast' },\n ],\n\n run: async (inputs, ctx) => {\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('Handlers not available');\n }\n if (!handlers.vote) {\n throw new Error('vote handler not available');\n }\n\n const proposalId = Number(inputs.proposalId);\n const vote = String(inputs.vote || '').trim();\n const rationale = String(inputs.rationale || '').trim();\n const proposalContractAddress = String(inputs.proposalContractAddress || '').trim();\n\n if (!proposalId || isNaN(proposalId)) throw new Error('proposalId is required');\n if (!vote) throw new Error('vote is required');\n if (!proposalContractAddress) throw new Error('proposalContractAddress is required');\n\n // dao_proposal_single accepts exactly these three options; anything else\n // (e.g. no_with_veto) is rejected by the contract.\n const validVotes = ['yes', 'no', 'abstain'];\n if (!validVotes.includes(vote)) {\n throw new Error(`vote must be one of: ${validVotes.join(', ')}`);\n }\n\n await handlers.vote({\n proposalId,\n vote,\n rationale: rationale || undefined,\n proposalContractAddress,\n });\n\n const votedAt = new Date().toISOString();\n return {\n output: {\n vote,\n rationale: rationale || '',\n proposalId: String(proposalId),\n votedAt,\n },\n topicRecords: ctx.topic\n ? [\n {\n type: 'org.ixo.topic.proposal-receipt',\n id: sha256Digest({ topicId: ctx.topic.topicId, proposalContractAddress, proposalId, actorDid: ctx.actorDid, votedAt }),\n version: 1,\n value: {\n event: 'vote-cast',\n proposalId: String(proposalId),\n proposalContractAddress,\n vote,\n rationaleDigest: sha256Digest(rationale),\n actorDid: ctx.actorDid,\n votedAt,\n },\n },\n ]\n : undefined,\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/protocol.select',\n can: 'protocol/select',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['selectedProtocolDid'],\n properties: {\n selectedProtocolDid: { type: 'string', description: 'DID of the protocol to select.' },\n selectedProtocolName: { type: 'string', description: 'Display name of the selected protocol.' },\n selectedProtocolType: { type: 'string', description: 'Type of the selected protocol.' },\n },\n },\n\n outputSchema: [\n { path: 'selectedProtocolDid', displayName: 'Selected Protocol DID', type: 'string', description: 'DID of the selected protocol' },\n { path: 'selectedProtocolName', displayName: 'Selected Protocol Name', type: 'string', description: 'Display name of the selected protocol' },\n { path: 'selectedProtocolType', displayName: 'Selected Protocol Type', type: 'string', description: 'Type of the selected protocol' },\n ],\n\n run: async (inputs, _ctx) => {\n const selectedProtocolDid = String(inputs.selectedProtocolDid || '').trim();\n const selectedProtocolName = String(inputs.selectedProtocolName || '').trim();\n const selectedProtocolType = String(inputs.selectedProtocolType || '').trim();\n\n if (!selectedProtocolDid) throw new Error('selectedProtocolDid is required');\n\n return {\n output: {\n selectedProtocolDid,\n selectedProtocolName,\n selectedProtocolType,\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { parseMaybeJsonObject } from '../inputRequirements';\n\n/**\n * @description Oracle-enriched preview and human approval gate for a Domain Card.\n *\n * This is the middle stage of the three-step pipeline:\n * card-build → card-preview → sign\n *\n * The action itself is a thin validator: it trusts that the UI has already\n * collected oracle-enriched preview data and a human approval, and echoes\n * the approved `domainCardData` forward so `qi/domain.sign` can consume it.\n *\n * Oracle integration contract — the oracle agent writes its enrichment into\n * the flow node's `runtime.output` under:\n * - `runtime.output.domainPreviewData` (DomainCardResponse UI preview shape)\n * - `runtime.output.domainCardData` (W3C credentialSubject envelope)\n * - `runtime.output.status` ('pending' | 'loading' | 'ready' | 'approved' | 'error')\n * - `runtime.output.loadingMessage` (optional)\n * - `runtime.output.errorMessage` (optional)\n *\n * The FlowDetail component reads these from `runtime.output`, renders the\n * preview, and on user approval calls `updateRuntime` with status='approved'\n * and re-emits `domainCardData` so downstream steps resolve it via the\n * reference resolver.\n */\nregisterAction({\n type: 'qi/domain.card-preview',\n can: 'domain/card-preview',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['domainCardData'],\n properties: {\n domainCardData: {\n type: 'object',\n description: 'Domain card envelope (object or JSON string) with credentialSubject.name; echoed forward for signing.',\n },\n domainPreviewData: {\n type: 'object',\n description: 'Oracle-enriched human-facing preview of the domain card (object or JSON string).',\n },\n },\n },\n\n outputSchema: [\n {\n path: 'domainCardData',\n displayName: 'Domain Card Data',\n type: 'object',\n description: 'Approved domain card envelope { credentialSubject, validFrom, validUntil } ready to sign',\n },\n { path: 'domainPreviewData', displayName: 'Preview Data', type: 'object', description: 'Oracle-enriched human-facing preview of the domain card' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'pending | loading | ready | approved | error' },\n { path: 'approvedAt', displayName: 'Approved At', type: 'number', description: 'Timestamp when the user approved the preview' },\n ],\n\n events: [\n {\n name: 'approved',\n displayName: 'Preview Approved',\n description: 'Fires when the user approves the oracle-enriched domain card preview.',\n payloadSchema: [\n { path: 'domainCardData', displayName: 'Domain Card Data', type: 'object', description: 'Approved domain card envelope ready for signing' },\n { path: 'approvedAt', displayName: 'Approved At', type: 'number', description: 'Timestamp of approval' },\n ],\n pendingDisplayFields: ['approvedAt'],\n },\n ],\n\n // Mirrors run(): the card envelope (object or JSON string) must carry\n // credentialSubject.name before a preview can render.\n getMissingInputs: (inputs) => {\n const card = parseMaybeJsonObject(inputs.domainCardData);\n if (!card) return ['domainCardData'];\n const subject = card.credentialSubject as Record<string, unknown> | undefined;\n return subject && String(subject.name || '').trim() ? [] : ['domainCardData.credentialSubject.name'];\n },\n\n run: async (inputs) => {\n let domainCardData: any = inputs.domainCardData;\n if (typeof domainCardData === 'string') {\n try {\n domainCardData = JSON.parse(domainCardData);\n } catch {\n throw new Error('domainCardData must be valid JSON');\n }\n }\n if (!domainCardData || typeof domainCardData !== 'object') {\n throw new Error('domainCardData is required to preview a domain card');\n }\n if (!domainCardData.credentialSubject?.name) {\n throw new Error('domainCardData.credentialSubject.name is required');\n }\n\n let domainPreviewData: any = inputs.domainPreviewData;\n if (typeof domainPreviewData === 'string') {\n try {\n domainPreviewData = JSON.parse(domainPreviewData);\n } catch {\n domainPreviewData = undefined;\n }\n }\n\n const now = Date.now();\n\n return {\n output: {\n domainCardData,\n domainPreviewData,\n status: 'approved',\n approvedAt: now,\n },\n events: [{ name: 'approved', payload: { domainCardData, approvedAt: now } }],\n };\n },\n});\n","import { sha256Digest } from '../digest';\nimport { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.invoke',\n can: 'oracle/invoke',\n sideEffect: true,\n proof: { fields: ['resultDigest'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['prompt'],\n properties: {\n prompt: { type: 'string', description: 'The prompt text sent to the Agent.' },\n },\n },\n\n sensitiveInputPaths: ['prompt'],\n sensitiveOutputPaths: ['result'],\n outputSchema: [\n { path: 'prompt', displayName: 'Prompt', type: 'string', description: 'Legacy Flow-timeline echo; redacted from Topic receipts.' },\n { path: 'sessionId', displayName: 'Session ID', type: 'string', description: 'Private Oracle session identifier.' },\n { path: 'result', displayName: 'Result', type: 'object', description: 'Full result retained in the Flow timeline.' },\n { path: 'resultDigest', displayName: 'Result Digest', type: 'string', description: 'Content digest safe for a Topic receipt.' },\n { path: 'evidenceDigest', displayName: 'Evidence Digest', type: 'string', description: 'Digest of evidence references returned by the Oracle.' },\n ],\n\n run: async (inputs, ctx) => {\n const prompt = String(inputs.prompt || '').trim();\n if (!prompt) throw new Error('prompt is required');\n\n if (!ctx.handlers?.askCompanion) {\n throw new Error('askCompanion handler is not available');\n }\n\n const raw = await ctx.handlers.askCompanion(prompt);\n const envelope: Record<string, unknown> = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : { result: raw };\n const result = envelope.result ?? envelope.response ?? envelope.message ?? raw ?? null;\n const evidence = Array.isArray(envelope.evidenceReferences) ? envelope.evidenceReferences : Array.isArray(envelope.evidence) ? envelope.evidence : [];\n\n return {\n output: {\n prompt,\n sessionId: String(envelope.sessionId ?? envelope.runId ?? ''),\n result,\n resultDigest: sha256Digest(result),\n evidenceDigest: sha256Digest(evidence),\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/credential.store',\n can: 'credential/store',\n sideEffect: true,\n proof: { fields: ['storedAt'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n inputSchema: {\n type: 'object',\n required: ['credentialKey', 'credential'],\n properties: {\n credentialKey: { type: 'string', description: 'Key under which to store the credential (e.g. kycamllevel1).' },\n credential: { type: 'object', description: 'The credential to store as a JSON object (also accepts a JSON string).' },\n roomId: { type: 'string', description: 'Matrix room ID to store the credential in; defaults to empty.' },\n },\n },\n\n outputSchema: [\n { path: 'credentialKey', displayName: 'Credential Key', type: 'string', description: 'Key under which credential was stored (e.g. kycamllevel1)' },\n { path: 'cid', displayName: 'Content ID', type: 'string', description: 'IPFS-compatible CID of the credential (used for deduplication)' },\n { path: 'storedAt', displayName: 'Stored At', type: 'string', description: 'ISO timestamp of when the credential was stored' },\n { path: 'duplicate', displayName: 'Duplicate', type: 'boolean', description: 'Whether this credential was already stored (matched by CID)' },\n ],\n\n run: async (inputs, ctx) => {\n const { credential, credentialKey, roomId } = inputs;\n\n if (!credentialKey) throw new Error('credentialKey is required');\n if (!credential) throw new Error('credential is required');\n\n // Normalize credential from any AI-provided format to a plain object.\n // AI may provide: object, JSON string, or double/triple-stringified JSON.\n let parsedCredential: any = credential;\n\n if (typeof parsedCredential === 'string') {\n // Unwrap up to 3 layers of stringification\n for (let i = 0; i < 3 && typeof parsedCredential === 'string'; i++) {\n try {\n parsedCredential = JSON.parse(parsedCredential);\n } catch {\n throw new Error('credential must be a valid JSON object or JSON string');\n }\n }\n }\n\n if (typeof parsedCredential !== 'object' || parsedCredential === null || Array.isArray(parsedCredential)) {\n throw new Error('credential must be a JSON object');\n }\n\n if (!ctx.services.matrix?.storeCredential) {\n throw new Error('Matrix credential storage service not configured');\n }\n\n // Compute IPFS-compatible CID (lazy-loaded)\n const { computeJsonCID } = await import('../../../lib/cid');\n const cid = await computeJsonCID(parsedCredential);\n\n const result = await ctx.services.matrix.storeCredential({\n roomId: roomId || '',\n credentialKey: String(credentialKey),\n credential: parsedCredential,\n cid,\n });\n\n return {\n output: {\n credentialKey: String(credentialKey),\n cid,\n storedAt: result.storedAt,\n duplicate: result.duplicate,\n },\n };\n },\n});\n","import { doneWhenCompleted, registerAction } from '../registry';\nimport { digestDesignPodValue } from '../../designPod';\n\n/**\n * These actions deliberately do NOT set `requiresSignedInvocation`.\n *\n * They ship inside the operational Flows that a minted protocol hands to every\n * instance stamped from it. That flag bypasses the `tempUcanEnforcementDisabled`\n * kill switch, so with it set every block in a stamped instance refused to run —\n * and only the original designer could unblock them, because a cloned Flow keeps\n * the designer's DID as its owner and a chain must root there.\n *\n * Access already has two layers people can reason about: the chain says who\n * controls the entity, Matrix says who is in the room. A third one nobody can\n * discover on their own bought nothing here. Their `proof` declarations stay —\n * a block still cannot report success without evidence; that is correctness,\n * not permission.\n *\n * Restore the flag per action once the authority model for cloned Flows is\n * settled (who owns a clone, and who issues its root).\n */\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${name} is required`);\n return value.trim();\n}\n\nfunction record(value: unknown, name: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${name} must be an object`);\n return value as Record<string, unknown>;\n}\n\nfunction strings(value: unknown, name: string): string[] {\n if (!Array.isArray(value) || value.length === 0 || value.some((item) => typeof item !== 'string' || item.trim().length === 0)) {\n throw new Error(`${name} must be a non-empty string array`);\n }\n return value.map((item) => String(item).trim());\n}\n\nfunction decimalAtLeast(left: string, right: string): boolean {\n const parse = (value: string) => {\n if (!/^(?:0|[1-9]\\d*)(?:\\.\\d+)?$/.test(value)) throw new Error('Coin amount must be a non-negative decimal string');\n const [whole, fraction = ''] = value.split('.');\n return { whole, fraction };\n };\n const leftValue = parse(left);\n const rightValue = parse(right);\n const scale = Math.max(leftValue.fraction.length, rightValue.fraction.length);\n const units = (value: { whole: string; fraction: string }) => BigInt(`${value.whole}${value.fraction.padEnd(scale, '0')}`);\n return units(leftValue) >= units(rightValue);\n}\n\nasync function operationalIntegrationDigest(binding: {\n service: 'funding' | 'credential' | 'yoma' | 'yoid' | 'outcome';\n capability: 'funding/verify' | 'credential/issue' | 'yoma/opportunity' | 'yoid/link' | 'outcome/certificate';\n resource: string;\n operation: string;\n payload: Record<string, unknown>;\n}): Promise<string> {\n const digest = await digestDesignPodValue({\n service: binding.service,\n capability: binding.capability,\n resource: binding.resource,\n operation: binding.operation,\n payload: binding.payload,\n });\n return digest.replace('sha256:', '');\n}\n\nregisterAction({\n type: 'qi/funding.verify',\n can: 'funding/verify',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n proof: { fields: ['requestDigest', 'receiptRef', 'balanceDigest'] },\n done: doneWhenCompleted,\n inputSchema: {\n type: 'object',\n required: ['deploymentNetwork', 'fundingAuthorityDid', 'sourceAccountRef', 'sourceAccountType', 'payout', 'minimumAvailable', 'claimantAddressResolution'],\n properties: {\n deploymentNetwork: { type: 'string', description: 'Target testnet or mainnet deployment.' },\n fundingAuthorityDid: { type: 'string', description: 'Human or organisation accountable for the payout source.' },\n sourceAccountRef: { type: 'string', description: 'Opaque, operator-configured payout source account reference.' },\n sourceAccountType: { type: 'string', description: 'Explicit wallet or treasury account type; never inferred from the Deed.' },\n payout: { type: 'object', description: 'Per-approved-claim denomination and amount.' },\n minimumAvailable: { type: 'object', description: 'Required available balance before claim evaluation opens.' },\n claimantAddressResolution: { type: 'object', description: 'Governed claimant wallet resolver and proof rule.' },\n },\n },\n outputSchema: [\n { path: 'sourceAccountRef', displayName: 'Source account', type: 'string', description: 'Verified payout source.' },\n { path: 'deploymentNetwork', displayName: 'Network', type: 'string', description: 'Observed target network.' },\n { path: 'availableBalance', displayName: 'Available balance', type: 'object', description: 'Observed source balance.' },\n { path: 'supportedDenominations', displayName: 'Supported coins', type: 'array', description: 'Coins supported by this deployment.' },\n { path: 'claimantAddressResolutionVerified', displayName: 'Address resolver verified', type: 'boolean', description: 'The claimant-address resolver returned proof.' },\n { path: 'requestDigest', displayName: 'Request digest', type: 'string', description: 'Source-verified canonical funding-request binding.' },\n { path: 'balanceDigest', displayName: 'Balance digest', type: 'string', description: 'Canonical source-balance observation digest.' },\n { path: 'receiptRef', displayName: 'Funding receipt', type: 'string', description: 'Externally issued source verification receipt.' },\n { path: 'observedAt', displayName: 'Observed at', type: 'string', description: 'Time the funding state was read back.' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.fundingVerification;\n if (!service) throw new Error('Funding verification service not configured');\n const deploymentNetwork = requiredString(inputs.deploymentNetwork, 'deploymentNetwork');\n if (!['testnet', 'mainnet'].includes(deploymentNetwork)) throw new Error('deploymentNetwork must be testnet or mainnet');\n const sourceAccountType = requiredString(inputs.sourceAccountType, 'sourceAccountType');\n if (!['provider_wallet', 'outcome_buyer_treasury', 'deed_entity_account', 'external_treasury'].includes(sourceAccountType)) {\n throw new Error('sourceAccountType is invalid');\n }\n const payout = record(inputs.payout, 'payout');\n const minimumAvailable = record(inputs.minimumAvailable, 'minimumAvailable');\n const claimantAddressResolution = record(inputs.claimantAddressResolution, 'claimantAddressResolution');\n const method = requiredString(claimantAddressResolution.method, 'claimantAddressResolution.method');\n if (!['claim_subject_address', 'verified_wallet_link', 'provider_registry'].includes(method)) {\n throw new Error('claimantAddressResolution.method is invalid');\n }\n if (claimantAddressResolution.proofRequired !== true) throw new Error('Claimant-address resolution proof is required');\n const request = {\n deploymentNetwork: deploymentNetwork as 'testnet' | 'mainnet',\n fundingAuthorityDid: requiredString(inputs.fundingAuthorityDid, 'fundingAuthorityDid'),\n sourceAccountRef: requiredString(inputs.sourceAccountRef, 'sourceAccountRef'),\n sourceAccountType: sourceAccountType as 'provider_wallet' | 'outcome_buyer_treasury' | 'deed_entity_account' | 'external_treasury',\n payout: {\n denom: requiredString(payout.denom, 'payout.denom'),\n amount: requiredString(payout.amount, 'payout.amount'),\n },\n minimumAvailable: {\n denom: requiredString(minimumAvailable.denom, 'minimumAvailable.denom'),\n amount: requiredString(minimumAvailable.amount, 'minimumAvailable.amount'),\n },\n claimantAddressResolution: {\n method: method as 'claim_subject_address' | 'verified_wallet_link' | 'provider_registry',\n resolverServiceRef: requiredString(claimantAddressResolution.resolverServiceRef, 'claimantAddressResolution.resolverServiceRef'),\n proofRequired: true as const,\n },\n };\n if (request.payout.denom !== request.minimumAvailable.denom) throw new Error('Payout and minimum balance must use one denomination');\n const result = await service.verify(request);\n const requestDigest = await operationalIntegrationDigest({\n service: 'funding',\n capability: 'funding/verify',\n resource: `ixo:funding:${request.deploymentNetwork}:${request.sourceAccountRef}`,\n operation: 'verify-source-balance-and-claimant-resolver',\n payload: request,\n });\n if (requiredString(result.requestDigest, 'requestDigest') !== requestDigest) {\n throw new Error('Funding verification is not bound to the canonical request');\n }\n if (result.sourceAccountRef !== request.sourceAccountRef || result.deploymentNetwork !== request.deploymentNetwork) {\n throw new Error('Funding service returned a different source account or network');\n }\n if (\n result.availableBalance.denom !== request.payout.denom ||\n !result.supportedDenominations.includes(request.payout.denom) ||\n !decimalAtLeast(result.availableBalance.amount, request.minimumAvailable.amount)\n ) {\n throw new Error('Funding source cannot cover the governed minimum in the approved payout coin');\n }\n if (result.claimantAddressResolutionVerified !== true) throw new Error('Claimant-address resolver was not verified');\n requiredString(result.balanceDigest, 'balanceDigest');\n if (!/^[a-f0-9]{64}$/.test(result.balanceDigest)) throw new Error('balanceDigest must be a lowercase SHA-256 digest');\n requiredString(result.receiptRef, 'receiptRef');\n requiredString(result.observedAt, 'observedAt');\n return { output: result };\n },\n});\n\nregisterAction({\n type: 'qi/credential.issue',\n can: 'credential/issue',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n proof: { fields: ['requestDigest', 'issuanceReceiptRef', 'deliveryReceiptRef', 'verificationReceiptRef'] },\n done: doneWhenCompleted,\n inputSchema: {\n type: 'object',\n required: ['credentialType', 'issuerDid', 'subjectDid', 'yoId', 'claims', 'evidenceRefs', 'deliveryChannel'],\n properties: {\n credentialType: { type: 'string', description: 'Governed verifiable-credential type.' },\n issuerDid: { type: 'string', description: 'Authorised credential issuer DID.' },\n subjectDid: { type: 'string', description: 'Youth holder IXO DID.' },\n yoId: { type: 'string', description: 'Verified YoID bound to the youth holder.' },\n claims: { type: 'object', description: 'Credential claims derived from evaluated Deed work.' },\n evidenceRefs: { type: 'array', description: 'Immutable evaluated-claim and evidence references.' },\n deliveryChannel: { type: 'string', description: 'yoid_wallet, ixo_portal, or both.' },\n },\n },\n outputSchema: [\n { path: 'credentialId', displayName: 'Credential ID', type: 'string', description: 'Issued credential identifier.' },\n { path: 'credential', displayName: 'Credential', type: 'object', description: 'Issued verifiable credential for governed storage.' },\n { path: 'requestDigest', displayName: 'Request digest', type: 'string', description: 'Source-verified canonical issuance-request binding.' },\n { path: 'issuanceReceiptRef', displayName: 'Issuance receipt', type: 'string', description: 'External issuance proof.' },\n { path: 'deliveryReceiptRef', displayName: 'Delivery receipt', type: 'string', description: 'YoID or Portal delivery proof.' },\n { path: 'verificationReceiptRef', displayName: 'Verification receipt', type: 'string', description: 'Post-issuance verification proof.' },\n { path: 'verificationStatus', displayName: 'Verification status', type: 'string', description: 'Must be verified.' },\n ],\n events: [\n {\n name: 'credential.issued',\n displayName: 'Credential issued',\n description: 'Fires after issuance, delivery, and verification all return receipts.',\n payloadSchema: [{ path: 'credentialId', displayName: 'Credential ID', type: 'string', description: 'Issued credential identifier.' }],\n },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.credentialIssuance;\n if (!service) throw new Error('Credential issuance service not configured');\n const deliveryChannel = requiredString(inputs.deliveryChannel, 'deliveryChannel');\n if (!['yoid_wallet', 'ixo_portal', 'both'].includes(deliveryChannel)) {\n throw new Error('deliveryChannel must be yoid_wallet, ixo_portal, or both');\n }\n const request = {\n credentialType: requiredString(inputs.credentialType, 'credentialType'),\n issuerDid: requiredString(inputs.issuerDid, 'issuerDid'),\n subjectDid: requiredString(inputs.subjectDid, 'subjectDid'),\n yoId: requiredString(inputs.yoId, 'yoId'),\n claims: record(inputs.claims, 'claims'),\n evidenceRefs: strings(inputs.evidenceRefs, 'evidenceRefs'),\n deliveryChannel: deliveryChannel as 'yoid_wallet' | 'ixo_portal' | 'both',\n };\n const result = await service.issueAndDeliver(request);\n for (const field of ['credentialId', 'issuanceReceiptRef', 'deliveryReceiptRef', 'verificationReceiptRef'] as const) {\n requiredString(result[field], field);\n }\n const requestDigest = await operationalIntegrationDigest({\n service: 'credential',\n capability: 'credential/issue',\n resource: `ixo:credential:${request.issuerDid}:${request.subjectDid}`,\n operation: 'issue-deliver-verify',\n payload: request,\n });\n if (requiredString(result.requestDigest, 'requestDigest') !== requestDigest) throw new Error('Issued credential is not bound to the canonical issuance request');\n if (result.verificationStatus !== 'verified') throw new Error('Issued credential was not independently verified');\n const credential = record(result.credential, 'credential');\n const issuer =\n typeof credential.issuer === 'string'\n ? requiredString(credential.issuer, 'credential.issuer')\n : requiredString(record(credential.issuer, 'credential.issuer').id, 'credential.issuer.id');\n if (issuer !== request.issuerDid) throw new Error('Issued credential issuer does not match the requested issuer');\n const credentialTypes = typeof credential.type === 'string' ? [requiredString(credential.type, 'credential.type')] : strings(credential.type, 'credential.type');\n if (!credentialTypes.includes(request.credentialType)) throw new Error('Issued credential type does not match the requested credential type');\n const rawSubjects = Array.isArray(credential.credentialSubject) ? credential.credentialSubject : [credential.credentialSubject];\n if (rawSubjects.length !== 1 || requiredString(record(rawSubjects[0], 'credential.credentialSubject').id, 'credential.credentialSubject.id') !== request.subjectDid) {\n throw new Error('Issued credential subject does not match the requested youth');\n }\n if (credential.id !== undefined && requiredString(credential.id, 'credential.id') !== result.credentialId) {\n throw new Error('Issued credential ID does not match the issuance result');\n }\n return {\n output: result,\n events: [{ name: 'credential.issued', payload: { credentialId: result.credentialId } }],\n };\n },\n});\n\nregisterAction({\n type: 'qi/yoma.opportunity',\n can: 'yoma/opportunity',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n proof: { fields: ['requestDigest', 'receiptRef'] },\n done: doneWhenCompleted,\n inputSchema: {\n type: 'object',\n required: ['operation', 'providerOrganisationId', 'deedDid', 'opportunity'],\n properties: {\n operation: { type: 'string', description: 'publish, update, pause, or withdraw.' },\n providerOrganisationId: { type: 'string', description: 'Yoma Opportunity Provider organisation.' },\n opportunityId: { type: 'string', description: 'Existing Yoma opportunity ID for non-publish operations.' },\n deedDid: { type: 'string', description: 'Instantiated IXO Deed DID.' },\n opportunity: { type: 'object', description: 'Yoma opportunity payload derived from the approved Blueprint.' },\n },\n },\n outputSchema: [\n { path: 'opportunityId', displayName: 'Opportunity ID', type: 'string', description: 'Yoma opportunity identifier.' },\n { path: 'status', displayName: 'Listing status', type: 'string', description: 'Observed Yoma listing status.' },\n { path: 'requestDigest', displayName: 'Request digest', type: 'string', description: 'Source-verified canonical Yoma-operation binding.' },\n { path: 'receiptRef', displayName: 'Yoma receipt', type: 'string', description: 'Signed or digest-bound Yoma operation receipt.' },\n { path: 'observedAt', displayName: 'Observed at', type: 'string', description: 'Time the listing state was read back.' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.yomaOpportunity;\n if (!service) throw new Error('Yoma opportunity service not configured');\n const operation = requiredString(inputs.operation, 'operation');\n if (!['publish', 'update', 'pause', 'withdraw'].includes(operation)) throw new Error('Unsupported Yoma opportunity operation');\n const requestedOpportunityId = operation !== 'publish' ? requiredString(inputs.opportunityId, 'opportunityId') : undefined;\n const request = {\n operation: operation as 'publish' | 'update' | 'pause' | 'withdraw',\n providerOrganisationId: requiredString(inputs.providerOrganisationId, 'providerOrganisationId'),\n opportunityId: requestedOpportunityId,\n deedDid: requiredString(inputs.deedDid, 'deedDid'),\n opportunity: record(inputs.opportunity, 'opportunity'),\n };\n const result = await service.execute(request);\n const observedOpportunityId = requiredString(result.opportunityId, 'opportunityId');\n requiredString(result.receiptRef, 'receiptRef');\n requiredString(result.observedAt, 'observedAt');\n const requestDigest = await operationalIntegrationDigest({\n service: 'yoma',\n capability: 'yoma/opportunity',\n resource: `ixo:yoma:opportunity:${request.providerOrganisationId}:${request.opportunityId ?? 'new'}`,\n operation: request.operation,\n payload: request,\n });\n if (requiredString(result.requestDigest, 'requestDigest') !== requestDigest) throw new Error('Yoma response is not bound to the canonical opportunity request');\n if (requestedOpportunityId && observedOpportunityId !== requestedOpportunityId) throw new Error('Yoma response opportunityId does not match the requested opportunity');\n const expectedStatus = operation === 'pause' ? 'paused' : operation === 'withdraw' ? 'withdrawn' : 'published';\n if (result.status !== expectedStatus) throw new Error(`Yoma response status does not prove the requested ${operation} operation`);\n return { output: result };\n },\n});\n\nregisterAction({\n type: 'qi/yoid.link',\n can: 'yoid/link',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n proof: { fields: ['requestDigest', 'receiptRef'] },\n done: doneWhenCompleted,\n inputSchema: {\n type: 'object',\n required: ['operation', 'participantDid', 'yoId', 'opportunityId', 'consentReceiptRef'],\n properties: {\n operation: { type: 'string', description: 'link, verify, or unlink.' },\n participantDid: { type: 'string', description: 'Youth IXO DID.' },\n yoId: { type: 'string', description: 'Youth YoID.' },\n opportunityId: { type: 'string', description: 'Yoma opportunity receiving the participant.' },\n consentReceiptRef: { type: 'string', description: 'Verifiable informed-consent receipt.' },\n },\n },\n outputSchema: [\n { path: 'bindingId', displayName: 'Binding ID', type: 'string', description: 'Yoma/YoID binding identifier.' },\n { path: 'status', displayName: 'Binding status', type: 'string', description: 'Observed linked, verified, or unlinked state.' },\n { path: 'requestDigest', displayName: 'Request digest', type: 'string', description: 'Source-verified canonical participant-link request binding.' },\n { path: 'receiptRef', displayName: 'YoID receipt', type: 'string', description: 'Signed or digest-bound identity operation receipt.' },\n { path: 'observedAt', displayName: 'Observed at', type: 'string', description: 'Time the identity state was read back.' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.yoId;\n if (!service) throw new Error('YoID integration service not configured');\n const operation = requiredString(inputs.operation, 'operation');\n if (!['link', 'verify', 'unlink'].includes(operation)) throw new Error('Unsupported YoID operation');\n const request = {\n operation: operation as 'link' | 'verify' | 'unlink',\n participantDid: requiredString(inputs.participantDid, 'participantDid'),\n yoId: requiredString(inputs.yoId, 'yoId'),\n opportunityId: requiredString(inputs.opportunityId, 'opportunityId'),\n consentReceiptRef: requiredString(inputs.consentReceiptRef, 'consentReceiptRef'),\n };\n const result = await service.execute(request);\n requiredString(result.bindingId, 'bindingId');\n requiredString(result.receiptRef, 'receiptRef');\n requiredString(result.observedAt, 'observedAt');\n const requestDigest = await operationalIntegrationDigest({\n service: 'yoid',\n capability: 'yoid/link',\n resource: `ixo:yoid:${request.participantDid}`,\n operation: request.operation,\n payload: request,\n });\n if (requiredString(result.requestDigest, 'requestDigest') !== requestDigest) throw new Error('YoID response is not bound to the canonical participant-link request');\n const expectedStatus = operation === 'link' ? 'linked' : operation === 'verify' ? 'verified' : 'unlinked';\n if (result.status !== expectedStatus) throw new Error(`YoID response status does not prove the requested ${operation} operation`);\n return { output: result };\n },\n});\n\nregisterAction({\n type: 'qi/outcome.certificate',\n can: 'outcome/certificate',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n proof: { fields: ['requestDigest', 'issuanceReceiptRef', 'verificationReceiptRef'] },\n done: doneWhenCompleted,\n inputSchema: {\n type: 'object',\n required: ['collectionId', 'methodologyRef', 'issuerDid', 'claimIds', 'evidenceDigest', 'period'],\n properties: {\n collectionId: { type: 'string', description: 'Claim collection being aggregated.' },\n methodologyRef: { type: 'string', description: 'Approved theory-of-change methodology.' },\n issuerDid: { type: 'string', description: 'Authorised outcome credential issuer.' },\n claimIds: { type: 'array', description: 'Verified claim IDs included in the outcome.' },\n evidenceDigest: { type: 'string', description: 'Canonical digest of the deidentified aggregate evidence.' },\n period: { type: 'object', description: 'Outcome measurement start and end timestamps.' },\n tokenisation: { type: 'object', description: 'Optional governed tokenisation request.' },\n outcomeBuyer: { type: 'object', description: 'Optional configured buyer commitment and settlement trigger.' },\n },\n },\n outputSchema: [\n { path: 'certificateId', displayName: 'Certificate ID', type: 'string', description: 'Issued outcome certificate identifier.' },\n { path: 'credential', displayName: 'Outcome credential', type: 'object', description: 'Issued verifiable outcome credential.' },\n { path: 'requestDigest', displayName: 'Request digest', type: 'string', description: 'Source-verified canonical outcome-request binding.' },\n { path: 'aggregateDigest', displayName: 'Aggregate digest', type: 'string', description: 'Verified evidence aggregate digest.' },\n { path: 'issuanceReceiptRef', displayName: 'Issuance receipt', type: 'string', description: 'Outcome issuance proof.' },\n { path: 'verificationReceiptRef', displayName: 'Verification receipt', type: 'string', description: 'Independent verification proof.' },\n { path: 'verificationStatus', displayName: 'Verification status', type: 'string', description: 'Must be verified.' },\n { path: 'tokenisationReceiptRef', displayName: 'Tokenisation receipt', type: 'string', description: 'Optional tokenisation proof.' },\n { path: 'buyerSettlementReceiptRef', displayName: 'Buyer settlement receipt', type: 'string', description: 'Optional configured outcome-buyer settlement proof.' },\n { path: 'settlementStatus', displayName: 'Settlement status', type: 'string', description: 'Must be settled when a buyer is configured.' },\n ],\n run: async (inputs, ctx) => {\n const service = ctx.services.outcomeCertificate;\n if (!service) throw new Error('Outcome certificate service not configured');\n const period = record(inputs.period, 'period');\n const start = requiredString(period.start, 'period.start');\n const end = requiredString(period.end, 'period.end');\n const startAt = Date.parse(start);\n const endAt = Date.parse(end);\n if (!Number.isFinite(startAt) || !Number.isFinite(endAt)) throw new Error('Outcome period start and end must be valid timestamps');\n if (endAt <= startAt) throw new Error('Outcome period end must follow start');\n const evidenceDigest = requiredString(inputs.evidenceDigest, 'evidenceDigest');\n if (!/^[a-f0-9]{64}$/.test(evidenceDigest)) throw new Error('evidenceDigest must be a lowercase SHA-256 digest');\n const tokenisation = inputs.tokenisation === undefined ? undefined : record(inputs.tokenisation, 'tokenisation');\n const outcomeBuyer = inputs.outcomeBuyer === undefined ? undefined : record(inputs.outcomeBuyer, 'outcomeBuyer');\n if (tokenisation?.enabled === true) {\n const network = requiredString(tokenisation.network, 'tokenisation.network');\n if (!['testnet', 'mainnet'].includes(network)) throw new Error('tokenisation.network must be testnet or mainnet');\n for (const field of ['assetClass', 'transferPolicyRef', 'marketServiceRef']) {\n requiredString(tokenisation[field], `tokenisation.${field}`);\n }\n }\n if (outcomeBuyer) {\n const purchaseTrigger = requiredString(outcomeBuyer.purchaseTrigger, 'outcomeBuyer.purchaseTrigger');\n if (!['certificate_issued', 'certificate_verified', 'manual_acceptance'].includes(purchaseTrigger)) {\n throw new Error('outcomeBuyer.purchaseTrigger is invalid');\n }\n }\n const request = {\n collectionId: requiredString(inputs.collectionId, 'collectionId'),\n methodologyRef: requiredString(inputs.methodologyRef, 'methodologyRef'),\n issuerDid: requiredString(inputs.issuerDid, 'issuerDid'),\n claimIds: strings(inputs.claimIds, 'claimIds'),\n evidenceDigest,\n period: { start, end },\n outcomeBuyer: outcomeBuyer\n ? {\n buyerDid: requiredString(outcomeBuyer.buyerDid, 'outcomeBuyer.buyerDid'),\n commitmentRef: requiredString(outcomeBuyer.commitmentRef, 'outcomeBuyer.commitmentRef'),\n purchaseTrigger: requiredString(outcomeBuyer.purchaseTrigger, 'outcomeBuyer.purchaseTrigger') as 'certificate_issued' | 'certificate_verified' | 'manual_acceptance',\n }\n : undefined,\n tokenisation: tokenisation\n ? {\n enabled: tokenisation.enabled === true,\n network: typeof tokenisation.network === 'string' ? (tokenisation.network as 'testnet' | 'mainnet') : undefined,\n assetClass: typeof tokenisation.assetClass === 'string' ? tokenisation.assetClass : undefined,\n transferPolicyRef: typeof tokenisation.transferPolicyRef === 'string' ? tokenisation.transferPolicyRef : undefined,\n marketServiceRef: typeof tokenisation.marketServiceRef === 'string' ? tokenisation.marketServiceRef : undefined,\n }\n : undefined,\n };\n const result = await service.issueAndVerify(request);\n requiredString(result.certificateId, 'certificateId');\n requiredString(result.aggregateDigest, 'aggregateDigest');\n requiredString(result.issuanceReceiptRef, 'issuanceReceiptRef');\n requiredString(result.verificationReceiptRef, 'verificationReceiptRef');\n const requestDigest = await operationalIntegrationDigest({\n service: 'outcome',\n capability: 'outcome/certificate',\n resource: `ixo:outcome:${request.collectionId}:${request.period.start}:${request.period.end}`,\n operation: request.outcomeBuyer ? 'aggregate-issue-verify-and-settle' : 'aggregate-issue-verify',\n payload: request,\n });\n if (requiredString(result.requestDigest, 'requestDigest') !== requestDigest) throw new Error('Outcome certificate is not bound to the canonical aggregation request');\n if (result.verificationStatus !== 'verified') throw new Error('Outcome certificate was not independently verified');\n if (tokenisation?.enabled === true) requiredString(result.tokenisationReceiptRef, 'tokenisationReceiptRef');\n if (outcomeBuyer) {\n requiredString(result.buyerSettlementReceiptRef, 'buyerSettlementReceiptRef');\n if (result.settlementStatus !== 'settled') throw new Error('Configured outcome buyer has not settled');\n }\n if (result.aggregateDigest !== evidenceDigest) throw new Error('Outcome service returned a different aggregate digest');\n const credential = record(result.credential, 'credential');\n const issuer =\n typeof credential.issuer === 'string'\n ? requiredString(credential.issuer, 'credential.issuer')\n : requiredString(record(credential.issuer, 'credential.issuer').id, 'credential.issuer.id');\n if (issuer !== request.issuerDid) throw new Error('Outcome credential issuer does not match the requested issuer');\n const credentialTypes = typeof credential.type === 'string' ? [requiredString(credential.type, 'credential.type')] : strings(credential.type, 'credential.type');\n if (!credentialTypes.includes('OutcomeCertificate')) throw new Error('Issued credential is not an OutcomeCertificate');\n if (requiredString(credential.id, 'credential.id') !== result.certificateId) throw new Error('Outcome credential ID does not match the issued certificate ID');\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\nimport { sendDirectMessage } from '../../matrixDm';\n\nregisterAction({\n type: 'qi/matrix.dm',\n can: 'matrix/dm',\n sideEffect: true,\n proof: { fields: ['roomId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n\n inputSchema: {\n type: 'object',\n required: ['targetDid', 'message'],\n properties: {\n targetDid: { type: 'string', description: 'The recipient DID to direct-message.' },\n message: { type: 'string', description: 'The message text to send.' },\n },\n },\n\n outputSchema: [\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'The Matrix room ID used for the DM' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'Timestamp when the message was sent' },\n ],\n\n run: async (inputs, ctx) => {\n const matrixClient = ctx.editor?.getMatrixClient?.();\n if (!matrixClient) {\n throw new Error('Matrix client not available');\n }\n\n const targetDid = String(inputs.targetDid || '').trim();\n const message = String(inputs.message || '').trim();\n\n if (!targetDid) throw new Error('Recipient DID is required');\n if (!message) throw new Error('Message is required');\n\n const result = await sendDirectMessage(matrixClient, targetDid, message);\n\n return {\n output: {\n roomId: result.roomId,\n sentAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/wallet.generate',\n can: 'wallet/generate',\n sideEffect: false,\n proof: { fields: ['address'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n },\n outputSchema: [\n { path: 'address', displayName: 'Wallet Address', type: 'string', description: 'The generated IXO wallet address' },\n { path: 'did', displayName: 'DID', type: 'string', description: 'The DID derived from the wallet address' },\n { path: 'pubKey', displayName: 'Public Key', type: 'string', description: 'The secp256k1 public key (hex)' },\n { path: 'mnemonic', displayName: 'Mnemonic', type: 'string', description: 'The BIP39 mnemonic seed phrase' },\n ],\n run: async (_inputs, ctx) => {\n if (!ctx.services.oracle?.generateWallet) {\n throw new Error('oracle.generateWallet handler not available');\n }\n const result = await ctx.services.oracle.generateWallet();\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\n/** What the chain used before this block could send anything else. */\nconst DEFAULT_DENOM = 'uixo';\n\nregisterAction({\n type: 'qi/wallet.fund',\n can: 'wallet/fund',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n\n inputSchema: {\n type: 'object',\n required: ['address'],\n properties: {\n address: { type: 'string', description: 'The IXO wallet address to fund.' },\n amount: { type: 'number', description: 'Funding amount in the denom’s base units (defaults to 250000).' },\n denom: { type: 'string', description: 'Base denom to send, e.g. uixo. Defaults to uixo.' },\n fromAddress: {\n type: 'string',\n description: 'Wallet the tokens leave. Defaults to the signed-in user’s wallet; any other address must be one they can act on.',\n },\n },\n },\n\n outputSchema: [\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The funding transaction hash' },\n { path: 'denom', displayName: 'Denom', type: 'string', description: 'The base denom that was sent' },\n { path: 'amount', displayName: 'Amount', type: 'string', description: 'The amount sent, in the denom’s base units' },\n { path: 'fromAddress', displayName: 'From Address', type: 'string', description: 'The wallet the tokens left (blank when the signer’s own wallet)' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.fundWallet) {\n throw new Error('oracle.fundWallet handler not available');\n }\n if (!inputs.address) throw new Error('address is required');\n\n const denom = String(inputs.denom || '').trim() || DEFAULT_DENOM;\n // Base units, never display units — the editor has no exponent table, so\n // converting here would silently send the wrong amount for any token that\n // is not 6-decimal.\n const amount = Number(inputs.amount) || 250000;\n if (!Number.isFinite(amount) || amount <= 0) throw new Error('amount must be greater than 0');\n if (!Number.isInteger(amount)) throw new Error(`amount must be a whole number of ${denom} base units`);\n\n const fromAddress = String(inputs.fromAddress || '').trim();\n\n const result = await ctx.services.oracle.fundWallet({\n address: inputs.address,\n amount,\n denom,\n ...(fromAddress ? { fromAddress } : {}),\n });\n // Echo what was actually sent so downstream blocks (and the run record)\n // do not have to re-derive it from the template inputs.\n return { output: { ...result, denom, amount: String(amount), fromAddress } };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/wallet.generateAndFund',\n can: 'wallet/generateAndFund',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: [],\n properties: {\n amount: { type: 'number', description: 'Funding amount in base units for the generated wallet (defaults to 250000).' },\n denom: { type: 'string', description: 'Base denom to send, e.g. uixo. Defaults to uixo.' },\n fromAddress: {\n type: 'string',\n description: 'Wallet the funding leaves. Defaults to the signed-in user’s wallet; any other address must be one they can act on.',\n },\n },\n },\n outputSchema: [\n { path: 'address', displayName: 'Wallet Address', type: 'string', description: 'The generated IXO wallet address' },\n { path: 'did', displayName: 'DID', type: 'string', description: 'The DID derived from the wallet address' },\n { path: 'pubKey', displayName: 'Public Key', type: 'string', description: 'The secp256k1 public key (hex)' },\n { path: 'mnemonic', displayName: 'Mnemonic', type: 'string', description: 'The BIP39 mnemonic seed phrase' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The funding transaction hash' },\n { path: 'denom', displayName: 'Denom', type: 'string', description: 'The base denom that was sent' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.generateWallet) {\n throw new Error('oracle.generateWallet handler not available');\n }\n if (!ctx.services.oracle?.fundWallet) {\n throw new Error('oracle.fundWallet handler not available');\n }\n\n // Step 1: Generate wallet\n const walletResult = await ctx.services.oracle.generateWallet();\n if (!walletResult?.address) {\n throw new Error('generateWallet did not return an address');\n }\n\n // Step 2: Fund wallet. Same token/source contract as `qi/wallet.fund` —\n // omitted denom stays uixo, omitted fromAddress stays the signer's wallet.\n const denom = String(inputs.denom || '').trim() || 'uixo';\n const fromAddress = String(inputs.fromAddress || '').trim();\n const fundResult = await ctx.services.oracle.fundWallet({\n address: walletResult.address,\n amount: inputs.amount || 250000,\n denom,\n ...(fromAddress ? { fromAddress } : {}),\n });\n if (!fundResult?.transactionHash) {\n throw new Error('fundWallet did not return a transactionHash');\n }\n\n return {\n output: {\n address: walletResult.address,\n did: walletResult.did,\n pubKey: walletResult.pubKey,\n mnemonic: walletResult.mnemonic,\n transactionHash: fundResult.transactionHash,\n denom,\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/iid.create',\n can: 'iid/create',\n sideEffect: true,\n proof: { fields: ['transactionHash', 'alreadyExisted'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['mnemonic', 'did', 'address', 'pubKey'],\n properties: {\n mnemonic: { type: 'string', description: 'Wallet mnemonic used to create the IID document.' },\n did: { type: 'string', description: 'The DID for the IID document.' },\n address: { type: 'string', description: 'The blockchain address.' },\n pubKey: { type: 'string', description: 'The public key for the IID document.' },\n },\n },\n outputSchema: [\n { path: 'did', displayName: 'DID', type: 'string', description: 'The IID document DID' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The IID creation transaction hash' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.createIidDocument) {\n throw new Error('oracle.createIidDocument handler not available');\n }\n if (!inputs.mnemonic) throw new Error('mnemonic is required');\n if (!inputs.did) throw new Error('did is required');\n if (!inputs.address) throw new Error('address is required');\n if (!inputs.pubKey) throw new Error('pubKey is required');\n // network and matrixHomeServerUrl are resolved by the consumer-side handler\n // from the platform's DefaultChainNetwork — this app is single-network.\n const result = await ctx.services.oracle.createIidDocument({\n mnemonic: inputs.mnemonic,\n did: inputs.did,\n address: inputs.address,\n pubKey: inputs.pubKey,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/matrix.register',\n can: 'matrix/register',\n sideEffect: true,\n proof: { fields: ['matrixUserId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['mnemonic', 'address', 'did', 'pin', 'oracleName'],\n properties: {\n mnemonic: { type: 'string', description: 'Wallet mnemonic used to register the Matrix account.' },\n address: { type: 'string', description: 'The blockchain address.' },\n did: { type: 'string', description: 'The DID associated with the Matrix account.' },\n pin: { type: 'string', description: 'PIN used to register the Matrix account.' },\n oracleName: { type: 'string', description: 'Oracle name for the Matrix account.' },\n avatarUrl: { type: 'string', description: 'Avatar URL for the Matrix account.' },\n },\n },\n outputSchema: [\n { path: 'matrixUserId', displayName: 'Matrix User ID', type: 'string', description: 'The Matrix user ID' },\n { path: 'matrixAccessToken', displayName: 'Matrix Access Token', type: 'string', description: 'The Matrix access token' },\n { path: 'matrixRoomId', displayName: 'Matrix Room ID', type: 'string', description: 'The Matrix room ID' },\n { path: 'matrixDeviceId', displayName: 'Matrix Device ID', type: 'string', description: 'The Matrix device ID' },\n { path: 'matrixMnemonic', displayName: 'Matrix Mnemonic', type: 'string', description: 'The Matrix account mnemonic' },\n { path: 'matrixPassword', displayName: 'Matrix Password', type: 'string', description: 'The Matrix account password' },\n { path: 'matrixRecoveryPhrase', displayName: 'Recovery Phrase', type: 'string', description: 'The Matrix recovery phrase' },\n { path: 'matrixHomeServerUrl', displayName: 'Matrix Homeserver', type: 'string', description: 'The Matrix homeserver URL' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.registerMatrixAccount) {\n throw new Error('oracle.registerMatrixAccount handler not available');\n }\n if (!inputs.mnemonic) throw new Error('mnemonic is required');\n if (!inputs.address) throw new Error('address is required');\n if (!inputs.did) throw new Error('did is required');\n if (!inputs.pin) throw new Error('pin is required');\n if (!inputs.oracleName) throw new Error('oracleName is required');\n const result = await ctx.services.oracle.registerMatrixAccount({\n mnemonic: inputs.mnemonic,\n address: inputs.address,\n did: inputs.did,\n pin: inputs.pin,\n oracleName: inputs.oracleName,\n avatarUrl: inputs.avatarUrl,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/identity.create',\n can: 'identity/create',\n sideEffect: true,\n // Dual-phase proof: on-chain IID (transactionHash or alreadyExisted) AND matrix registration.\n proof: { validate: (output) => !!(output.transactionHash || output.alreadyExisted) && !!output.matrixUserId },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['mnemonic', 'did', 'address', 'pubKey', 'pin', 'oracleName'],\n properties: {\n mnemonic: { type: 'string', description: 'Wallet mnemonic used to create the IID document and Matrix account.' },\n did: { type: 'string', description: 'The DID for the IID document.' },\n address: { type: 'string', description: 'The blockchain address.' },\n pubKey: { type: 'string', description: 'The public key for the IID document.' },\n pin: { type: 'string', description: 'PIN used to register the Matrix account.' },\n oracleName: { type: 'string', description: 'Oracle name for the Matrix account.' },\n avatarUrl: { type: 'string', description: 'Avatar URL for the Matrix account (mapped from form logoUrl).' },\n formAnswers: { type: 'string', description: 'JSON string of runtime form answers merged into inputs.' },\n },\n },\n outputSchema: [\n { path: 'did', displayName: 'DID', type: 'string', description: 'The IID document DID' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The IID creation transaction hash' },\n { path: 'alreadyExisted', displayName: 'Already Existed', type: 'boolean', description: 'Whether the IID document already existed' },\n { path: 'matrixUserId', displayName: 'Matrix User ID', type: 'string', description: 'The Matrix user ID' },\n { path: 'matrixAccessToken', displayName: 'Matrix Access Token', type: 'string', description: 'The Matrix access token' },\n { path: 'matrixRoomId', displayName: 'Matrix Room ID', type: 'string', description: 'The Matrix room ID' },\n { path: 'matrixDeviceId', displayName: 'Matrix Device ID', type: 'string', description: 'The Matrix device ID' },\n { path: 'matrixMnemonic', displayName: 'Matrix Mnemonic', type: 'string', description: 'The Matrix account mnemonic' },\n { path: 'matrixPassword', displayName: 'Matrix Password', type: 'string', description: 'The Matrix account password' },\n { path: 'matrixRecoveryPhrase', displayName: 'Recovery Phrase', type: 'string', description: 'The Matrix recovery phrase' },\n { path: 'matrixHomeServerUrl', displayName: 'Matrix Homeserver', type: 'string', description: 'The Matrix homeserver URL' },\n ],\n run: async (rawInputs, ctx) => {\n // Parse form answers (JSON string from runtime.output.form.answers) and\n // merge them into inputs so existing inputs.<field> references resolve.\n // Explicit template inputs take precedence over form fields.\n const form = (() => {\n const raw = (rawInputs as Record<string, unknown>).formAnswers;\n if (typeof raw !== 'string' || !raw) return {};\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n })() as Record<string, unknown>;\n const inputs = {\n // Rename: form.logoUrl → avatarUrl for the registerMatrixAccount handler\n avatarUrl: form.logoUrl,\n ...form,\n ...rawInputs,\n } as typeof rawInputs & Record<string, unknown>;\n\n // --- Validate handlers ---\n if (!ctx.services.oracle?.createIidDocument) {\n throw new Error('oracle.createIidDocument handler not available');\n }\n if (!ctx.services.oracle?.registerMatrixAccount) {\n throw new Error('oracle.registerMatrixAccount handler not available');\n }\n\n // --- Validate IID inputs ---\n if (!inputs.mnemonic) throw new Error('mnemonic is required');\n if (!inputs.did) throw new Error('did is required');\n if (!inputs.address) throw new Error('address is required');\n if (!inputs.pubKey) throw new Error('pubKey is required');\n\n // --- Validate Matrix inputs ---\n if (!inputs.pin) throw new Error('pin is required');\n if (!inputs.oracleName) throw new Error('oracleName is required');\n\n // --- Phase 1: Create IID document ---\n const iidResult = (await ctx.services.oracle.createIidDocument({\n mnemonic: inputs.mnemonic,\n did: inputs.did,\n address: inputs.address,\n pubKey: inputs.pubKey,\n })) as { did: string; transactionHash: string; alreadyExisted?: boolean };\n\n // Validate IID result\n if (!iidResult?.transactionHash && !iidResult?.alreadyExisted) {\n throw new Error('IID creation returned success without a transaction hash or alreadyExisted flag');\n }\n\n // --- Phase 2: Register Matrix account ---\n const matrixResult = await ctx.services.oracle.registerMatrixAccount({\n mnemonic: inputs.mnemonic,\n address: inputs.address,\n did: inputs.did,\n pin: inputs.pin,\n oracleName: inputs.oracleName,\n avatarUrl: inputs.avatarUrl,\n });\n\n // Validate Matrix result\n if (!matrixResult?.matrixUserId) {\n throw new Error('Matrix registration returned success without a matrixUserId');\n }\n\n // --- Return combined output ---\n return {\n output: {\n did: iidResult.did || inputs.did,\n transactionHash: iidResult.transactionHash,\n alreadyExisted: iidResult.alreadyExisted || false,\n matrixUserId: matrixResult.matrixUserId,\n matrixAccessToken: matrixResult.matrixAccessToken,\n matrixRoomId: matrixResult.matrixRoomId,\n matrixDeviceId: matrixResult.matrixDeviceId,\n matrixMnemonic: matrixResult.matrixMnemonic,\n matrixPassword: matrixResult.matrixPassword,\n matrixRecoveryPhrase: matrixResult.matrixRecoveryPhrase,\n matrixHomeServerUrl: matrixResult.matrixHomeServerUrl,\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/entity.createOracle',\n can: 'entity/createOracle',\n sideEffect: true,\n proof: { fields: ['entityDid'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['mnemonic', 'address', 'did', 'pubKey', 'pin', 'matrixAccessToken', 'matrixRoomId', 'oracleName', 'apiUrl', 'price'],\n properties: {\n mnemonic: { type: 'string', description: 'BIP39 mnemonic for the oracle wallet.' },\n address: { type: 'string', description: 'The oracle wallet address.' },\n did: { type: 'string', description: 'The oracle DID.' },\n pubKey: { type: 'string', description: 'The oracle wallet public key.' },\n pin: { type: 'string', description: 'PIN used to sign the oracle entity creation.' },\n matrixAccessToken: { type: 'string', description: 'Matrix access token for the oracle.' },\n matrixRoomId: { type: 'string', description: 'Matrix room ID for the oracle.' },\n oracleName: { type: 'string', description: 'Display name of the oracle.' },\n apiUrl: { type: 'string', description: 'The oracle API URL.' },\n price: { type: 'string', description: 'The oracle subscription price.' },\n orgName: { type: 'string', description: 'Optional organization name.' },\n description: { type: 'string', description: 'Optional oracle description.' },\n location: { type: 'string', description: 'Optional oracle location.' },\n logoUrl: { type: 'string', description: 'Optional oracle logo URL.' },\n coverImageUrl: { type: 'string', description: 'Optional oracle cover image URL.' },\n llmModel: { type: 'string', description: 'Optional LLM model identifier.' },\n opening: { type: 'string', description: 'Optional oracle opening message.' },\n communicationStyle: { type: 'string', description: 'Optional oracle communication style.' },\n capabilities: { type: 'array', description: 'Optional oracle capabilities.' },\n mcpConfig: { type: 'object', description: 'Optional MCP configuration.' },\n parentProtocol: { type: 'string', description: 'Optional parent protocol DID.' },\n formAnswers: { type: 'string', description: 'Optional JSON string of form answers merged into inputs.' },\n },\n },\n outputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The oracle entity DID' },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The entity creation transaction hash' },\n {\n path: 'encryptionPublicKeyMultibase',\n displayName: 'Encryption Public Key (multibase)',\n type: 'string',\n description: 'Multibase-encoded P-256 public key registered as a keyAgreement vm on the entity DID',\n },\n {\n path: 'encryptionVerificationMethodId',\n displayName: 'Encryption Verification Method ID',\n type: 'string',\n description: 'DID verification method id of the P-256 keyAgreement key',\n },\n ],\n run: async (rawInputs, ctx) => {\n // Parse form answers (JSON string from runtime.output.form.answers) and\n // merge into inputs so existing inputs.<field> references resolve.\n const form = (() => {\n const raw = (rawInputs as Record<string, unknown>).formAnswers;\n if (typeof raw !== 'string' || !raw) return {};\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n })() as Record<string, unknown>;\n const inputs = { ...form, ...rawInputs } as typeof rawInputs & Record<string, unknown>;\n\n if (!ctx.services.oracle?.createOracleEntity) {\n throw new Error('oracle.createOracleEntity handler not available');\n }\n if (!inputs.mnemonic) throw new Error('mnemonic is required');\n if (!inputs.address) throw new Error('address is required');\n if (!inputs.did) throw new Error('did is required');\n if (!inputs.pubKey) throw new Error('pubKey is required');\n if (!inputs.pin) throw new Error('pin is required');\n if (!inputs.matrixAccessToken) throw new Error('matrixAccessToken is required');\n if (!inputs.matrixRoomId) throw new Error('matrixRoomId is required');\n if (!inputs.oracleName) throw new Error('oracleName is required');\n if (!inputs.apiUrl) throw new Error('apiUrl is required');\n if (!inputs.price) throw new Error('price is required');\n // network and matrixHomeServerUrl come from the platform's DefaultChainNetwork\n // in the consumer-side handler — this app is single-network.\n const result = await ctx.services.oracle.createOracleEntity({\n mnemonic: inputs.mnemonic,\n address: inputs.address,\n did: inputs.did,\n pubKey: inputs.pubKey,\n pin: inputs.pin,\n matrixAccessToken: inputs.matrixAccessToken,\n matrixRoomId: inputs.matrixRoomId,\n oracleName: inputs.oracleName,\n orgName: inputs.orgName,\n description: inputs.description,\n location: inputs.location,\n logoUrl: inputs.logoUrl,\n coverImageUrl: inputs.coverImageUrl,\n apiUrl: inputs.apiUrl,\n price: inputs.price,\n llmModel: inputs.llmModel,\n opening: inputs.opening,\n communicationStyle: inputs.communicationStyle,\n capabilities: inputs.capabilities,\n mcpConfig: inputs.mcpConfig,\n parentProtocol: inputs.parentProtocol,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/sandbox.provision',\n can: 'sandbox/provision',\n sideEffect: true,\n proof: { fields: ['status', 'sandboxUrl'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['entityDid', 'matrixRoomId'],\n properties: {\n entityDid: { type: 'string', description: 'Oracle entity DID to provision a sandbox for.' },\n matrixRoomId: { type: 'string', description: 'Matrix room id associated with the oracle.' },\n },\n },\n outputSchema: [\n { path: 'sandboxUrl', displayName: 'Sandbox URL', type: 'string', description: 'The provisioned sandbox URL' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'Provisioning status' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.provisionSandbox) {\n throw new Error('oracle.provisionSandbox handler not available');\n }\n if (!inputs.entityDid) throw new Error('entityDid is required');\n if (!inputs.matrixRoomId) throw new Error('matrixRoomId is required');\n\n const result = await ctx.services.oracle.provisionSandbox({\n entityDid: inputs.entityDid,\n matrixRoomId: inputs.matrixRoomId,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.contract',\n can: 'oracle/contract',\n sideEffect: true,\n proof: { fields: ['userOracleRoomId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['oracleEntityDid'],\n properties: {\n oracleEntityDid: { type: 'string', description: 'Oracle entity DID from the entity.createOracle output.' },\n },\n },\n outputSchema: [\n { path: 'userOracleRoomId', displayName: 'User↔Oracle Room ID', type: 'string', description: 'Matrix room id of the user↔oracle DM room' },\n { path: 'userOracleRoomAlias', displayName: 'User↔Oracle Room Alias', type: 'string', description: 'Matrix alias of the user↔oracle DM room' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.contract) {\n throw new Error('oracle.contract handler not available');\n }\n if (!inputs.oracleEntityDid) throw new Error('oracleEntityDid is required (from entity.createOracle output)');\n\n const result = await ctx.services.oracle.contract({\n oracleEntityDid: inputs.oracleEntityDid,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nconst SENSITIVE_PLAINTEXT_KEYS = ['SECP_MNEMONIC', 'MATRIX_ORACLE_ADMIN_PASSWORD', 'MATRIX_RECOVERY_PHRASE', 'MATRIX_VALUE_PIN'] as const;\n\nregisterAction({\n type: 'qi/oracle.storeSecrets',\n can: 'oracle/storeSecrets',\n sideEffect: true,\n proof: { fields: ['storedSecrets'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: [\n 'matrixRoomId',\n 'publicKeyMultibase',\n 'verificationMethodId',\n 'matrixHomeServerUrl',\n 'matrixUsername',\n 'matrixPassword',\n 'mnemonic',\n 'matrixRecoveryPhrase',\n 'pin',\n 'openRouterApiKeyJwe',\n ],\n properties: {\n matrixRoomId: { type: 'string', description: 'Matrix room id from the oracle.contract output.' },\n publicKeyMultibase: { type: 'string', description: 'Oracle public key (multibase) from the entity.createOracle output.' },\n verificationMethodId: { type: 'string', description: 'Verification method id from the entity.createOracle output.' },\n matrixHomeServerUrl: { type: 'string', description: 'Matrix homeserver URL from the matrix.register output.' },\n matrixUsername: { type: 'string', description: 'Matrix username from the matrix.register output.' },\n matrixPassword: { type: 'string', description: 'Matrix password from the matrix.register output.' },\n mnemonic: { type: 'string', description: 'Wallet mnemonic from the wallet.generate output.' },\n matrixRecoveryPhrase: { type: 'string', description: 'Matrix recovery phrase from the matrix.register output.' },\n pin: { type: 'string', description: 'PIN from the form output.' },\n openRouterApiKeyJwe: { type: 'string', description: 'JWE-encrypted OpenRouter API key from the form.' },\n mcpAuthSecrets: { type: 'object', description: 'Optional pre-encrypted MCP auth secrets (object or JSON string).' },\n },\n },\n outputSchema: [\n { path: 'storedSecrets', displayName: 'Stored Secrets', type: 'array', description: 'List of secret names stored' },\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'Matrix room where secrets are stored' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.storeSecrets) {\n throw new Error('oracle.storeSecrets handler not available');\n }\n // Routing\n if (!inputs.matrixRoomId) throw new Error('matrixRoomId is required (from oracle.contract output)');\n if (!inputs.publicKeyMultibase) throw new Error('publicKeyMultibase is required (from entity.createOracle output)');\n if (!inputs.verificationMethodId) throw new Error('verificationMethodId is required (from entity.createOracle output)');\n // Fresh mxLogin\n if (!inputs.matrixHomeServerUrl) throw new Error('matrixHomeServerUrl is required (from matrix.register output)');\n if (!inputs.matrixUsername) throw new Error('matrixUsername is required (from matrix.register output matrixUserId)');\n if (!inputs.matrixPassword) throw new Error('matrixPassword is required (from matrix.register output)');\n // Sensitive plaintext values\n if (!inputs.mnemonic) throw new Error('mnemonic is required (from wallet.generate output)');\n if (!inputs.matrixRecoveryPhrase) throw new Error('matrixRecoveryPhrase is required (from matrix.register output)');\n if (!inputs.pin) throw new Error('pin is required (from form output)');\n // OpenRouter must already be JWE-encrypted by the FlowDetail before submit\n if (!inputs.openRouterApiKeyJwe) {\n throw new Error('OPEN_ROUTER_API_KEY is required — enter it in the form before submitting');\n }\n\n const secrets: Record<string, string> = {\n SECP_MNEMONIC: inputs.mnemonic,\n MATRIX_ORACLE_ADMIN_PASSWORD: inputs.matrixPassword,\n MATRIX_RECOVERY_PHRASE: inputs.matrixRecoveryPhrase,\n MATRIX_VALUE_PIN: inputs.pin,\n };\n const preEncryptedSecrets: Record<string, string> = {\n OPEN_ROUTER_API_KEY: inputs.openRouterApiKeyJwe,\n };\n\n // Add MCP auth secrets if provided (already JWE-encrypted by FlowDetail)\n if (inputs.mcpAuthSecrets) {\n try {\n const mcpSecrets = typeof inputs.mcpAuthSecrets === 'string' ? JSON.parse(inputs.mcpAuthSecrets) : inputs.mcpAuthSecrets;\n if (mcpSecrets && typeof mcpSecrets === 'object') {\n Object.assign(preEncryptedSecrets, mcpSecrets);\n }\n } catch {\n console.warn('[oracle.storeSecrets] Failed to parse mcpAuthSecrets');\n }\n }\n\n // Sanity: do not let any sensitive plaintext key be empty after assembly\n for (const k of SENSITIVE_PLAINTEXT_KEYS) {\n if (!secrets[k]) throw new Error(`${k} is empty after assembly — refusing to call storeSecrets`);\n }\n\n const result = await ctx.services.oracle.storeSecrets({\n matrixRoomId: inputs.matrixRoomId,\n publicKeyMultibase: inputs.publicKeyMultibase,\n verificationMethodId: inputs.verificationMethodId,\n matrixHomeServerUrl: inputs.matrixHomeServerUrl,\n matrixUsername: inputs.matrixUsername,\n matrixPassword: inputs.matrixPassword,\n secrets,\n preEncryptedSecrets,\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.storeConfig',\n can: 'oracle/storeConfig',\n sideEffect: true,\n proof: { fields: ['configStored'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['matrixRoomId', 'oracleName', 'entityDid'],\n properties: {\n matrixRoomId: { type: 'string', description: 'Matrix room id from the oracle.contract output.' },\n oracleName: { type: 'string', description: 'Oracle name.' },\n entityDid: { type: 'string', description: 'Oracle entity DID.' },\n orgName: { type: 'string', description: 'Organisation name.' },\n description: { type: 'string', description: 'Oracle description.' },\n location: { type: 'string', description: 'Oracle location.' },\n price: { type: 'number', description: 'Oracle price; defaults to 0.' },\n apiUrl: { type: 'string', description: 'Oracle API URL.' },\n logoUrl: { type: 'string', description: 'Oracle logo URL.' },\n llmModel: { type: 'string', description: 'LLM model identifier.' },\n opening: { type: 'string', description: 'Oracle opening message.' },\n communicationStyle: { type: 'string', description: 'Oracle communication style.' },\n capabilities: { type: 'string', description: 'Oracle capabilities description.' },\n skills: { type: 'array', description: 'List of oracle skills.' },\n mcpServers: { type: 'array', description: 'List of configured MCP servers.' },\n matrixUserId: { type: 'string', description: 'Oracle Matrix user id.' },\n matrixAccountRoomId: { type: 'string', description: 'Oracle Matrix account room id.' },\n oracleAddress: { type: 'string', description: 'Oracle wallet address.' },\n oracleDid: { type: 'string', description: 'Oracle DID.' },\n },\n },\n outputSchema: [\n { path: 'configStored', displayName: 'Config Stored', type: 'boolean', description: 'Whether the oracle config was stored successfully' },\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'The Matrix room ID where config was stored' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.storeConfig) {\n throw new Error('oracle.storeConfig handler not available');\n }\n if (!inputs.matrixRoomId) throw new Error('matrixRoomId is required (from oracle.contract output)');\n if (!inputs.oracleName) throw new Error('oracleName is required');\n if (!inputs.entityDid) throw new Error('entityDid is required');\n\n const result = await ctx.services.oracle.storeConfig({\n matrixRoomId: inputs.matrixRoomId,\n config: {\n oracleName: inputs.oracleName,\n orgName: inputs.orgName || '',\n description: inputs.description || '',\n location: inputs.location || '',\n price: inputs.price ?? 0,\n apiUrl: inputs.apiUrl || '',\n entityDid: inputs.entityDid,\n logoUrl: inputs.logoUrl || '',\n llmModel: inputs.llmModel || '',\n opening: inputs.opening,\n communicationStyle: inputs.communicationStyle,\n capabilities: inputs.capabilities,\n skills: inputs.skills,\n mcpServers: inputs.mcpServers,\n matrixUserId: inputs.matrixUserId || '',\n matrixAccountRoomId: inputs.matrixAccountRoomId || '',\n oracleAddress: inputs.oracleAddress || '',\n oracleDid: inputs.oracleDid || '',\n },\n });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nconst SENSITIVE_PLAINTEXT_KEYS = ['SECP_MNEMONIC', 'MATRIX_ORACLE_ADMIN_PASSWORD', 'MATRIX_RECOVERY_PHRASE', 'MATRIX_VALUE_PIN'] as const;\n\nregisterAction({\n type: 'qi/oracle.storeSecretsAndConfig',\n can: 'oracle/storeSecretsAndConfig',\n sideEffect: true,\n proof: { fields: ['storedSecrets'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: [\n 'matrixRoomId',\n 'publicKeyMultibase',\n 'verificationMethodId',\n 'matrixHomeServerUrl',\n 'matrixUsername',\n 'matrixPassword',\n 'mnemonic',\n 'matrixRecoveryPhrase',\n 'pin',\n 'openRouterApiKeyJwe',\n 'oracleName',\n 'entityDid',\n ],\n properties: {\n matrixRoomId: { type: 'string', description: 'Matrix room id from the oracle.contract output.' },\n publicKeyMultibase: { type: 'string', description: 'Oracle public key (multibase) from the entity.createOracle output.' },\n verificationMethodId: { type: 'string', description: 'Verification method id from the entity.createOracle output.' },\n matrixHomeServerUrl: { type: 'string', description: 'Matrix homeserver URL from the matrix.register output.' },\n matrixUsername: { type: 'string', description: 'Matrix username from the matrix.register output.' },\n matrixPassword: { type: 'string', description: 'Matrix password from the matrix.register output.' },\n mnemonic: { type: 'string', description: 'Wallet mnemonic from the wallet.generate output.' },\n matrixRecoveryPhrase: { type: 'string', description: 'Matrix recovery phrase from the matrix.register output.' },\n pin: { type: 'string', description: 'PIN from the form output.' },\n openRouterApiKeyJwe: { type: 'string', description: 'JWE-encrypted OpenRouter API key from the form.' },\n mcpAuthSecrets: { type: 'object', description: 'Optional pre-encrypted MCP auth secrets (object or JSON string).' },\n oracleName: { type: 'string', description: 'Oracle name.' },\n entityDid: { type: 'string', description: 'Oracle entity DID.' },\n orgName: { type: 'string', description: 'Organisation name.' },\n description: { type: 'string', description: 'Oracle description.' },\n location: { type: 'string', description: 'Oracle location.' },\n price: { type: 'number', description: 'Oracle price; defaults to 0.' },\n apiUrl: { type: 'string', description: 'Oracle API URL.' },\n logoUrl: { type: 'string', description: 'Oracle logo URL.' },\n llmModel: { type: 'string', description: 'LLM model identifier.' },\n opening: { type: 'string', description: 'Oracle opening message.' },\n communicationStyle: { type: 'string', description: 'Oracle communication style.' },\n capabilities: { type: 'string', description: 'Oracle capabilities description.' },\n skills: { type: 'array', description: 'List of oracle skills.' },\n mcpServers: { type: 'array', description: 'List of configured MCP servers.' },\n matrixUserId: { type: 'string', description: 'Oracle Matrix user id.' },\n matrixAccountRoomId: { type: 'string', description: 'Oracle Matrix account room id.' },\n oracleAddress: { type: 'string', description: 'Oracle wallet address.' },\n oracleDid: { type: 'string', description: 'Oracle DID.' },\n },\n },\n outputSchema: [\n { path: 'storedSecrets', displayName: 'Stored Secrets', type: 'array', description: 'List of secret names stored' },\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'Matrix room where data is stored' },\n { path: 'configStored', displayName: 'Config Stored', type: 'boolean', description: 'Whether oracle config was stored' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.storeSecrets) throw new Error('oracle.storeSecrets handler not available');\n if (!ctx.services.oracle?.storeConfig) throw new Error('oracle.storeConfig handler not available');\n\n // ── Phase 1: Store Secrets ──────────────────────────────────────────\n // Routing\n if (!inputs.matrixRoomId) throw new Error('matrixRoomId is required (from oracle.contract output)');\n if (!inputs.publicKeyMultibase) throw new Error('publicKeyMultibase is required (from entity.createOracle output)');\n if (!inputs.verificationMethodId) throw new Error('verificationMethodId is required (from entity.createOracle output)');\n // Fresh mxLogin\n if (!inputs.matrixHomeServerUrl) throw new Error('matrixHomeServerUrl is required (from matrix.register output)');\n if (!inputs.matrixUsername) throw new Error('matrixUsername is required (from matrix.register output matrixUserId)');\n if (!inputs.matrixPassword) throw new Error('matrixPassword is required (from matrix.register output)');\n // Sensitive plaintext values\n if (!inputs.mnemonic) throw new Error('mnemonic is required (from wallet.generate output)');\n if (!inputs.matrixRecoveryPhrase) throw new Error('matrixRecoveryPhrase is required (from matrix.register output)');\n if (!inputs.pin) throw new Error('pin is required (from form output)');\n // OpenRouter must already be JWE-encrypted by the FlowDetail before submit\n if (!inputs.openRouterApiKeyJwe) {\n throw new Error('OPEN_ROUTER_API_KEY is required — enter it in the form before submitting');\n }\n\n const secrets: Record<string, string> = {\n SECP_MNEMONIC: inputs.mnemonic,\n MATRIX_ORACLE_ADMIN_PASSWORD: inputs.matrixPassword,\n MATRIX_RECOVERY_PHRASE: inputs.matrixRecoveryPhrase,\n MATRIX_VALUE_PIN: inputs.pin,\n };\n const preEncryptedSecrets: Record<string, string> = {\n OPEN_ROUTER_API_KEY: inputs.openRouterApiKeyJwe,\n };\n\n // Add MCP auth secrets if provided (already JWE-encrypted by FlowDetail)\n if (inputs.mcpAuthSecrets) {\n try {\n const mcpSecrets = typeof inputs.mcpAuthSecrets === 'string' ? JSON.parse(inputs.mcpAuthSecrets) : inputs.mcpAuthSecrets;\n if (mcpSecrets && typeof mcpSecrets === 'object') {\n Object.assign(preEncryptedSecrets, mcpSecrets);\n }\n } catch {\n console.warn('[oracle.storeSecretsAndConfig] Failed to parse mcpAuthSecrets');\n }\n }\n\n // Sanity: do not let any sensitive plaintext key be empty after assembly\n for (const k of SENSITIVE_PLAINTEXT_KEYS) {\n if (!secrets[k]) throw new Error(`${k} is empty after assembly — refusing to call storeSecrets`);\n }\n\n console.log('[oracle.storeSecretsAndConfig] Phase 1: storing secrets');\n const secretsResult = await ctx.services.oracle.storeSecrets({\n matrixRoomId: inputs.matrixRoomId,\n publicKeyMultibase: inputs.publicKeyMultibase,\n verificationMethodId: inputs.verificationMethodId,\n matrixHomeServerUrl: inputs.matrixHomeServerUrl,\n matrixUsername: inputs.matrixUsername,\n matrixPassword: inputs.matrixPassword,\n secrets,\n preEncryptedSecrets,\n });\n\n if (!secretsResult.storedSecrets || secretsResult.storedSecrets.length === 0) {\n throw new Error('storeSecrets returned success without any storedSecrets');\n }\n\n // ── Phase 2: Store Config ───────────────────────────────────────────\n if (!inputs.oracleName) throw new Error('oracleName is required');\n if (!inputs.entityDid) throw new Error('entityDid is required');\n\n console.log('[oracle.storeSecretsAndConfig] Phase 2: storing config');\n const configResult = await ctx.services.oracle.storeConfig({\n matrixRoomId: inputs.matrixRoomId,\n config: {\n oracleName: inputs.oracleName,\n orgName: inputs.orgName || '',\n description: inputs.description || '',\n location: inputs.location || '',\n price: inputs.price ?? 0,\n apiUrl: inputs.apiUrl || '',\n entityDid: inputs.entityDid,\n logoUrl: inputs.logoUrl || '',\n llmModel: inputs.llmModel || '',\n opening: inputs.opening,\n communicationStyle: inputs.communicationStyle,\n capabilities: inputs.capabilities,\n skills: inputs.skills,\n mcpServers: inputs.mcpServers,\n matrixUserId: inputs.matrixUserId || '',\n matrixAccountRoomId: inputs.matrixAccountRoomId || '',\n oracleAddress: inputs.oracleAddress || '',\n oracleDid: inputs.oracleDid || '',\n },\n });\n\n if (!configResult.configStored) {\n throw new Error('storeConfig returned success without configStored=true');\n }\n\n console.log('[oracle.storeSecretsAndConfig] Both phases complete');\n return {\n output: {\n storedSecrets: secretsResult.storedSecrets,\n roomId: secretsResult.roomId,\n configStored: configResult.configStored,\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nconst SENSITIVE_PLAINTEXT_KEYS = ['SECP_MNEMONIC', 'MATRIX_ORACLE_ADMIN_PASSWORD', 'MATRIX_RECOVERY_PHRASE', 'MATRIX_VALUE_PIN'] as const;\n\nregisterAction({\n type: 'qi/oracle.configureOracle',\n can: 'oracle/configureOracle',\n sideEffect: true,\n proof: { fields: ['configStored'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: [\n 'oracleEntityDid',\n 'publicKeyMultibase',\n 'verificationMethodId',\n 'matrixHomeServerUrl',\n 'matrixUsername',\n 'matrixPassword',\n 'mnemonic',\n 'matrixRecoveryPhrase',\n 'pin',\n 'openRouterApiKeyJwe',\n 'oracleName',\n 'entityDid',\n ],\n properties: {\n formAnswers: { type: 'string', description: 'Optional JSON string of form answers merged into the inputs.' },\n oracleEntityDid: { type: 'string', description: 'Oracle entity DID from the entity.createOracle output.' },\n publicKeyMultibase: { type: 'string', description: 'Oracle public key (multibase) from the entity.createOracle output.' },\n verificationMethodId: { type: 'string', description: 'Verification method id from the entity.createOracle output.' },\n matrixHomeServerUrl: { type: 'string', description: 'Matrix homeserver URL from the matrix.register output.' },\n matrixUsername: { type: 'string', description: 'Matrix username from the matrix.register output.' },\n matrixPassword: { type: 'string', description: 'Matrix password from the matrix.register output.' },\n mnemonic: { type: 'string', description: 'Wallet mnemonic from the wallet.generate output.' },\n matrixRecoveryPhrase: { type: 'string', description: 'Matrix recovery phrase from the matrix.register output.' },\n pin: { type: 'string', description: 'PIN from the form output.' },\n openRouterApiKeyJwe: { type: 'string', description: 'JWE-encrypted OpenRouter API key from the form.' },\n openRouterApiKeyPlaintext: { type: 'string', description: 'Optional plaintext OpenRouter API key passed through to the deploy output.' },\n mcpAuthSecrets: { type: 'object', description: 'Optional pre-encrypted MCP auth secrets (object or JSON string).' },\n oracleName: { type: 'string', description: 'Oracle name.' },\n entityDid: { type: 'string', description: 'Oracle entity DID.' },\n orgName: { type: 'string', description: 'Organisation name.' },\n description: { type: 'string', description: 'Oracle description.' },\n location: { type: 'string', description: 'Oracle location.' },\n price: { type: 'number', description: 'Oracle price; defaults to 0.' },\n apiUrl: { type: 'string', description: 'Oracle API URL.' },\n logoUrl: { type: 'string', description: 'Oracle logo URL.' },\n llmModel: { type: 'string', description: 'LLM model identifier.' },\n opening: { type: 'string', description: 'Oracle opening message.' },\n communicationStyle: { type: 'string', description: 'Oracle communication style.' },\n capabilities: { type: 'string', description: 'Oracle capabilities description.' },\n skills: { type: 'array', description: 'List of oracle skills.' },\n mcpServers: { type: 'array', description: 'List of configured MCP servers.' },\n matrixUserId: { type: 'string', description: 'Oracle Matrix user id.' },\n matrixAccountRoomId: { type: 'string', description: 'Oracle Matrix account room id.' },\n oracleAddress: { type: 'string', description: 'Oracle wallet address.' },\n oracleDid: { type: 'string', description: 'Oracle DID.' },\n },\n },\n outputSchema: [\n { path: 'userOracleRoomId', displayName: 'User-Oracle Room ID', type: 'string', description: 'Matrix room id from contract phase' },\n { path: 'userOracleRoomAlias', displayName: 'User-Oracle Room Alias', type: 'string', description: 'Matrix alias from contract phase' },\n { path: 'storedSecrets', displayName: 'Stored Secrets', type: 'array', description: 'List of secret names stored' },\n { path: 'roomId', displayName: 'Room ID', type: 'string', description: 'Matrix room where data is stored' },\n { path: 'configStored', displayName: 'Config Stored', type: 'boolean', description: 'Whether oracle config was stored' },\n { path: 'freshAccessToken', displayName: 'Fresh Access Token', type: 'string', description: 'Fresh Matrix access token from mxLogin during secret storage' },\n { path: 'openRouterApiKeyPlaintext', displayName: 'OpenRouter API Key', type: 'string', description: 'Plaintext OpenRouter API key for deploy' },\n ],\n run: async (rawInputs, ctx) => {\n // Parse form answers (JSON string from runtime.output.form.answers) and\n // merge into inputs so existing inputs.<field> references resolve.\n const form = (() => {\n const raw = (rawInputs as Record<string, unknown>).formAnswers;\n if (typeof raw !== 'string' || !raw) return {};\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n })() as Record<string, unknown>;\n const inputs = { ...form, ...rawInputs } as typeof rawInputs & Record<string, unknown>;\n\n if (!ctx.services.oracle?.contract) throw new Error('oracle.contract handler not available');\n if (!ctx.services.oracle?.storeSecrets) throw new Error('oracle.storeSecrets handler not available');\n if (!ctx.services.oracle?.storeConfig) throw new Error('oracle.storeConfig handler not available');\n\n // ── Phase 1: Contract ──────────────────────────────────────────────\n if (!inputs.oracleEntityDid) throw new Error('oracleEntityDid is required (from entity.createOracle output)');\n\n // Validate secrets inputs upfront so we fail fast before any side effects\n if (!inputs.publicKeyMultibase) throw new Error('publicKeyMultibase is required (from entity.createOracle output)');\n if (!inputs.verificationMethodId) throw new Error('verificationMethodId is required (from entity.createOracle output)');\n if (!inputs.matrixHomeServerUrl) throw new Error('matrixHomeServerUrl is required (from matrix.register output)');\n if (!inputs.matrixUsername) throw new Error('matrixUsername is required (from matrix.register output matrixUserId)');\n if (!inputs.matrixPassword) throw new Error('matrixPassword is required (from matrix.register output)');\n if (!inputs.mnemonic) throw new Error('mnemonic is required (from wallet.generate output)');\n if (!inputs.matrixRecoveryPhrase) throw new Error('matrixRecoveryPhrase is required (from matrix.register output)');\n if (!inputs.pin) throw new Error('pin is required (from form output)');\n if (!inputs.openRouterApiKeyJwe) {\n throw new Error('OPEN_ROUTER_API_KEY is required — enter it in the form before submitting');\n }\n if (!inputs.oracleName) throw new Error('oracleName is required');\n if (!inputs.entityDid) throw new Error('entityDid is required');\n\n console.log('[oracle.configureOracle] Phase 1: contracting oracle');\n const contractResult = await ctx.services.oracle.contract({\n oracleEntityDid: inputs.oracleEntityDid,\n });\n\n if (!contractResult.userOracleRoomId) {\n throw new Error('contract returned success without userOracleRoomId');\n }\n\n const matrixRoomId = contractResult.userOracleRoomId;\n\n // ── Phase 2: Store Secrets ─────────────────────────────────────────\n const secrets: Record<string, string> = {\n SECP_MNEMONIC: inputs.mnemonic,\n MATRIX_ORACLE_ADMIN_PASSWORD: inputs.matrixPassword,\n MATRIX_RECOVERY_PHRASE: inputs.matrixRecoveryPhrase,\n MATRIX_VALUE_PIN: inputs.pin,\n };\n const preEncryptedSecrets: Record<string, string> = {\n OPEN_ROUTER_API_KEY: inputs.openRouterApiKeyJwe,\n };\n\n // Add MCP auth secrets if provided (already JWE-encrypted by FlowDetail)\n if (inputs.mcpAuthSecrets) {\n try {\n const mcpSecrets = typeof inputs.mcpAuthSecrets === 'string' ? JSON.parse(inputs.mcpAuthSecrets) : inputs.mcpAuthSecrets;\n if (mcpSecrets && typeof mcpSecrets === 'object') {\n Object.assign(preEncryptedSecrets, mcpSecrets);\n }\n } catch {\n console.warn('[oracle.configureOracle] Failed to parse mcpAuthSecrets');\n }\n }\n\n // Sanity: do not let any sensitive plaintext key be empty after assembly\n for (const k of SENSITIVE_PLAINTEXT_KEYS) {\n if (!secrets[k]) throw new Error(`${k} is empty after assembly — refusing to call storeSecrets`);\n }\n\n console.log('[oracle.configureOracle] Phase 2: storing secrets');\n const secretsResult = await ctx.services.oracle.storeSecrets({\n matrixRoomId,\n publicKeyMultibase: inputs.publicKeyMultibase,\n verificationMethodId: inputs.verificationMethodId,\n matrixHomeServerUrl: inputs.matrixHomeServerUrl,\n matrixUsername: inputs.matrixUsername,\n matrixPassword: inputs.matrixPassword,\n secrets,\n preEncryptedSecrets,\n });\n\n if (!secretsResult.storedSecrets || secretsResult.storedSecrets.length === 0) {\n throw new Error('storeSecrets returned success without any storedSecrets');\n }\n\n // ── Phase 3: Store Config ──────────────────────────────────────────\n console.log('[oracle.configureOracle] Phase 3: storing config');\n const configResult = await ctx.services.oracle.storeConfig({\n matrixRoomId,\n config: {\n oracleName: inputs.oracleName,\n orgName: inputs.orgName || '',\n description: inputs.description || '',\n location: inputs.location || '',\n price: inputs.price ?? 0,\n apiUrl: inputs.apiUrl || '',\n entityDid: inputs.entityDid,\n logoUrl: inputs.logoUrl || '',\n llmModel: inputs.llmModel || '',\n opening: inputs.opening,\n communicationStyle: inputs.communicationStyle,\n capabilities: inputs.capabilities,\n skills: inputs.skills,\n mcpServers: inputs.mcpServers,\n matrixUserId: inputs.matrixUserId || '',\n matrixAccountRoomId: inputs.matrixAccountRoomId || '',\n oracleAddress: inputs.oracleAddress || '',\n oracleDid: inputs.oracleDid || '',\n },\n });\n\n if (!configResult.configStored) {\n throw new Error('storeConfig returned success without configStored=true');\n }\n\n console.log('[oracle.configureOracle] All 3 phases complete');\n return {\n output: {\n userOracleRoomId: contractResult.userOracleRoomId,\n userOracleRoomAlias: contractResult.userOracleRoomAlias,\n storedSecrets: secretsResult.storedSecrets,\n roomId: secretsResult.roomId,\n configStored: configResult.configStored,\n freshAccessToken: secretsResult.freshAccessToken || '',\n openRouterApiKeyPlaintext: inputs.openRouterApiKeyPlaintext || '',\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deploySetup',\n can: 'oracle/deploySetup',\n sideEffect: true,\n proof: { fields: ['setupComplete'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['name', 'config', 'roomId'],\n properties: {\n name: { type: 'string', description: 'Project name from the form.' },\n config: { type: 'object', description: 'Oracle config object (or its JSON string).' },\n roomId: { type: 'string', description: 'Matrix room id from the oracle contract/configure output.' },\n secrets: { type: 'object', description: 'Optional map of secret name to value passed to deploy setup.' },\n },\n },\n outputSchema: [\n { path: 'setupComplete', displayName: 'Setup Complete', type: 'boolean', description: 'Whether the oracle setup completed successfully' },\n { path: 'stdout', displayName: 'Build Output', type: 'string', description: 'Build stdout output' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.deploySetup) {\n throw new Error('oracle.deploySetup handler not available');\n }\n if (!inputs.name) throw new Error('name is required (project name from form)');\n\n const config = typeof inputs.config === 'string' ? JSON.parse(inputs.config) : inputs.config;\n if (!config || typeof config !== 'object') throw new Error('config is required (oracle config object)');\n\n if (!inputs.roomId) throw new Error('roomId is required (from oracle contract/configure output)');\n\n const secrets = inputs.secrets as Record<string, string> | undefined;\n const result = await ctx.services.oracle.deploySetup({ name: inputs.name, config, roomId: inputs.roomId, secrets });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deployStart',\n can: 'oracle/deployStart',\n sideEffect: true,\n proof: { fields: ['processId', 'status'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['name', 'entityDid', 'roomId'],\n properties: {\n name: { type: 'string', description: 'Project name from the form.' },\n entityDid: { type: 'string', description: 'Oracle entity DID from the entity.createOracle output.' },\n roomId: { type: 'string', description: 'Matrix room id from the oracle contract/configure output.' },\n secrets: { type: 'object', description: 'Optional map of secret name to value passed to deploy start.' },\n },\n },\n outputSchema: [\n { path: 'processId', displayName: 'Process ID', type: 'string', description: 'Running process identifier' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'Oracle process status' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.deployStart) {\n throw new Error('oracle.deployStart handler not available');\n }\n if (!inputs.name) throw new Error('name is required (project name from form)');\n if (!inputs.entityDid) throw new Error('entityDid is required (from entity.createOracle output)');\n if (!inputs.roomId) throw new Error('roomId is required (from oracle contract/configure output)');\n\n const secrets = inputs.secrets as Record<string, string> | undefined;\n const result = await ctx.services.oracle.deployStart({ name: inputs.name, entityDid: inputs.entityDid, roomId: inputs.roomId, secrets });\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deploy',\n can: 'oracle/deploy',\n sideEffect: true,\n proof: { fields: ['processId', 'status'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['name', 'entityDid', 'roomId', 'config'],\n properties: {\n name: { type: 'string', description: 'Project name from the form.' },\n entityDid: { type: 'string', description: 'Oracle entity DID from the entity.createOracle output.' },\n roomId: { type: 'string', description: 'Matrix room id from the oracle.configureOracle output.' },\n config: { type: 'object', description: 'Oracle config object (or its JSON string).' },\n secrets: { type: 'object', description: 'Optional map of secret name to value passed to deploy.' },\n },\n },\n outputSchema: [\n { path: 'setupComplete', displayName: 'Setup Complete', type: 'boolean', description: 'Whether the oracle setup completed successfully' },\n { path: 'processId', displayName: 'Process ID', type: 'string', description: 'Running process identifier' },\n { path: 'status', displayName: 'Status', type: 'string', description: 'Oracle process status' },\n { path: 'deploymentUrl', displayName: 'Deployment URL', type: 'string', description: 'The URL where the oracle was deployed' },\n { path: 'domainUpdateTxHash', displayName: 'Domain Update Tx', type: 'string', description: 'Transaction hash of the on-chain domain update' },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.oracle?.deploySetup) {\n throw new Error('oracle.deploySetup handler not available');\n }\n if (!ctx.services.oracle?.deployStart) {\n throw new Error('oracle.deployStart handler not available');\n }\n if (!inputs.name) throw new Error('name is required (project name from form)');\n if (!inputs.entityDid) throw new Error('entityDid is required (from entity.createOracle output)');\n if (!inputs.roomId) throw new Error('roomId is required (from oracle.configureOracle output)');\n\n const config = typeof inputs.config === 'string' ? JSON.parse(inputs.config) : inputs.config;\n if (!config || typeof config !== 'object') throw new Error('config is required (oracle config object)');\n\n const secrets = inputs.secrets as Record<string, string> | undefined;\n\n const setupResult = await ctx.services.oracle.deploySetup({ name: inputs.name, config, roomId: inputs.roomId, secrets });\n if (!setupResult.setupComplete) {\n throw new Error(`Deploy setup failed: ${setupResult.stderr || 'setupComplete was not true'}`);\n }\n\n const startResult = await ctx.services.oracle.deployStart({ name: inputs.name, entityDid: inputs.entityDid, roomId: inputs.roomId, secrets });\n if (!startResult.processId && startResult.status !== 'running') {\n throw new Error('Deploy start failed: no processId returned and status is not running');\n }\n\n let deploymentUrl: string | undefined;\n let domainUpdateTxHash: string | undefined;\n if (startResult.url) {\n if (!ctx.services.oracle?.updateOracleDomain) {\n console.warn('[oracle.deploy] updateOracleDomain handler not available, skipping domain update');\n } else {\n const domainResult = await ctx.services.oracle.updateOracleDomain({\n entityDid: inputs.entityDid,\n newApiUrl: startResult.url,\n });\n deploymentUrl = startResult.url;\n domainUpdateTxHash = domainResult.transactionHash;\n }\n }\n\n return {\n output: {\n setupComplete: setupResult.setupComplete,\n processId: startResult.processId,\n status: startResult.status,\n deploymentUrl,\n domainUpdateTxHash,\n },\n };\n },\n});\n","import type { ActionEventDefinition, OutputSchemaField } from '../../types';\n\n/**\n * Canonical action type for the single claim-collection lifecycle block.\n * One block, one runtime entry; `run()` dispatches on the `operation` input\n * (create | updateState | updateDates | updateQuota | updatePayments |\n * updateIntents | refresh) and always returns the full latest on-chain\n * `CollectionState` as `output` (IXO-2573).\n */\nexport const COLLECTION_LIFECYCLE_ACTION_TYPE = 'qi/collection.lifecycle';\n\n/**\n * Output schema = the fields of `CollectionState`. `output` always holds the\n * full latest on-chain collection state, never a per-operation delta.\n */\nexport const COLLECTION_LIFECYCLE_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Chain-assigned collection identifier' },\n { path: 'entity', displayName: 'Entity DID', type: 'string', description: 'Entity (deed) DID the collection belongs to' },\n { path: 'protocol', displayName: 'Protocol', type: 'string', description: 'Protocol DID/id the collection follows' },\n { path: 'admin', displayName: 'Admin Address', type: 'string', description: 'Address authorised to mutate the collection' },\n { path: 'state', displayName: 'State', type: 'number', description: 'Lifecycle state (0=OPEN, 1=PAUSED, 2=CLOSED)' },\n { path: 'startDate', displayName: 'Start Date', type: 'string', description: 'ISO-8601 start date' },\n { path: 'endDate', displayName: 'End Date', type: 'string', description: 'ISO-8601 end date' },\n { path: 'quota', displayName: 'Quota', type: 'string', description: 'Max claims; 0 = unlimited' },\n { path: 'count', displayName: 'Count', type: 'string', description: 'Number of claims submitted' },\n { path: 'evaluated', displayName: 'Evaluated', type: 'string', description: 'Number of claims evaluated' },\n { path: 'approved', displayName: 'Approved', type: 'string', description: 'Number of approved claims' },\n { path: 'rejected', displayName: 'Rejected', type: 'string', description: 'Number of rejected claims' },\n { path: 'disputed', displayName: 'Disputed', type: 'string', description: 'Number of disputed claims' },\n { path: 'payments', displayName: 'Payments', type: 'object', description: 'Payment legs (submission/evaluation/approval/rejection)' },\n { path: 'intents', displayName: 'Intents', type: 'object', description: 'Intent configuration' },\n];\n\n/**\n * Name of the event emitted once when a new collection is created on-chain\n * (IXO-2595). A listener block — e.g. Manage Collection Users\n * (`qi/collection.users`) — can declare a `block.event` trigger on this event\n * and will be queued for invocation, bound to the freshly-created collection,\n * the moment the create succeeds.\n */\nexport const COLLECTION_CREATED_EVENT_NAME = 'created';\n\n/**\n * Event vocabulary for the `created` event. The payload carries everything a\n * listener needs to act on the new collection without re-deriving it: the\n * chain-assigned `collectionId`, the owning `entity` (deed) DID and the\n * `protocol`. `pendingDisplayFields` drive the inline preview the assignee\n * sees in their pending-invocation list.\n *\n * Emitted ONLY on the `create` operation (see `./collection`); manage/update\n * /refresh runs never emit it. `getDynamicEvents` hides it from the trigger\n * picker for manage-mode blocks (those bound to an existing collectionId).\n */\nexport const COLLECTION_CREATED_EVENT: ActionEventDefinition = {\n name: COLLECTION_CREATED_EVENT_NAME,\n displayName: 'Collection created',\n description: 'Fires once when a new claim collection is created on-chain. Carries the collection id, entity (deed) DID and protocol so a listener can manage the new collection.',\n payloadSchema: [\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Chain-assigned collection identifier' },\n { path: 'entity', displayName: 'Entity DID', type: 'string', description: 'Entity (deed) DID the collection belongs to' },\n { path: 'protocol', displayName: 'Protocol', type: 'string', description: 'Protocol DID/id the collection follows' },\n { path: 'transactionHash', displayName: 'Tx Hash', type: 'string', description: 'MsgCreateCollection broadcast transaction hash' },\n ],\n pendingDisplayFields: ['collectionId', 'entity'],\n};\n\n// NOTE: The action is registered (with the real operation dispatcher `run()`)\n// in `./collection`. This module intentionally exports only the shared\n// constants (action type + output schema + event vocabulary) that `./collection`\n// and the FlowDetail/diff tracks import, so there is exactly one `registerAction`\n// call for `qi/collection.lifecycle` and no Phase-0 stub collision (IXO-2580).\n","import { registerAction } from '../../registry';\nimport type { ActionResult } from '../../types';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport { COLLECTION_CREATED_EVENT, COLLECTION_CREATED_EVENT_NAME, COLLECTION_LIFECYCLE_ACTION_TYPE, COLLECTION_LIFECYCLE_OUTPUT_SCHEMA } from './index';\nimport { CollectionStateEnum } from './types';\nimport type { CollectionCreateParams, CollectionIntentOptions, CollectionLifecycleRunInputs, CollectionState, CollectionWriteOperation, Payments } from './types';\n\n/**\n * Core `run()` for the single `qi/collection.lifecycle` block (IXO-2573 / IXO-2575).\n *\n * One action type, one runtime entry. `run()` dispatches on `inputs.operation`\n * and — per the architecture decision in IXO-2573 — `output` ALWAYS holds the\n * full latest on-chain `CollectionState`, never a per-operation delta. Every\n * write op therefore follows the same three steps:\n *\n * 1. broadcast its `Msg*` (via `ctx.services.collection.<method>`),\n * 2. re-fetch the full collection by id (`collection.get`),\n * 3. return that whole `CollectionState` as `output`.\n *\n * `refresh` is read-only: it skips step 1 (broadcasts nothing) and just reads\n * back state. It is the recovery primitive for the three moments `output` is\n * blank — loading an existing collection by id, recovering after a failed\n * write, and the in-flight window during an update.\n *\n * Proof guard (hard rule, see CLAUDE.md): a write op is only \"completed\" when\n * the service returned a `transactionHash` AND the follow-up `get` returned a\n * non-empty collection. `create` additionally asserts the chain assigned a\n * `collectionId`. A run that broadcasts but cannot read back state THROWS so the\n * executor writes `failed`; `refresh` then recovers the display. We never return\n * `output` without a resolved `collectionId`.\n */\n\n/** Coerce the optional numeric quota boundary string. `''`/undefined → absent. */\nfunction normalizeQuota(quota: string | undefined): string | undefined {\n if (quota === undefined || quota === null) return undefined;\n const trimmed = String(quota).trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Validate that a requested quota is acceptable for the collection's current\n * count. Mirrors the chain-side `ErrCollectionQuotaBelowCount`: `0` (unlimited)\n * is always allowed; otherwise the quota must be `>= count`.\n */\nfunction assertQuotaNotBelowCount(quota: string, count: string): void {\n if (quota === '0') return; // 0 = unlimited, always allowed.\n const quotaNum = Number(quota);\n const countNum = Number(count);\n if (!Number.isFinite(quotaNum) || quotaNum < 0) {\n throw new Error(`Invalid quota \"${quota}\". Quota must be a non-negative integer string (\"0\" = unlimited).`);\n }\n if (Number.isFinite(countNum) && quotaNum < countNum) {\n throw new Error(`Quota ${quota} is below the current submitted count ${count} (ErrCollectionQuotaBelowCount). Quota must be 0 (unlimited) or >= ${count}.`);\n }\n}\n\n/** Assert the fetched collection is non-empty (has a resolved collectionId). */\nfunction assertNonEmptyCollection(state: CollectionState | undefined | null, collectionId: string): asserts state is CollectionState {\n if (!state || !String(state.collectionId || '').trim()) {\n throw new Error(\n `Collection read-back returned empty state for collectionId \"${collectionId}\". Broadcast may have succeeded but chain state is not yet readable — retry via refresh.`\n );\n }\n}\n\nregisterAction<CollectionLifecycleRunInputs>({\n type: COLLECTION_LIFECYCLE_ACTION_TYPE,\n can: 'collection/lifecycle',\n sideEffect: true,\n // Chain transaction signed as the entity admin — only the human in the\n // Portal FlowDetail holds that authority. Orchestrators gather inputs and\n // hand off; they must not run or delegate this.\n executionOwner: 'human',\n // Dynamic resolvers predate merge-by-default and intentionally control\n // the full vocabulary (e.g. returning [] to hide the static baseline).\n dynamicResolutionMode: 'replace',\n proof: { fields: ['collectionId'] },\n done: {\n isDone: (state) => state.state === 'completed' && typeof state.output?.collectionId === 'string' && state.output.collectionId.length > 0,\n check: async ({ inputs, actionState, ctx }) => {\n const service = ctx.services?.collection;\n const collectionId = String(inputs.collectionId || actionState.output?.collectionId || '').trim();\n if (!service || !collectionId) {\n return {\n done: 'unknown',\n source: 'collection.chain',\n reason: !service ? 'Collection read service unavailable.' : 'No collection id is available for read-back.',\n };\n }\n try {\n const state = await service.get({ collectionId });\n assertNonEmptyCollection(state, collectionId);\n const operation = inputs.operation;\n let done = false;\n switch (operation) {\n case 'create':\n case 'refresh':\n done = true;\n break;\n case 'updateState':\n done = state.state === inputs.state;\n break;\n case 'updateDates':\n done = (inputs.startDate === undefined || state.startDate === inputs.startDate) && (inputs.endDate === undefined || state.endDate === inputs.endDate);\n break;\n case 'updateQuota':\n done = state.quota === normalizeQuota(inputs.quota);\n break;\n case 'updatePayments':\n done = JSON.stringify(state.payments || {}) === JSON.stringify(inputs.payments || {});\n break;\n case 'updateIntents':\n done = JSON.stringify(state.intents || {}) === JSON.stringify(inputs.intents || {});\n break;\n default:\n done = false;\n }\n return {\n done,\n source: 'collection.chain',\n ...(done ? { output: state as unknown as Record<string, unknown> } : {}),\n ...(!done ? { reason: `Collection state does not satisfy ${String(operation)}.` } : {}),\n };\n } catch (error) {\n return {\n done: 'unknown',\n source: 'collection.chain',\n reason: error instanceof Error ? error.message : 'Collection state could not be read.',\n };\n }\n },\n },\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: COLLECTION_LIFECYCLE_OUTPUT_SCHEMA,\n getDynamicOutputSchema: () => COLLECTION_LIFECYCLE_OUTPUT_SCHEMA,\n // Static vocabulary (used by the pending-invocation preview / compiler).\n events: [COLLECTION_CREATED_EVENT],\n // Only a CREATE entry point (no bound collectionId) can emit `created`, so a\n // manage-mode block bound to an existing collection is hidden from the\n // trigger picker as a source (IXO-2595).\n getDynamicEvents: (inputs) => (String(inputs?.collectionId || '').trim() ? [] : [COLLECTION_CREATED_EVENT]),\n inputSchema: {\n type: 'object',\n required: ['operation'],\n properties: {\n operation: { type: 'string', description: 'Lifecycle op to dispatch: create | updateState | updateDates | updateQuota | updatePayments | updateIntents | refresh.' },\n collectionId: { type: 'string', description: 'Target collection id; required for every op except create.' },\n entity: { type: 'string', description: 'create — entity (deed) DID the collection belongs to.' },\n protocol: { type: 'string', description: 'create — protocol DID the collection follows (must be a bare did:).' },\n state: { type: 'number', description: 'create/updateState — lifecycle state (0=OPEN, 1=PAUSED, 2=CLOSED).' },\n startDate: { type: 'string', description: 'create/updateDates — ISO-8601 start date.' },\n endDate: { type: 'string', description: 'create/updateDates — ISO-8601 end date.' },\n quota: { type: 'string', description: 'create/updateQuota — max claims; \"0\" = unlimited.' },\n payments: { type: 'object', description: 'create/updatePayments — payment legs.' },\n intents: { type: 'object', description: 'create/updateIntents — intent configuration.' },\n },\n },\n // Mirrors run()'s throw-preamble: `operation` selects the branch, `create`\n // needs the entity + protocol DIDs, and every other op targets an existing\n // collection so it needs `collectionId`. Per-op value validity (state enum,\n // quota vs count, at-least-one-date) stays with run().\n getMissingInputs: (inputs) => {\n const operation = String(inputs?.operation || '').trim();\n if (!operation) return ['operation'];\n if (operation === 'create') {\n const missing: string[] = [];\n if (!String(inputs?.entity || '').trim()) missing.push('entity');\n if (!String(inputs?.protocol || '').trim()) missing.push('protocol');\n return missing;\n }\n return String(inputs?.collectionId || '').trim() ? [] : ['collectionId'];\n },\n run: async (inputs, ctx): Promise<ActionResult> => {\n const service = ctx.services.collection;\n if (!service) {\n throw new Error('collection service not configured (ctx.services.collection is undefined)');\n }\n\n const operation = inputs.operation;\n if (!operation) {\n throw new Error('operation is required (create | updateState | updateDates | updateQuota | updatePayments | updateIntents | refresh)');\n }\n\n // ---- create: broadcast MsgCreateCollection, then read back full state ----\n if (operation === 'create') {\n const entity = String(inputs.entity || '').trim();\n const protocol = String(inputs.protocol || '').trim();\n if (!entity) throw new Error('create: entity is required');\n if (!protocol) throw new Error('create: protocol is required');\n // The protocol must be a bare DID. A non-DID value here is almost always\n // an unresolved claim-template reference (e.g. a creator-studio\n // `ref:<node>:did#<name>` placeholder) that slipped through the picker —\n // fail with a clear message instead of the chain's opaque DID-syntax error.\n if (!protocol.startsWith('did:') || protocol.includes('#')) {\n throw new Error(\n `create: protocol \"${protocol}\" is not a valid DID. The selected claim protocol did not resolve to a ledgered did:ixo: identifier (it may be an unresolved template reference). Re-pick the protocol from the entity's linked claims.`\n );\n }\n\n const quota = normalizeQuota(inputs.quota);\n\n // Consumer handler resolves the entity admin account + owner (gql.entity →\n // admin account + entity.owner) and fills each payment leg's `account`\n // with the resolved admin address — see impacts-x-webapp createCollection\n // reference. The editor only forwards the template configuration.\n const createParams: CollectionCreateParams = {\n entity,\n protocol,\n state: inputs.state,\n startDate: inputs.startDate,\n endDate: inputs.endDate,\n quota,\n payments: inputs.payments,\n intents: inputs.intents,\n };\n\n // ---- Act as the DAO POD: the MsgCreateCollection goes in the proposal.\n // The new collection id is only assigned when the proposal executes, so\n // the host snapshots the entity's existing collection ids at prepare\n // time and the finalize step diffs against the live list to resolve the\n // created one (`resolveGroupCreatedCollection`).\n if (isGroupExecution(inputs)) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const groupHandlers = ctx.handlers as any;\n if (typeof groupHandlers?.prepareGroupCollectionLifecycle !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupCollectionLifecycle');\n }\n const prepared = await groupHandlers.prepareGroupCollectionLifecycle({\n groupAddress: coreAddress,\n operation: 'create',\n params: createParams,\n });\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: prepared.msgs || [],\n expectedOutput: { collectionId: '', entity, protocol, state: inputs.state, startDate: inputs.startDate, endDate: inputs.endDate, quota, transactionHash: '' },\n finalize: 'collection.create-resolve',\n finalizeParams: {\n entityDid: entity,\n protocolDid: protocol,\n priorCollectionIds: Array.isArray(prepared.priorCollectionIds) ? prepared.priorCollectionIds : [],\n },\n completionEvent: COLLECTION_CREATED_EVENT_NAME,\n });\n }\n\n const result = await service.create(createParams);\n const transactionHash = String(result?.transactionHash || '').trim();\n const collectionId = String(result?.collectionId || '').trim();\n\n // Proof guard: create must yield both a tx hash and a chain-assigned id.\n if (!transactionHash) {\n throw new Error('create: service returned no transactionHash. Collection was not created.');\n }\n if (!collectionId) {\n throw new Error('create: service returned no collectionId. Cannot read back collection state.');\n }\n\n const state = await service.get({ collectionId });\n assertNonEmptyCollection(state, collectionId);\n // Emit `created` so listener blocks (e.g. Manage Collection Users) are\n // queued for invocation bound to this new collection. The payload carries\n // the chain truth (`state.*`), falling back to the validated inputs.\n return {\n output: state,\n events: [\n {\n name: COLLECTION_CREATED_EVENT_NAME,\n payload: {\n collectionId: String(state.collectionId || collectionId),\n entity: String(state.entity || entity),\n protocol: String(state.protocol || protocol),\n transactionHash,\n },\n },\n ],\n };\n }\n\n // ---- refresh: read-only, broadcasts nothing ----\n if (operation === 'refresh') {\n const collectionId = String(inputs.collectionId || '').trim();\n if (!collectionId) throw new Error('refresh: collectionId is required');\n\n const state = await service.get({ collectionId });\n assertNonEmptyCollection(state, collectionId);\n return { output: state };\n }\n\n // ---- write updates: collectionId required; admin resolved from chain ----\n const writeOp: CollectionWriteOperation = operation;\n const collectionId = String(inputs.collectionId || '').trim();\n if (!collectionId) throw new Error(`${writeOp}: collectionId is required`);\n\n // Pre-fetch the current collection: this resolves the authoritative admin\n // address for the update and (for updateQuota) the current count used by the\n // quota validation. It also confirms the collection exists before we\n // broadcast a mutation against it.\n const current = await service.get({ collectionId });\n assertNonEmptyCollection(current, collectionId);\n\n const adminAddress = String(current.admin || '').trim();\n if (!adminAddress) {\n throw new Error(`${writeOp}: could not resolve admin address for collection \"${collectionId}\" (chain state has no admin). Cannot authorise the update.`);\n }\n\n // ---- Act as the DAO group: propose instead of broadcasting directly ----\n // The host builds the same MsgExec-wrapped update with the GROUP as the\n // authorized executor; once the proposal passes, the update lands and the\n // block completes via read-back with the refreshed collection state.\n // (`create` as a group is not supported yet — the new collection id is\n // only knowable after execution.)\n if (isGroupExecution(inputs)) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const groupHandlers = ctx.handlers as any;\n if (typeof groupHandlers?.prepareGroupCollectionLifecycle !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupCollectionLifecycle');\n }\n const prepared = await groupHandlers.prepareGroupCollectionLifecycle({\n groupAddress: coreAddress,\n operation: writeOp,\n params: { ...inputs, collectionId, adminAddress },\n });\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs: prepared.msgs || [],\n expectedOutput: { ...current, collectionId, transactionHash: '' },\n finalize: 'collection.refresh',\n finalizeParams: { collectionId },\n });\n }\n\n let transactionHash = '';\n\n switch (writeOp) {\n case 'updateState': {\n const state = inputs.state;\n if (state === undefined || state === null) {\n throw new Error('updateState: state is required (0=OPEN, 1=PAUSED, 2=CLOSED)');\n }\n if (!(state in CollectionStateEnum) || typeof state !== 'number') {\n throw new Error(`updateState: invalid state \"${String(state)}\". Expected 0 (OPEN), 1 (PAUSED) or 2 (CLOSED).`);\n }\n const res = await service.updateState({ collectionId, state: state as CollectionStateEnum, adminAddress });\n transactionHash = String(res?.transactionHash || '').trim();\n break;\n }\n\n case 'updateDates': {\n const startDate = inputs.startDate;\n const endDate = inputs.endDate;\n if (!startDate && !endDate) {\n throw new Error('updateDates: at least one of startDate or endDate is required');\n }\n const res = await service.updateDates({ collectionId, startDate, endDate, adminAddress });\n transactionHash = String(res?.transactionHash || '').trim();\n break;\n }\n\n case 'updateQuota': {\n const quota = normalizeQuota(inputs.quota);\n if (quota === undefined) {\n throw new Error('updateQuota: quota is required (\"0\" = unlimited)');\n }\n // Validate against the current submitted count before broadcasting.\n assertQuotaNotBelowCount(quota, String(current.count || '0'));\n const res = await service.updateQuota({ collectionId, quota, adminAddress });\n transactionHash = String(res?.transactionHash || '').trim();\n break;\n }\n\n case 'updatePayments': {\n const payments = inputs.payments as Payments | undefined;\n if (!payments || typeof payments !== 'object') {\n throw new Error('updatePayments: payments is required');\n }\n const res = await service.updatePayments({ collectionId, payments, adminAddress });\n transactionHash = String(res?.transactionHash || '').trim();\n break;\n }\n\n case 'updateIntents': {\n const intents = inputs.intents as CollectionIntentOptions | undefined;\n if (!intents || typeof intents !== 'object') {\n throw new Error('updateIntents: intents is required');\n }\n const res = await service.updateIntents({ collectionId, intents, adminAddress });\n transactionHash = String(res?.transactionHash || '').trim();\n break;\n }\n\n default: {\n // Exhaustiveness guard — unreachable if CollectionWriteOperation is honoured.\n const _exhaustive: never = writeOp;\n throw new Error(`Unsupported collection operation: ${String(_exhaustive)}`);\n }\n }\n\n // Proof guard: write ops must return a transactionHash.\n if (!transactionHash) {\n throw new Error(`${writeOp}: service returned no transactionHash. The update was not broadcast.`);\n }\n\n // Re-fetch the full latest on-chain state so `output` is canonical truth.\n const updated = await service.get({ collectionId });\n assertNonEmptyCollection(updated, collectionId);\n return { output: updated };\n },\n});\n","import { registerAction, neverDone } from '../../registry';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { ActionResult } from '../../types';\nimport { COLLECTION_USERS_ACTION_TYPE, COLLECTION_USERS_MAX_GRANTS_PER_TX, COLLECTION_USERS_OUTPUT_SCHEMA } from './index';\nimport type { CollectionUserRole, CollectionUsersRunInputs } from './types';\n\n/**\n * Core `run()` for the single `qi/collection.users` block (IXO-2586).\n *\n * One action type, one runtime entry. `run()` dispatches on `inputs.operation`:\n *\n * - `add` → grant submit/evaluate authz for one collection to one or many\n * grantees. The grantee set comes from `granteeKind`: a single\n * address, the members the FlowDetail enumerated for a group, or\n * a list of accounts pasted in bulk. For more than one grantee\n * the dispatcher prefers `grantMany`, batching up to\n * COLLECTION_USERS_MAX_GRANTS_PER_TX grants per transaction (a\n * list within the cap is one signature; a longer one is split\n * into consecutive batches). It falls back to one `grant(...)`\n * per grantee only on a host that does not implement `grantMany`.\n * - `revoke` → per-collection read-modify-write revoke (the consumer handler\n * reads live authz, drops the target constraint, and re-grants\n * the remainder in a single atomic tx — see IXO-2590).\n * - `list` → read-only; returns the grantees holding a constraint for the\n * target collection.\n *\n * Proof guard (hard rule, see CLAUDE.md): a write op is only \"completed\" when\n * the service returned a non-empty `transactionHash`; `list` is only complete\n * when it returns a (possibly empty) `grantees` array. A handler that returns\n * `{}` THROWS so the executor writes `failed`.\n */\n\nfunction normalizeRole(value: string | undefined): CollectionUserRole {\n const normalized = String(value || '')\n .trim()\n .toLowerCase();\n if (normalized === 'submit' || normalized === 'evaluate') return normalized;\n throw new Error('role must be either \"submit\" or \"evaluate\"');\n}\n\n/**\n * The full set of addresses an `add` confers the grant on, in one place, so the\n * direct and the act-as-a-POD paths always agree on who is being granted:\n *\n * - `address-list` → the accounts pasted in bulk (IXO-4396),\n * - `group-members` → the members the FlowDetail enumerated,\n * - anything else → the single grantee address.\n *\n * De-duplicated (a spreadsheet paste and a group fan-out both repeat people)\n * and order-preserving. Throws when the selected kind resolved to nobody —\n * broadcasting an add that grants no one is never the intent.\n */\nfunction resolveAddGrantees(inputs: CollectionUsersRunInputs): string[] {\n const kind = inputs.granteeKind || 'user';\n let candidates: string[];\n\n if (kind === 'address-list') {\n candidates = Array.isArray(inputs.granteeAddresses) ? inputs.granteeAddresses.map((address) => String(address || '').trim()) : [];\n if (candidates.filter(Boolean).length === 0) {\n throw new Error('add (address-list): no accounts in the pasted list. Paste at least one valid ixo1… address.');\n }\n } else if (kind === 'group-members') {\n candidates = Array.isArray(inputs.members) ? inputs.members.map((member) => String(member?.address || '').trim()) : [];\n if (candidates.filter(Boolean).length === 0) {\n throw new Error('add (group-members): no members resolved to grant to. Enumerate the group members before signing.');\n }\n } else {\n candidates = [String(inputs.granteeAddress || '').trim()];\n if (!candidates[0]) throw new Error('add: granteeAddress is required');\n }\n\n return Array.from(new Set(candidates.filter(Boolean)));\n}\n\n/**\n * Opening of a batched-add failure message. A batch that already committed is\n * NOT rolled back by a later failure, so the message always leads with what\n * landed: how many accounts are already granted, and what remains to re-run.\n */\nfunction batchFailurePrefix(completedBatches: number, totalBatches: number, granted: number, total: number): string {\n if (totalBatches === 1) return `add: the grant of ${total} accounts was not broadcast.`;\n const remaining = total - granted;\n return `add: batch ${completedBatches + 1} of ${totalBatches} failed. ${granted} of ${total} accounts ARE granted and stay granted; re-run with the remaining ${remaining}.`;\n}\n\n/** Split the grantee list into the batches that each become one transaction. */\nfunction chunkGrantees(grantees: string[], size = COLLECTION_USERS_MAX_GRANTS_PER_TX): string[][] {\n const batches: string[][] = [];\n for (let i = 0; i < grantees.length; i += size) {\n batches.push(grantees.slice(i, i + size));\n }\n return batches;\n}\n\nregisterAction<CollectionUsersRunInputs>({\n type: COLLECTION_USERS_ACTION_TYPE,\n can: 'collection/users',\n sideEffect: true,\n // Authz grants signed by the entity admin — only the human in the Portal\n // FlowDetail holds that authority. Orchestrators gather inputs and hand\n // off; they must not run or delegate this.\n executionOwner: 'human',\n // Dynamic resolvers predate merge-by-default and intentionally control\n // the full vocabulary (e.g. returning [] to hide the static baseline).\n dynamicResolutionMode: 'replace',\n proof: { fields: ['transactionHash', 'collectionId'] },\n done: neverDone,\n // Repeatable: members are granted/revoked many times over the flow's life.\n // Never latches to a terminal Done. See cardinality.\n cardinality: 'many',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: COLLECTION_USERS_OUTPUT_SCHEMA,\n getDynamicOutputSchema: () => COLLECTION_USERS_OUTPUT_SCHEMA,\n // Can be wired to a `block.event` trigger (IXO-2596) — e.g. listen for the\n // `created` event from a Claim Collection block and manage the new\n // collection's users. When invoked from a pending invocation, `collectionId`\n // arrives via the event payload (merged into inputs by name); the FlowDetail\n // resolves the entity admin account from the payload `entity` and passes it\n // as `adminAddress`.\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['operation', 'collectionId', 'adminAddress'],\n properties: {\n operation: { type: 'string', description: 'Which user-management operation to run: add | revoke | list.' },\n collectionId: { type: 'string', description: 'Target claim collection identifier.' },\n adminAddress: { type: 'string', description: 'Granter entity admin account address (the authz granter).' },\n role: { type: 'string', description: 'Which authorization to act on for add/revoke: submit or evaluate.' },\n deedDid: { type: 'string', description: 'Entity (deed) DID forwarded to the handler.' },\n granteeAddress: { type: 'string', description: 'The single grantee bech32 address for add/revoke.' },\n granteeDid: { type: 'string', description: 'Optional resolved grantee DID for display or audit.' },\n granteeKind: { type: 'string', description: 'How to treat the add grantee: user, group-account, group-members, or address-list.' },\n agentQuota: { type: 'string', description: 'Remaining agent quota for add; 0 means unlimited.' },\n maxAmount: { type: 'array', description: 'Per-claim max amount cap for the add evaluate role.' },\n intentDurationNs: { type: 'string', description: 'Intent duration in nanoseconds for add, carried as a string.' },\n members: { type: 'array', description: 'Resolved members to fan the grant out to when granteeKind is group-members.' },\n granteeAddresses: { type: 'array', description: 'Accounts pasted in bulk to grant in one transaction when granteeKind is address-list.' },\n },\n },\n // Only the decision inputs are human-askable: `operation` selects the\n // branch and `collectionId` targets the collection (often filled by the\n // `created` event of an upstream collection.lifecycle block). adminAddress,\n // role and grantee fields are resolved by the host/FlowDetail, so a blank\n // there is not something to escalate to a human for.\n getMissingInputs: (inputs) => {\n const operation = String(inputs?.operation || '').trim();\n if (!operation) return ['operation'];\n return String(inputs?.collectionId || '').trim() ? [] : ['collectionId'];\n },\n run: async (inputs, ctx): Promise<ActionResult> => {\n const service = ctx.services.collectionUsers;\n if (!service) {\n throw new Error('collectionUsers service not configured (ctx.services.collectionUsers is undefined)');\n }\n\n const operation = inputs.operation;\n if (!operation) {\n throw new Error('operation is required (add | revoke | list)');\n }\n\n const collectionId = String(inputs.collectionId || '').trim();\n const adminAddress = String(inputs.adminAddress || '').trim();\n\n // ---- list: read-only; returns grantees for the collection ----------------\n if (operation === 'list') {\n if (!collectionId) throw new Error('list: collectionId is required');\n if (!adminAddress) throw new Error('list: adminAddress (entity admin account) is required');\n\n const result = await service.list({ granterAdminAddress: adminAddress, collectionId });\n const grantees = Array.isArray(result?.grantees) ? result.grantees : undefined;\n // Proof guard: list must return an array (empty is valid — no grantees yet).\n if (!grantees) {\n throw new Error('list: service returned no grantees array. Check the [collection:list] handler logs.');\n }\n // `operation` is echoed on every output: one block runs three ops with\n // three different output shapes, so the shape alone cannot tell the UI\n // which one produced the result it is rendering.\n return { output: { operation: 'list', grantees, collectionId } };\n }\n\n // ---- shared validation for the two write ops ------------------------------\n if (!collectionId) throw new Error(`${operation}: collectionId is required`);\n if (!adminAddress) throw new Error(`${operation}: adminAddress (entity admin account) is required`);\n const role = normalizeRole(inputs.role);\n const deedDid = String(inputs.deedDid || '').trim() || undefined;\n\n // ---- Act as the DAO group: propose instead of broadcasting directly ------\n // The host builds the same MsgExec-wrapped grant/revoke with the GROUP as\n // the signer (the group must hold the entity owner's authorization). For\n // group-members adds, every member's grant goes into ONE proposal.\n if (isGroupExecution(inputs) && (operation === 'add' || operation === 'revoke')) {\n const { coreAddress, title, description } = requireGroupExecutionParams(inputs);\n const groupHandlers = ctx.handlers as any;\n if (typeof groupHandlers?.prepareGroupCollectionUserChange !== 'function') {\n throw new Error('Acting as a POD is not available: the host does not implement prepareGroupCollectionUserChange');\n }\n if (!deedDid) throw new Error(`${operation}: deedDid is required when acting as a POD`);\n\n // An add fans out over the pasted list / group members / single address;\n // a revoke always targets exactly one grantee. Either way every message\n // goes into ONE proposal, so the POD votes once.\n let grantees: string[];\n if (operation === 'add') {\n grantees = resolveAddGrantees(inputs);\n // A proposal executes as a single transaction, so it is bound by the\n // same per-transaction ceiling as a direct grant. Splitting is not an\n // option here — that would mean several proposals and several votes —\n // so an oversized list is refused up front rather than passed to a vote\n // that could never execute.\n if (grantees.length > COLLECTION_USERS_MAX_GRANTS_PER_TX) {\n throw new Error(\n `add: ${grantees.length} grantees exceed the ${COLLECTION_USERS_MAX_GRANTS_PER_TX} per proposal limit when acting as a POD (the proposal executes as one transaction). Grant them in groups of ${COLLECTION_USERS_MAX_GRANTS_PER_TX} or fewer.`\n );\n }\n } else {\n const granteeAddress = String(inputs.granteeAddress || '').trim();\n if (!granteeAddress) throw new Error(`${operation}: granteeAddress is required`);\n grantees = [granteeAddress];\n }\n\n const msgs: Array<{ typeUrl: string; value: string }> = [];\n for (const granteeAddress of grantees) {\n const prepared = await groupHandlers.prepareGroupCollectionUserChange({\n groupAddress: coreAddress,\n operation,\n entityDid: deedDid,\n collectionId,\n adminAddress,\n role,\n granteeAddress,\n quota: inputs.agentQuota !== undefined && inputs.agentQuota !== null ? Number(inputs.agentQuota) : undefined,\n maxAmount: Array.isArray(inputs.maxAmount) ? inputs.maxAmount : undefined,\n });\n msgs.push(...(prepared.msgs || []));\n }\n\n return proposeGroupExecution(ctx, {\n coreAddress,\n title,\n description,\n msgs,\n expectedOutput: {\n operation,\n transactionHash: '',\n transactionHashes: [],\n grantedCount: operation === 'add' ? grantees.length : 0,\n role,\n collectionId,\n granteeAddress: grantees.length === 1 ? grantees[0] : undefined,\n granteeAddresses: operation === 'add' ? grantees : undefined,\n },\n });\n }\n\n // ---- revoke: per-collection read-modify-write -----------------------------\n if (operation === 'revoke') {\n const granteeAddress = String(inputs.granteeAddress || '').trim();\n if (!granteeAddress) throw new Error('revoke: granteeAddress is required');\n\n const result = await service.revoke({ granterAdminAddress: adminAddress, granteeAddress, collectionId, role });\n const transactionHash = String(result?.transactionHash || '').trim();\n if (!transactionHash) {\n throw new Error('revoke: service returned no transactionHash. The revoke was not broadcast.');\n }\n return { output: { operation: 'revoke', transactionHash, role, collectionId, granteeAddress } };\n }\n\n // ---- add: grant one collection's authz to one or many grantees ------------\n const agentQuota = inputs.agentQuota !== undefined && inputs.agentQuota !== null ? String(inputs.agentQuota).trim() || undefined : undefined;\n const maxAmount = Array.isArray(inputs.maxAmount) ? inputs.maxAmount : undefined;\n const intentDurationNs = String(inputs.intentDurationNs || '').trim() || undefined;\n const grantees = resolveAddGrantees(inputs);\n // The same grant configuration is conferred on every grantee — that is what\n // makes the bulk add a single signature rather than N.\n const grantConfig = { granterAdminAddress: adminAddress, collectionId, role, agentQuota, maxAmount, intentDurationNs, deedDid };\n\n // Many grantees, batched: up to COLLECTION_USERS_MAX_GRANTS_PER_TX grants\n // ride in one transaction, so a list within the cap is a single signature\n // and a longer one is split into consecutive batches (IXO-4396).\n if (grantees.length > 1 && typeof service.grantMany === 'function') {\n const batches = chunkGrantees(grantees);\n const transactionHashes: string[] = [];\n let granted = 0;\n\n for (const batch of batches) {\n // Each batch is its own transaction and its own signature, so a later\n // one failing — or being rejected in the wallet — does NOT undo the\n // earlier ones. Every failure therefore has to report how far it got,\n // or the user is told \"failed\" while N accounts hold live grants.\n let result: { transactionHash: string } | undefined;\n try {\n result = await service.grantMany({ ...grantConfig, granteeAddresses: batch });\n } catch (error) {\n throw new Error(`${batchFailurePrefix(transactionHashes.length, batches.length, granted, grantees.length)} ${error instanceof Error ? error.message : String(error)}`);\n }\n const hash = String(result?.transactionHash || '').trim();\n if (!hash) {\n throw new Error(`${batchFailurePrefix(transactionHashes.length, batches.length, granted, grantees.length)} The service returned no transactionHash.`);\n }\n transactionHashes.push(hash);\n granted += batch.length;\n }\n\n return {\n output: {\n operation: 'add',\n transactionHash: transactionHashes[transactionHashes.length - 1],\n transactionHashes,\n grantedCount: grantees.length,\n role,\n collectionId,\n granteeAddresses: grantees,\n batched: true,\n batchCount: batches.length,\n },\n };\n }\n\n // Fallback fan-out: one transaction (and one signature) per grantee. Only\n // reached on a host that does not implement `grantMany`. A failure part-way\n // through leaves the earlier grants in place, so the error says how far it\n // got — the user re-runs with the remainder.\n const transactionHashes: string[] = [];\n for (const granteeAddress of grantees) {\n // As with the batched path, an earlier grant stands when a later one\n // fails — so report the progress instead of a bare failure.\n let result: { transactionHash: string } | undefined;\n try {\n result = await service.grant({ ...grantConfig, granteeAddress });\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n if (grantees.length === 1) throw error instanceof Error ? error : new Error(cause);\n throw new Error(\n `add: the grant to ${granteeAddress} failed. ${transactionHashes.length} of ${grantees.length} accounts ARE granted and stay granted; re-run with the rest. ${cause}`\n );\n }\n const hash = String(result?.transactionHash || '').trim();\n if (!hash) {\n throw new Error(\n grantees.length === 1\n ? 'add: service returned no transactionHash. The grant was not broadcast.'\n : `add: the grant to ${granteeAddress} returned no transactionHash. ${transactionHashes.length} of ${grantees.length} accounts ARE granted and stay granted; re-run with the rest.`\n );\n }\n transactionHashes.push(hash);\n }\n\n return {\n output: {\n operation: 'add',\n transactionHash: transactionHashes[transactionHashes.length - 1],\n transactionHashes,\n grantedCount: transactionHashes.length,\n role,\n collectionId,\n granteeAddress: grantees.length === 1 ? grantees[0] : undefined,\n granteeAddresses: grantees,\n batched: false,\n },\n };\n },\n});\n","import type { OutputSchemaField } from '../../types';\n\n// ---------------------------------------------------------------------------\n// Shared output schemas for the carbon action types (IXO-2675).\n//\n// These drive the reference picker for `{{block.output.field}}` refs. The array\n// fields expose `itemSchema` so downstream blocks (harvest/retire) can pick the\n// per-batch fields, and so the harvest/retire FlowDetails can reference the\n// upstream `loadBatches` arrays.\n// ---------------------------------------------------------------------------\n\nconst HARVESTABLE_ITEM_SCHEMA: OutputSchemaField[] = [\n { path: 'id', displayName: 'Batch ID', type: 'string' },\n { path: 'entityDid', displayName: 'Entity DID', type: 'string' },\n { path: 'adminAddress', displayName: 'Admin Address', type: 'string' },\n { path: 'claimable', displayName: 'Claimable', type: 'number' },\n { path: 'alsoKnownAs', displayName: 'Entity Name', type: 'string' },\n];\n\nconst RETIREABLE_ITEM_SCHEMA: OutputSchemaField[] = [\n { path: 'id', displayName: 'Batch ID', type: 'string' },\n { path: 'amount', displayName: 'Amount', type: 'number' },\n { path: 'entityDid', displayName: 'Entity DID', type: 'string' },\n { path: 'alsoKnownAs', displayName: 'Entity Name', type: 'string' },\n];\n\n/** Output of `qi/carbon.loadBatches`. */\nexport const CARBON_LOAD_OUTPUT: OutputSchemaField[] = [\n { path: 'harvestableBatches', displayName: 'Harvestable Batches', type: 'array', itemSchema: HARVESTABLE_ITEM_SCHEMA, description: 'Batches with claimable credits' },\n { path: 'retireableBatches', displayName: 'Retireable Batches', type: 'array', itemSchema: RETIREABLE_ITEM_SCHEMA, description: 'Batches with credits available to retire' },\n { path: 'totalClaimable', displayName: 'Total Claimable', type: 'number', description: 'Sum of all claimable credits' },\n { path: 'totalAvailable', displayName: 'Total Available', type: 'number', description: 'Sum of all retireable credits' },\n { path: 'totalRetired', displayName: 'Total Retired', type: 'number', description: 'Sum of all retired credits' },\n];\n\n/** Output of `qi/carbon.harvest`. */\nexport const CARBON_HARVEST_OUTPUT: OutputSchemaField[] = [\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The harvest transaction hash' },\n {\n path: 'harvestedBatchIds',\n displayName: 'Harvested Batch IDs',\n type: 'array',\n itemSchema: [{ path: '', displayName: 'Batch ID', type: 'string' }],\n description: 'Ids of the harvested batches',\n },\n { path: 'harvestedAmount', displayName: 'Harvested Amount', type: 'number', description: 'Total credits harvested into the wallet' },\n];\n\n/** Output of `qi/carbon.retire`. */\nexport const CARBON_RETIRE_OUTPUT: OutputSchemaField[] = [\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The retire transaction hash' },\n {\n path: 'retiredBatchIds',\n displayName: 'Retired Batch IDs',\n type: 'array',\n itemSchema: [{ path: '', displayName: 'Batch ID', type: 'string' }],\n description: 'Ids of the retired batches',\n },\n { path: 'retiredAmount', displayName: 'Retired Amount', type: 'number', description: 'Total credits permanently retired' },\n { path: 'jurisdiction', displayName: 'Jurisdiction', type: 'string', description: 'Jurisdiction recorded on the retirement' },\n];\n","import { registerAction } from '../../registry';\nimport { CARBON_LOAD_OUTPUT } from './schemas';\n\n/**\n * qi/carbon.loadBatches — reconcile the user's owner-side and entity-admin-side\n * CARBON batches into the unified harvestable/retireable view (IXO-2675).\n *\n * Pure read (no side effect, no signing). The heavy lifting — the two-perspective\n * read, the owner-driven reconciliation, and provenance recovery for transferred\n * batches — lives in the consumer `carbon.loadBatches` handler. The editor only\n * validates the address and forwards the call; the returned payload becomes\n * `runtime.output` for downstream harvest/retire blocks to reference.\n */\nregisterAction({\n type: 'qi/carbon.loadBatches',\n can: 'carbon/load',\n sideEffect: false,\n proof: 'none',\n done: {\n isDone: (state) => state.state === 'completed',\n check: async ({ inputs, ctx }) => {\n if (!ctx.services?.carbon?.loadBatches || !inputs.ownerAddress) {\n return {\n done: 'unknown',\n source: 'carbon.chain',\n reason: 'Carbon read service or owner address is unavailable.',\n };\n }\n try {\n const output = await ctx.services.carbon.loadBatches({\n ownerAddress: inputs.ownerAddress,\n });\n return { done: true, source: 'carbon.chain', output };\n } catch (error) {\n return {\n done: 'unknown',\n source: 'carbon.chain',\n reason: error instanceof Error ? error.message : 'Carbon batches could not be read.',\n };\n }\n },\n },\n defaultRequiresConfirmation: false,\n inputSchema: {\n type: 'object',\n required: ['ownerAddress'],\n properties: {\n ownerAddress: { type: 'string', description: 'Wallet address whose owner-side and entity-admin-side CARBON batches are reconciled.' },\n },\n },\n outputSchema: CARBON_LOAD_OUTPUT,\n run: async (inputs, ctx) => {\n if (!ctx.services.carbon?.loadBatches) {\n throw new Error('carbon.loadBatches handler not available');\n }\n if (!inputs.ownerAddress) throw new Error('ownerAddress is required');\n\n const result = await ctx.services.carbon.loadBatches({\n ownerAddress: inputs.ownerAddress,\n });\n\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { CARBON_HARVEST_OUTPUT } from './schemas';\nimport type { CarbonHarvestRunInputs } from './types';\n\n/**\n * qi/carbon.harvest — claim (harvest) batches held on entity admin accounts the\n * user owns into the user's wallet (IXO-2675).\n *\n * User-signed. The consumer `carbon.harvest` handler builds the per-entity\n * authz-grant + exec-transfer pairs and signs them via the user's wallet; the\n * editor never signs on the user's behalf. Proof of a real harvest is the\n * returned `transactionHash` — we refuse to report success without it so the\n * FlowDetail's catch path writes `failed` instead of a stale `completed`.\n */\nregisterAction<CarbonHarvestRunInputs>({\n type: 'qi/carbon.harvest',\n can: 'carbon/harvest',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n inputSchema: {\n type: 'object',\n required: ['ownerAddress', 'tokens'],\n properties: {\n ownerAddress: { type: 'string', description: 'Wallet address owning the entity admin accounts to harvest from.' },\n tokens: { type: 'array', description: 'Batches to harvest; each requires id, entityDid, adminAddress and a claimable amount > 0.' },\n },\n },\n outputSchema: CARBON_HARVEST_OUTPUT,\n run: async (inputs, ctx) => {\n if (!ctx.services.carbon?.harvest) {\n throw new Error('carbon.harvest handler not available');\n }\n if (!inputs.ownerAddress) throw new Error('ownerAddress is required');\n const tokens = Array.isArray(inputs.tokens) ? inputs.tokens : [];\n if (tokens.length === 0) throw new Error('No batches selected to harvest');\n for (const t of tokens) {\n if (!t.id) throw new Error('Each harvest token requires an id');\n if (!t.entityDid) throw new Error(`Batch ${t.id} is missing entityDid (cannot construct harvest)`);\n if (!t.adminAddress) throw new Error(`Batch ${t.id} is missing adminAddress (cannot construct harvest)`);\n if (!(Number(t.claimable) > 0)) throw new Error(`Batch ${t.id} has no claimable amount`);\n }\n\n const result = await ctx.services.carbon.harvest({\n ownerAddress: inputs.ownerAddress,\n tokens: tokens.map((t) => ({ id: t.id, entityDid: t.entityDid, adminAddress: t.adminAddress, claimable: Number(t.claimable) })),\n });\n\n if (!result?.transactionHash) {\n throw new Error('carbon.harvest returned no transaction hash. Check the [carbon:harvest] handler logs.');\n }\n\n return { output: result };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { CARBON_RETIRE_OUTPUT } from './schemas';\nimport type { CarbonRetireRunInputs } from './types';\n\n/**\n * qi/carbon.retire — retire (burn/offset) credits the user holds in their\n * wallet (IXO-2675).\n *\n * User-signed and IRREVERSIBLE. The consumer `carbon.retire` handler builds and\n * signs a single `MsgRetireToken`. Proof of a real retirement is the returned\n * `transactionHash`; we refuse to report success without it.\n */\nregisterAction<CarbonRetireRunInputs>({\n type: 'qi/carbon.retire',\n can: 'carbon/retire',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n inputSchema: {\n type: 'object',\n required: ['owner', 'tokens'],\n properties: {\n owner: { type: 'string', description: 'Wallet address holding the credits to retire.' },\n tokens: { type: 'array', description: 'Batches to retire; each requires an id and an amount > 0.' },\n reason: { type: 'string', description: 'Retirement reason (defaults to \"offset\").' },\n jurisdiction: { type: 'string', description: 'Retirement jurisdiction (defaults to \"Global\").' },\n },\n },\n outputSchema: CARBON_RETIRE_OUTPUT,\n run: async (inputs, ctx) => {\n if (!ctx.services.carbon?.retire) {\n throw new Error('carbon.retire handler not available');\n }\n if (!inputs.owner) throw new Error('owner is required');\n const tokens = Array.isArray(inputs.tokens) ? inputs.tokens : [];\n if (tokens.length === 0) throw new Error('No batches selected to retire');\n for (const t of tokens) {\n if (!t.id) throw new Error('Each retire token requires an id');\n if (!(Number(t.amount) > 0)) throw new Error(`Batch ${t.id} has no amount to retire`);\n }\n\n const reason = inputs.reason || 'offset';\n const jurisdiction = inputs.jurisdiction || 'Global';\n\n const result = await ctx.services.carbon.retire({\n owner: inputs.owner,\n reason,\n jurisdiction,\n tokens: tokens.map((t) => ({ id: t.id, amount: Number(t.amount) })),\n });\n\n if (!result?.transactionHash) {\n throw new Error('carbon.retire returned no transaction hash. Check the [carbon:retire] handler logs.');\n }\n\n return { output: { ...result, jurisdiction } };\n },\n});\n","import type { OutputSchemaField } from '../../types';\n\n// ---------------------------------------------------------------------------\n// Output schema for qi/entity.transfer (IXO-2696).\n//\n// Drives the reference picker for `{{block.output.field}}` refs. `transactionHash`\n// is the proof field; `recipientResolved` / `createdRecipientIid` surface what\n// the host actually did (group→DAO resolution, recipient IID creation).\n// ---------------------------------------------------------------------------\n\nexport const ENTITY_TRANSFER_OUTPUT: OutputSchemaField[] = [\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The entity transfer transaction hash' },\n { path: 'recipientDid', displayName: 'Recipient DID', type: 'string', description: 'The new owner DID the entity was transferred to' },\n {\n path: 'recipientResolved',\n displayName: 'Resolved Recipient',\n type: 'string',\n description: 'The resolved recipient when a group entity was mapped to its DAO controller',\n },\n {\n path: 'createdRecipientIid',\n displayName: 'Created Recipient IID',\n type: 'boolean',\n description: \"True when the host created the recipient's IID document before transferring\",\n },\n];\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { ENTITY_TRANSFER_OUTPUT } from './schemas';\nimport type { EntityTransferRunInputs } from './types';\n\n/**\n * qi/entity.transfer — transfer ownership of an entity (domain) to a new owner\n * (IXO-2696).\n *\n * User-signed and IRREVERSIBLE. The consumer `entity.transfer` handler resolves\n * a group recipient to its DAO controller, ensures the recipient has an IID\n * document, builds a single `MsgTransferEntity`, and signs it via the user's\n * wallet — the editor never signs on the user's behalf. Proof of a real transfer\n * is the returned `transactionHash`; we refuse to report success without it so\n * the FlowDetail's catch path writes `failed` instead of a stale `completed`.\n */\nregisterAction<EntityTransferRunInputs>({\n type: 'qi/entity.transfer',\n can: 'entity/transfer',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n outputSchema: ENTITY_TRANSFER_OUTPUT,\n inputSchema: {\n type: 'object',\n required: ['entityDid', 'recipientDid'],\n properties: {\n entityDid: { type: 'string', description: 'Entity DID being transferred (did:ixo:entity:…).' },\n recipientDid: { type: 'string', description: 'New owner DID (user or did:ixo:wasm: controller).' },\n ownerDid: { type: 'string', description: 'Current owner DID; host defaults to the connected user when omitted.' },\n ownerAddress: { type: 'string', description: 'Current owner address; host defaults to the connected user when omitted.' },\n },\n },\n run: async (inputs, ctx) => {\n if (!ctx.services.entity?.transfer) {\n throw new Error('entity.transfer handler not available');\n }\n if (!inputs.entityDid) throw new Error('entityDid is required');\n if (!inputs.recipientDid) throw new Error('recipientDid is required');\n\n const result = await ctx.services.entity.transfer({\n entityDid: inputs.entityDid,\n recipientDid: inputs.recipientDid,\n ...(inputs.ownerDid ? { ownerDid: inputs.ownerDid } : {}),\n ...(inputs.ownerAddress ? { ownerAddress: inputs.ownerAddress } : {}),\n });\n\n if (!result?.transactionHash) {\n throw new Error('entity.transfer returned no transaction hash. Check the [entity:transfer] handler logs.');\n }\n\n return { output: { ...result, recipientDid: inputs.recipientDid } };\n },\n});\n","import type { ActionContext, ActionResult } from '../../types';\nimport { composeCollectionDescription } from './description';\nimport type { EvalRegisterRunInputs } from './types';\n\n/**\n * Enrolment stage of the merged \"Evaluation Engine\" block (`qi/eval.engine`) — pull-claim-spec\n * §6. Formerly its own registered `qi/eval.register` block (\"Enable Evaluation Engine\"); that\n * registration is gone (owner decision, 2026-07-30 — nothing referenced it once `qi/eval.engine`\n * shipped), but this function survives verbatim as the enrolment half `evalEngine.ts` imports and\n * calls directly. Enrolls a claim collection with the IXO Evaluation Engine in ONE signed step,\n * so the engine can read the collection's claims on the owner's behalf and enter the cron\n * poll-set.\n *\n * The step, in order:\n * 1. MINT the `owner → oracle` enrolment delegation host-side\n * (`service.mintBotDelegation`). The host owns the oracle-DID default, the\n * capability list, the `issuerType:'user'` signing, the medium TTL, and\n * revocability — the block passes only the optional overrides. It grants\n * TWO capabilities, because the engine acts as the owner in two places:\n * `{ can:'*', with:'ixo:matrix-claims-bot' }` to read the claim bodies\n * (spec §3.3), and `{ can:'subscriptions/read', with:'ixo:subscriptions' }`\n * so the engine can look up the owner's oracle claim collection — the\n * account per-claim fees are billed to (billing-spec §2/§18.4). A delegation\n * missing the second one enrols but can never be billed, and the engine\n * rejects that register rather than recording it silently. Returns the CAR\n * `token`.\n * 2. DEPOSIT that delegation into the UCAN Store\n * (`POST {ucanStoreUrl}/api/delegations { token }`), authorized by a\n * self-signed `store/add` invocation the host mints (`service.depositDelegation`).\n * 3. REGISTER the collection with the engine\n * (`POST {evalEngineUrl}/v1/collections/register`) so it joins the cron\n * poll-set (`service.registerCollection`). Idempotent upsert on\n * `collectionId`; carries the per-collection check `settings`\n * (eval-dashboard spec §B.1).\n * 4. GRANT on-chain evaluate authz to the engine — whenever \"Submit decisions\n * on chain\" (`allowChainEvaluation`) is on, which is the default. That setting and\n * this grant are the SAME decision: the setting tells the engine to submit\n * `MsgEvaluateClaim`, the grant is what makes the chain accept it. Granting\n * one without the other leaves an engine that tries and is rejected with\n * `authorization not found`. Granter = the entity admin account\n * (`adminAddress`, required for THIS step only), grantee = the engine's\n * address (explicit `oracleAddress`, else derived from the oracle DID),\n * capped by `evaluateMaxAmount`. Reuses the `qi/collection.users` grant\n * service (role 'evaluate'); reads never need it (spec §3.3).\n *\n * This block signs NO submit-authz grant: how the engine gets paid is settled\n * elsewhere (owner, 2026-07-27), so enrolment grants evaluator rights or nothing.\n *\n * This is its own COMPOSITE action — do not fold it into `qi/collection.users`\n * (generic authz CRUD) or `qi/claim.submit` (per-claim).\n *\n * No required user inputs beyond the collection binding: the oracle DID, store\n * URL, engine URL and rubric are optional overrides that fall back to host\n * defaults when blank.\n *\n * Proof guard (hard rule, see CLAUDE.md): enrollment is only \"completed\" when\n * the engine acknowledges registration with a non-empty `registrationId`. Each\n * host call that returns an empty result THROWS so the executor writes `failed`.\n *\n * Security: never log the pin or the delegation token. Fail loudly.\n */\nexport async function runEvalRegister(inputs: EvalRegisterRunInputs, ctx: ActionContext): Promise<ActionResult> {\n const service = ctx.services.evalRegister;\n if (!service) {\n throw new Error('evalRegister service not configured (ctx.services.evalRegister is undefined)');\n }\n\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n // Billing-notice identity (engine billing guide §10/§19). The name is optional; the email is\n // REQUIRED (owner, 2026-07-30) — a collection with no billing email has nowhere to be told\n // \"a payment failed / your evaluations paused\". Checked HERE, before the PIN prompt and the\n // delegation mint, so a blank or typo'd address fails cheap instead of after the whole\n // enrolment signed. The config UI prefills it from the owner's account (getNotificationEmail);\n // the engine's API keeps the field optional only for older published-editor clients.\n const displayName =\n String(inputs.displayName || '')\n .trim()\n .slice(0, 120) || undefined;\n const notifyEmail = String(inputs.notifyEmail || '').trim();\n if (!notifyEmail) {\n throw new Error(\n 'A billing email is needed: if a payment fails or your evaluations pause, that address is where we tell you. Add it in the block settings — it is filled from your account when we can read it.'\n );\n }\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(notifyEmail)) {\n throw new Error(`\"${notifyEmail}\" is not a valid email address — fix the billing email in the block settings.`);\n }\n // What this collection actually collects, in the owner's words — the context the engine's\n // duplicate-claim judge is otherwise missing (it sees two claim bodies and nothing else, so a\n // legitimate repeat of a daily task looks like the same claim sent twice). Three plain\n // questions composed into ONE opaque string here (`./description`); the engine stores it\n // verbatim and never parses it. Optional in every direction: unanswered composes to\n // `undefined`, and the key is then LEFT OFF the payload entirely — absent means \"no opinion\"\n // to the engine, while an explicit `''` would erase a description set on an earlier register.\n const description = composeCollectionDescription(inputs);\n // The person enabling the engine is the collection owner (the engine verifies\n // this DID against the on-chain collection admin). Defaults to the actor.\n const ownerDid = String(inputs.ownerDid || ctx.actorDid || '').trim();\n // Optional overrides — blank falls back to the host's network defaults.\n const oracleDid = String(inputs.oracleDid || '').trim() || undefined;\n const ttlDays = typeof inputs.ttlDays === 'number' && inputs.ttlDays > 0 ? inputs.ttlDays : undefined;\n const ucanStoreUrl = String(inputs.ucanStoreUrl || '').trim() || undefined;\n const evalEngineUrl = String(inputs.evalEngineUrl || '').trim() || undefined;\n const rubricId = String(inputs.rubricId || '').trim() || undefined;\n // Per-collection check settings (eval-dashboard spec §B.1) — absent means ON,\n // matching the config UI's defaults, so a caller that omits them (an agent\n // authoring the block, an event-triggered enrolment) gets the same enrolment\n // the owner would have signed. `!== false`: only an explicit opt-out counts.\n // Image detection lives inside the AI lane, so it is normalized to false\n // whenever AI checks are off (the UI nests the toggle the same way).\n const allowAiChecks = inputs.allowAiChecks !== false;\n const allowImageChecks = allowAiChecks && inputs.allowImageChecks !== false;\n const allowChainEvaluation = inputs.allowChainEvaluation !== false;\n // `=== true`, NOT `!== false` like the three above: this one is opt-IN. It tells the engine to\n // approve on chain even when the approval moves no money — correct for an attestation-only\n // collection, and a silent forfeit of the claimant's payout for a collection that has merely\n // not funded its approval lane yet. Defaulting it on the way the others default would hand that\n // forfeit to every caller who omitted the field.\n const allowZeroPayoutApprovals = inputs.allowZeroPayoutApprovals === true;\n\n if (!collectionId) throw new Error('collectionId is required');\n if (!deedDid) throw new Error('deedDid (entity/deed DID) is required');\n if (!ownerDid) throw new Error('ownerDid is required (pass it explicitly, or run as the collection owner)');\n\n // ---- 1) Mint the owner→oracle claim-bot delegation (host-signed) --------\n // Collect the PIN ONCE here and forward it to the mint so the owner is\n // prompted a single time for the whole \"Enable\" action (mintBotDelegation\n // uses this pin instead of prompting again; the store/register invocations\n // reuse the same decrypted session).\n let pin = String(inputs.pin || '').trim();\n if (!pin) {\n pin = await service.requestPin({\n title: 'Enable Evaluation Engine',\n description: 'Enter your PIN to authorize the evaluation engine for this collection',\n submitText: 'Authorize',\n });\n }\n if (!pin) throw new Error('PIN is required to authorize enrollment');\n\n // evalEngineUrl lets the host resolve the engine's DID from its /.well-known/did.json\n // (no hardcoded oracle DID); oracleDid stays an optional power-user override.\n const minted = await service.mintBotDelegation({ oracleDid, ttlDays, pin, evalEngineUrl });\n const delegationToken = String(minted?.token || '').trim();\n if (!delegationToken) {\n throw new Error('mintBotDelegation returned no token. The owner→oracle delegation was not created.');\n }\n\n // ---- 2) Deposit the delegation into the UCAN Store ----------------------\n const deposited = await service.depositDelegation({\n token: delegationToken,\n note: `eval-engine enrollment: collection ${collectionId}`,\n ucanStoreUrl,\n });\n const depositCid = String(deposited?.cid || '').trim();\n if (!depositCid) {\n throw new Error('depositDelegation returned no cid. The delegation was not stored in the UCAN Store.');\n }\n\n // ---- 3) Register the collection with the evaluation engine --------------\n const registration = await service.registerCollection({\n collectionId,\n deedDid,\n ownerDid,\n rubricId,\n evalEngineUrl,\n displayName,\n notifyEmail,\n // Spread, not `description,`: the key must be genuinely ABSENT when nothing was answered\n // (see above), and a host that copies `params` field-by-field would otherwise forward an\n // explicit `undefined` as the erasing empty value.\n ...(description !== undefined ? { description } : {}),\n settings: { allowAiChecks, allowImageChecks, allowChainEvaluation, allowZeroPayoutApprovals },\n });\n const registrationId = String(registration?.id || '').trim();\n // Proof guard: no id → enrollment did not land. THROW so the executor\n // records `failed` (never a silent `completed`).\n if (!registrationId) {\n throw new Error('registerCollection returned no id. The collection was not registered with the evaluation engine.');\n }\n\n // ---- 4) on-chain evaluate-authz grant, iff chain evaluation is on -------\n // The READ path (spec §3.3) needs only the delegation above; this grant is\n // what lets the engine SUBMIT the decision (`MsgEvaluateClaim`), which is\n // exactly what `allowChainEvaluation` promises the owner. So the setting\n // drives the grant — an engine told to write on chain without the authz is\n // rejected by the chain on every claim (\"authorization not found\").\n // Failure fails the whole action: enrolling an engine that cannot act is\n // half-broken, and the flow is idempotent (register upserts, the grant\n // re-issues), so the owner just retries.\n let evaluateAuthzTxHash: string | undefined;\n if (allowChainEvaluation) {\n // Granter: the entity admin account — only required for this grant, which\n // is why it is checked HERE and not as a precondition of enrolling.\n const granterAdminAddress = String(inputs.adminAddress || '').trim();\n if (!granterAdminAddress) {\n throw new Error('adminAddress (entity admin account) is required to grant the engine evaluator rights for on-chain decisions.');\n }\n // Grantee: explicit override first, else the oracle DID (`did:ixo:<addr>` →\n // `<addr>`) — the block's own input, falling back to the audience the mint\n // resolved from the engine's /.well-known/did.json.\n const granteeDid = oracleDid || String(minted?.oracleDid || '').trim();\n const oracleAddress = String(inputs.oracleAddress || '').trim() || (granteeDid.startsWith('did:ixo:') ? granteeDid.slice('did:ixo:'.length) : '');\n if (!oracleAddress) {\n throw new Error('The engine address is unknown: pass oracleAddress, or an oracleDid of the form did:ixo:<address> (hosts can echo it from mintBotDelegation).');\n }\n const grantService = ctx.services.collectionUsers;\n if (!grantService) throw new Error('collectionUsers service not configured (needed for the evaluate-authz grant)');\n\n const grant = await grantService.grant({\n granterAdminAddress,\n granteeAddress: oracleAddress,\n collectionId,\n role: 'evaluate',\n // The engine acts on every claim in the collection — the chain rejects a 0\n // quota, so use the effectively-unlimited value the portal already grants\n // its subscription oracles.\n agentQuota: '9999999',\n // The cap on what the engine may pay out per claim (`maxCustomAmount`), in\n // BASE units and the owner's chosen denoms — the config UI collects them,\n // this never picks one. An EMPTY cap rejects any evaluation that carries\n // coins, and the engine echoes an ordinary claim's own amount when it\n // approves it (intent claims carry none — the escrow pays).\n maxAmount: Array.isArray(inputs.evaluateMaxAmount) && inputs.evaluateMaxAmount.length > 0 ? inputs.evaluateMaxAmount : undefined,\n deedDid,\n });\n evaluateAuthzTxHash = String(grant?.transactionHash || '').trim() || undefined;\n if (!evaluateAuthzTxHash) {\n throw new Error('evaluate grant returned no transactionHash. The engine cannot submit decisions on chain — retry the registration.');\n }\n }\n\n return {\n output: {\n registrationId,\n collectionId,\n ownerDid,\n deedDid,\n depositCid,\n ...(oracleDid ? { oracleDid } : {}),\n ...(evaluateAuthzTxHash ? { evaluateAuthzTxHash } : {}),\n },\n };\n}\n","/**\n * Canonical serialization — rubric-spec §A.10.\n *\n * The rubric has ONE identifier and it costs nothing to make: the content hash\n * of the uploaded document, which the upload itself returns.\n *\n * rubricId == contentHash == LinkedResource.proof == sha256(the exact uploaded bytes)\n *\n * So nothing is computed, projected or derived here — no semantic projection,\n * no `rub_` id to construct, no hashing (the host hashes what it stores). What\n * remains matters for exactly one reason: an id that IS a hash of bytes is only\n * stable if the bytes are stable. `run()` serializes the envelope with\n * `canonicalJson` before upload, so the same rules always produce the same\n * bytes — and therefore the same id — regardless of the order the author\n * happened to click things together. That is what keeps §A.10's \"republishing\n * identical rules is a no-op\" honest.\n */\n\n/**\n * JCS-style canonical JSON: recursively sorted keys (code-unit order), no\n * whitespace, ES-number serialization. Throws on non-finite numbers — bytes an\n * id depends on must never contain a value JSON cannot round-trip.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`canonicalJson: non-finite number ${value}`);\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n // JSON semantics: an undefined element serializes as null.\n return `[${value.map((item) => (item === undefined ? 'null' : canonicalJson(item))).join(',')}]`;\n }\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`);\n return `{${entries.join(',')}}`;\n }\n throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);\n}\n","/**\n * Rules-checking + publishing logic for the merged \"Evaluation Engine\" block (`qi/eval.engine`)\n * — rubric-spec §B.2. Outputs the `rubricId` the composite's enrolment stage already accepted.\n * Formerly its own registered `qi/eval.rubric` block (\"Claim Approval Rules\"); that registration\n * (and its composer, `runEvalRubric`) is gone (owner decision, 2026-07-30 — nothing referenced\n * either once `qi/eval.engine` shipped). What survives is split in two, exactly as before, so\n * `qi/eval.engine` can run the checks BEFORE anything irreversible elsewhere in its own flow\n * (rules must fail before enrolment, never after):\n * - `preflightEvalRubric` — READ-ONLY. Steps 1, 2, 2b below. Nothing signed, nothing hashed,\n * nothing uploaded.\n * - `publishEvalRubric` — the write half. Steps 3–6 below, given the preflight's result verbatim.\n *\n * The step, in order:\n * 1. RE-VALIDATE the authored rubric against the catalog it was authored\n * against (`claimSchemaSnapshot`) — defense in depth; the config already\n * blocks save on errors.\n * 2. FORM RE-CHECK: reload the live claim form\n * (`handlers.getDeedSurveyTemplate`), re-extract the field catalog, and\n * re-validate — so rules can never be published referencing a question\n * that was deleted or retyped since authoring (`RUB_SCHEMA_DRIFT`).\n * 2b. ENGINE PRE-CHECK — ask the engine whether these rules would even be\n * accepted (§C.7); see `preflightEvalRubric`'s own comment for the\n * `settings` parameter this step now takes.\n * 3. SERIALIZE: wrap in the envelope (§A.2) → `bytes = canonicalJson(...)`.\n * Canonical (sorted keys, no whitespace) so identical rules always yield\n * identical bytes — and therefore an identical id.\n * 4. UPLOAD the exact bytes to Matrix media (`service.uploadRubric`, §C.1) →\n * `{ url, sha256 }`. **That `sha256` IS the `rubricId`** (§A.10): the id\n * is the content hash, so there is nothing to compute, compare or verify\n * — and no `@id` inside the document, which cannot contain its own hash.\n * 5. ANCHOR: replace any existing `#rub` (IID has no update: delete + add in\n * ONE transaction, the proven `domainCard.ts` pattern) via\n * `handlers.create{Delete,Add}LinkedResourceMessage` +\n * `handlers.executeTransaction` (§C.2) → `txHash`. The LinkedResource\n * `proof` is that same id.\n * 6. PIN (best-effort, non-fatal): tell the engine the new `rubricId` — it\n * re-resolves from chain regardless.\n *\n * The host does all I/O and signing (`ctx.services` / `ctx.handlers`), like\n * every other block; nothing here touches the network or a wallet directly.\n *\n * Proof guard (hard rule, see CLAUDE.md): rules are only \"published\" when the\n * anchor transaction lands. Every host call that returns an empty result\n * THROWS so the executor writes `failed` — a rubric that isn't on chain is a\n * rubric the engine will never see, and silently \"completing\" would leave the\n * owner believing their claims are being judged when they are not.\n */\n\nimport type { ActionContext, ActionResult } from '../../types';\nimport { canonicalJson } from './canonical';\nimport { extractRubricFieldCatalog } from './fieldCatalog';\nimport { validateRubricShape } from './schemaGate';\nimport { buildRubricEnvelope, type EvalRubricRunInputs, type RubricBody, type RubricFieldCatalog } from './types';\nimport { validateRubric } from './validate';\n\n/** What `publishEvalRubric` needs — computed once by `preflightEvalRubric` so the bytes it\n * canonicalizes and anchors are EXACTLY the ones that were validated and previewed, never\n * re-read or re-parsed from the original inputs. */\nexport interface EvalRubricPreflight {\n rubric: RubricBody;\n collectionId: string;\n evalEngineUrl?: string;\n}\n\n/**\n * READ-ONLY half — steps 1, 2, 2b. Re-validates against the authoring snapshot, reloads the LIVE\n * claim form and re-validates against that (drift since authoring surfaces as `RUB_SCHEMA_DRIFT`),\n * then asks the engine's pre-check whether these rules would even be accepted. Nothing here signs,\n * hashes, or uploads anything — every throw is cheap to hit and cheap to retry after a fix.\n *\n * `settings`: the engine's pre-check reads a collection's engine settings (allowAiChecks /\n * allowImageChecks / allowChainEvaluation) to judge AI rules truthfully — a rule set with AI\n * checks on is publishable but INERT on a collection with AI checks off. The legacy `qi/eval.rubric`\n * block always runs against an already-enrolled collection, so it omits this and the engine falls\n * back to its own stored row (unchanged from before this split). A caller running this BEFORE\n * enrolment (`qi/eval.engine`, which registers the collection in a later stage of the same run)\n * passes what it INTENDS those settings to be, so the truthfulness the engine's stored row used to\n * provide is preserved even though no such row exists yet.\n */\nexport async function preflightEvalRubric(\n inputs: EvalRubricRunInputs,\n ctx: ActionContext,\n settings?: { allowAiChecks: boolean; allowImageChecks: boolean; allowChainEvaluation: boolean }\n): Promise<EvalRubricPreflight> {\n const service = ctx.services.rubric;\n if (!service) {\n throw new Error('rubric service not configured (ctx.services.rubric is undefined)');\n }\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('handlers not available (ctx.handlers is undefined)');\n }\n\n const deedDid = String(inputs.deedDid || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n // Optional override — blank falls back to the host's network default\n // (mirrors `qi/eval.register`'s advanced `evalEngineUrl` input).\n const evalEngineUrl = String(inputs.evalEngineUrl || '').trim() || undefined;\n\n if (!deedDid) throw new Error('deedDid (entity/deed DID) is required');\n if (!collectionId) throw new Error('collectionId is required');\n\n // Inputs may arrive as objects or JSON strings (DataInput refs serialize).\n const rubric = dropRemovedKeys(parseObjectInput<RubricBody>(inputs.rubric, 'rubric'));\n const snapshot = parseObjectInput<RubricFieldCatalog>(inputs.claimSchemaSnapshot, 'claimSchemaSnapshot');\n if (!Array.isArray(snapshot.fields)) {\n throw new Error('claimSchemaSnapshot must carry the authored field catalog (fields[])');\n }\n\n // ---- 1) Re-validate against the authoring snapshot ----------------------\n throwOnErrors(validateRubric(rubric, snapshot), 'The rules are not valid');\n\n // ---- 2) Form re-check against the LIVE claim form -----------------------\n if (typeof handlers.getDeedSurveyTemplate !== 'function') {\n throw new Error('getDeedSurveyTemplate handler not implemented — the rules cannot be re-checked against the live claim form');\n }\n const template = await hostCall<any>('getDeedSurveyTemplate', () => handlers.getDeedSurveyTemplate!(deedDid, collectionId));\n const surveyTemplate = template?.surveyTemplate;\n if (!surveyTemplate) {\n throw new Error(`No claim form found for collection ${collectionId}. Rules can only be published against an existing form.`);\n }\n // The live form's own pin when the host returns one (§A.3) — it describes\n // this catalog, not the one the rules were authored against.\n const liveCatalog = extractRubricFieldCatalog(surveyTemplate, String(template?.proof || '') || snapshot.proof);\n // Passing the snapshot as the authoring catalog turns \"the question is\n // gone / has a different type now\" into RUB_SCHEMA_DRIFT — the honest\n // diagnosis (the form changed), not a vague unresolved-ref error. A moved\n // pin on its own is NOT drift: rewording a form's title changes its proof\n // without touching any question a rule depends on.\n throwOnErrors(validateRubric(rubric, liveCatalog, snapshot), 'The claim form changed since these rules were written');\n console.info('[eval.rubric] step validate — rules valid against the snapshot and the live form');\n\n // ---- 2b) ENGINE BACKSTOP before anything is signed (§A.12 / §C.7) ------\n // The editor's binder is looser than the engine's, and two things it cannot\n // know at all: whether the LIVE claim form still binds, and whether this\n // collection's engine settings permit these rules (AI rules on a collection\n // with AI checks off are publishable but inert — every claim would just pile\n // up in review). Asking the engine here is the last moment this costs\n // nothing; the write half (`publishEvalRubric`) is where the rubric gets\n // hashed and, eventually, anchored by a signed transaction.\n //\n // Fail closed in BOTH lanes: an unreachable engine must never read as valid.\n // `interactive: true` — every caller of this preflight is already inside a human-signed,\n // confirmation-gated action (`qi/eval.rubric` collecting the anchor PIN, or `qi/eval.engine`\n // collecting register's PIN later in the same run), so this is a call site allowed to prompt.\n const preview = service.previewRubric\n ? await service.previewRubric({ collectionId, rubric, evalEngineUrl, interactive: true, ...(settings ? { settings } : {}) }).catch((error) => {\n throw new Error(`Couldn't reach the rules service to check your rules — try again. (${errorMessageOf(error)})`);\n })\n : null;\n if (preview) {\n throwOnErrors(preview.problems, 'These rules cannot be published');\n console.info('[eval.rubric] step engine preview — passed');\n } else {\n // Older host: the local Ajv shape gate only. Strictly weaker (no form\n // binding, no settings check), but better than publishing unchecked.\n const shape = await validateRubricShape(rubric, service.getRubricSchema, evalEngineUrl);\n if (!shape.ok) {\n throw new Error(`Couldn't reach the rules service to check your rules — try again. (${shape.reason})`);\n }\n throwOnErrors(shape.problems, 'These rules have a setting the rules service will not accept');\n console.info('[eval.rubric] step schema gate — passed (host has no previewRubric)');\n }\n\n return { rubric, collectionId, evalEngineUrl };\n}\n\n/**\n * WRITE half — steps 3–6. Takes `preflightEvalRubric`'s result verbatim: canonicalize → upload to\n * Matrix (the hash IS the id, §A.10) → replace `#rub` in one delete+add anchor transaction (§C.2)\n * → best-effort pin. Proof guard (see CLAUDE.md): every host call that returns an empty result\n * THROWS so the executor writes `failed`, never a silent partial `completed`.\n */\nexport async function publishEvalRubric(preflight: EvalRubricPreflight, ctx: ActionContext): Promise<ActionResult> {\n const service = ctx.services.rubric;\n if (!service) {\n throw new Error('rubric service not configured (ctx.services.rubric is undefined)');\n }\n const handlers = ctx.handlers;\n if (!handlers) {\n throw new Error('handlers not available (ctx.handlers is undefined)');\n }\n const { rubric, collectionId, evalEngineUrl } = preflight;\n\n // ---- 3) Serialize the envelope, canonically ----------------------------\n // Canonical JSON (sorted keys, no whitespace): the id is the hash of these\n // bytes, so identical rules must produce identical bytes no matter what\n // order the author built them in — otherwise a no-op republish would mint\n // a new id (§A.10).\n const bytes = canonicalJson(buildRubricEnvelope(rubric));\n console.info('[eval.rubric] step canonicalize — envelope bytes built', { byteLength: bytes.length });\n\n // ---- 4) Upload to Matrix media — the returned hash IS the id -----------\n const uploaded = await hostCall('uploadRubric', () => service.uploadRubric({ json: bytes, fileName: 'rubric' }));\n console.info('[eval.rubric] step upload — stored', { url: uploaded?.url, sha256: uploaded?.sha256 });\n const resourceUrl = String(uploaded?.url || '').trim();\n if (!resourceUrl) {\n throw new Error('uploadRubric returned no url. The rubric document was not stored.');\n }\n // §A.10: rubricId == contentHash == LinkedResource.proof == sha256(bytes).\n // Nothing to compute and nothing to cross-check — the host hashes exactly\n // what it stored. No hash ⇒ no id ⇒ no content commitment to anchor, so\n // this is a hard stop rather than a publish with an empty proof.\n const rubricId = String(uploaded?.sha256 || '').trim();\n if (!rubricId) {\n throw new Error('uploadRubric returned no sha256. Without the content hash the rubric has no id and cannot be anchored.');\n }\n\n // ---- 5) Anchor the #rub LinkedResource on the protocol entity ----------\n if (typeof handlers.createAddLinkedResourceMessage !== 'function') {\n throw new Error('createAddLinkedResourceMessage handler not implemented');\n }\n if (typeof handlers.executeTransaction !== 'function') {\n throw new Error('executeTransaction handler not implemented');\n }\n\n const protocolDid = String(rubric.claimSchema?.protocol || '').trim();\n if (!protocolDid) {\n throw new Error('rubric.claimSchema.protocol is required — it names the protocol entity that carries the claim form and the rules');\n }\n\n const messages: unknown[] = [];\n // IID has no update: replacing rules is DELETE + ADD in the SAME\n // transaction, delete FIRST (the chain executes messages in order) — a bare\n // second add is rejected as a duplicated resource id (x/iid). The host's\n // `getRubricResource` reads the entity's existing `#rub` (its id EXACTLY as\n // stored on chain, e.g. the literal `{id}#rub`); an older host without the\n // service falls back to add-only, so a first publish never breaks.\n if (service.getRubricResource) {\n let existing: { id: string; proof: string } | null = null;\n try {\n existing = await service.getRubricResource({ protocolDid });\n } catch (error) {\n // The host could not answer \"is there a #rub already?\" — publishing\n // anyway would add-and-fail on chain, so stop with a readable error.\n console.error('[eval.rubric] getRubricResource rejected', error);\n throw new Error(`Couldn't check whether this protocol already has published rules — try again. (${errorMessageOf(error)})`);\n }\n console.info('[eval.rubric] step existing #rub —', existing?.id ?? 'none');\n if (existing?.id) {\n if (typeof handlers.createDeleteLinkedResourceMessage !== 'function') {\n throw new Error('This protocol already has rules, and the createDeleteLinkedResourceMessage handler is not implemented — they cannot be replaced.');\n }\n // The PROTOCOL entity explicitly (the rubric lives there, which need\n // not be the host's \"current\" entity), and the stored id verbatim.\n messages.push(await hostCall('createDeleteLinkedResourceMessage', () => handlers.createDeleteLinkedResourceMessage!({ entityDid: protocolDid, resourceId: existing!.id })));\n }\n } else {\n console.info('[eval.rubric] step existing #rub — host has no getRubricResource; composing add-only');\n }\n\n // §C.2 — `type: 'rubric'` + the `#rub` fragment is exactly what the\n // portal's existing `getDeedRubric` read path already matches.\n const resourceId = '{id}#rub';\n messages.push(\n await hostCall('createAddLinkedResourceMessage', () =>\n handlers.createAddLinkedResourceMessage!({\n entityDid: protocolDid,\n linkedResource: {\n id: resourceId,\n type: 'rubric',\n description: rubric.title || 'Claim Approval Rules',\n mediaType: 'application/ld+json',\n serviceEndpoint: resourceUrl,\n // The id IS the content commitment (§A.10) — one value, both jobs.\n proof: rubricId,\n encrypted: 'false',\n right: '',\n },\n })\n )\n );\n console.info(\n '[eval.rubric] step compose — messages',\n messages.map((message) => (message as { typeUrl?: string } | null)?.typeUrl ?? typeof message)\n );\n\n const anchored = await hostCall<{ transactionHash?: string }>('executeTransaction', () => handlers.executeTransaction!({ messages, memo: 'Set claim approval rules' }));\n console.info('[eval.rubric] step anchor — executeTransaction returned', anchored);\n const resourceTxHash = String(anchored?.transactionHash || '').trim();\n // Proof guard: no tx hash → the rules are not on chain. THROW so the\n // executor records `failed` (never a silent `completed`).\n if (!resourceTxHash) {\n throw new Error('The anchor transaction completed but returned no transaction hash. The rules were not published.');\n }\n\n // ---- 6) Tell the engine (best-effort; never fails the action) ----------\n // The engine re-resolves the rubric from chain on its own schedule, so a\n // failed pin costs nothing but a slower first pickup.\n if (service.pinRubric) {\n try {\n await service.pinRubric({ collectionId, rubricId, evalEngineUrl });\n console.info('[eval.rubric] step pin — engine notified of the new rubricId');\n } catch (error) {\n console.warn(`[eval.rubric] step pin — failed for collection ${collectionId}; the engine will re-resolve from chain. ${errorMessageOf(error)}`);\n }\n } else {\n console.info('[eval.rubric] step pin — skipped (host has no pinRubric)');\n }\n\n return {\n output: {\n rubricId,\n resourceId,\n protocolDid,\n collectionId,\n resourceUrl,\n resourceTxHash,\n },\n };\n}\n\n/**\n * The real message inside ANY throw shape. Host handlers don't only throw\n * `Error`s: the portal's `awaitTransaction` rejects with a plain STRING, SignX\n * with a raw event OBJECT — and the flow engine's `instanceof Error` branch\n * would surface those as a blank 'Execution failed'. Extracting here (and only\n * ever re-throwing real Errors from run()) keeps the actual failure text alive\n * without touching the shared executor.\n */\nfunction errorMessageOf(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === 'string' && error) return error;\n if (error && typeof error === 'object' && 'message' in error && (error as { message?: unknown }).message) {\n return String((error as { message: unknown }).message);\n }\n try {\n const serialized = JSON.stringify(error);\n if (serialized && serialized !== '{}' && serialized !== 'null' && serialized !== 'undefined') return serialized;\n } catch {\n // circular / unserializable — fall through\n }\n return 'Execution failed';\n}\n\n/**\n * Run one host call of the publish pipeline. A rejection of ANY shape logs RAW\n * (the full SignX event / chain rawLog always lands in the console) and\n * re-throws as a real `Error` named after the step, carrying the extracted\n * text — so the generic '[eval.rubric] execute failed' can never eat the\n * reason again.\n */\nasync function hostCall<T>(step: string, call: () => Promise<T>): Promise<T> {\n try {\n return await call();\n } catch (error) {\n console.error(`[eval.rubric] ${step} rejected`, error);\n throw new Error(`${step} failed: ${errorMessageOf(error)}`);\n }\n}\n\n/**\n * One-time migration for drafts authored before a key was removed from the format.\n *\n * A block's rubric body is persisted JSON in the flow document and is spread (`...body`) on every\n * edit, so a key the editor no longer WRITES can still ride along in a draft saved earlier. The\n * engine's Settlement is a strict object, so republishing such a draft fails the pre-publish check\n * on a key the author cannot see and has no control left to remove — a dead end. Dropping it here\n * means the next publish quietly writes a clean document.\n *\n * Currently: `settlement.maturityRung` (removed 2026-07-26 — whether a decision is acted on is the\n * collection's `allowChainEvaluation` setting, never the rubric's).\n */\nfunction dropRemovedKeys(body: RubricBody): RubricBody {\n const settlement = body.settlement as (RubricBody['settlement'] & { maturityRung?: unknown }) | undefined;\n if (!settlement || !('maturityRung' in settlement)) return body;\n const { maturityRung: _removed, ...rest } = settlement;\n console.info('[eval.rubric] dropped removed key settlement.maturityRung from a pre-existing draft');\n return { ...body, settlement: rest };\n}\n\n/** Inputs may arrive as an object or a JSON string; anything else is a configuration error. */\nfunction parseObjectInput<T>(raw: unknown, name: string): T {\n const value = typeof raw === 'string' ? safeParse(raw, name) : raw;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${name} is required and must be an object`);\n }\n return value as T;\n}\n\nfunction safeParse(raw: string, name: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n throw new Error(`${name} must be valid JSON`);\n }\n}\n\n/** Any error-severity diagnostic blocks the publish — name the codes so the UI can point at them. */\n// Structural, not `RubricDiagnostic[]`: the engine's preview returns codes the editor's own\n// diagnostic union doesn't know (the binder's `BIND_*` family), and only these four fields are read.\nfunction throwOnErrors(diagnostics: { code: string; severity: string; path: string; message: string }[], summary: string): void {\n const errors = diagnostics.filter((d) => d.severity === 'error');\n if (errors.length === 0) return;\n const detail = errors.map((d) => `${d.code}${d.path ? ` at ${d.path}` : ''}: ${d.message}`).join('; ');\n throw new Error(`${summary} — ${errors.length} problem(s) must be fixed before publishing. ${detail}`);\n}\n","import type { OutputSchemaField } from '../../types';\n\n/**\n * Output schema for the enrolment stage (`runEvalRegister`) of the merged \"Evaluation Engine\"\n * block (`qi/eval.engine`) — pull-claim-spec §6. `registrationId` + `collectionId` are the proof\n * fields (the engine's registration id acknowledges enrollment). The remaining fields are the\n * audit trail of the step so the reference picker can target them. `qi/eval.engine`'s own output\n * schema (`evalEngine/index.ts`) composes this with the rubric stage's.\n *\n * There was formerly a standalone `qi/eval.register` action type here too; it and its\n * `EVAL_REGISTER_ACTION_TYPE` constant are gone (owner decision, 2026-07-30 — nothing referenced\n * either once `qi/eval.engine` shipped).\n */\nexport const EVAL_REGISTER_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'registrationId', displayName: 'Registration ID', type: 'string', description: 'Evaluation engine registration id (proof of enrollment)' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Enrolled claim collection identifier' },\n { path: 'ownerDid', displayName: 'Owner DID', type: 'string', description: 'Collection owner DID (delegation issuer)' },\n { path: 'deedDid', displayName: 'Deed DID', type: 'string', description: 'Entity (deed) DID the collection belongs to' },\n { path: 'depositCid', displayName: 'Deposit CID', type: 'string', description: 'CID of the delegation deposited in the UCAN Store' },\n { path: 'oracleDid', displayName: 'Oracle DID', type: 'string', description: 'Evaluation engine DID (delegation audience), when overridden' },\n {\n path: 'evaluateAuthzTxHash',\n displayName: 'Evaluate Authz Tx',\n type: 'string',\n description: 'On-chain evaluate-authz grant tx hash — present when decisions are submitted on chain',\n },\n];\n\n// NOTE: `runEvalRegister` (the real logic) lives in `./evalRegister` and is registered nowhere on\n// its own — it is imported and called directly by `qi/eval.engine` (`../evalEngine/evalEngine.ts`).\n// This module exports only the shared output-schema constant that `./evalRegister` and\n// `../evalEngine/index.ts` import.\n","import type { OutputSchemaField } from '../../types';\n\n/**\n * Output schema for the rubric-publishing stage (`preflightEvalRubric` + `publishEvalRubric`) of\n * the merged \"Evaluation Engine\" block (`qi/eval.engine`) — rubric-spec §B.2. `rubricId` +\n * `resourceTxHash` are the proof fields (no anchor transaction ⇒ never \"completed\"). The\n * remaining fields are the audit trail of the publish so the reference picker can target them.\n * `qi/eval.engine`'s own output schema (`evalEngine/index.ts`) composes this with the register\n * stage's.\n *\n * There is no separate content-hash output: `rubricId` IS the sha256 of the published bytes and\n * the same value is the on-chain LinkedResource `proof` (§A.10) — one id, one hash, one thing to\n * quote in a receipt.\n *\n * There was formerly a standalone `qi/eval.rubric` action type here too; it and its\n * `EVAL_RUBRIC_ACTION_TYPE` constant are gone (owner decision, 2026-07-30 — nothing referenced\n * either once `qi/eval.engine` shipped).\n */\nexport const EVAL_RUBRIC_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'rubricId', displayName: 'Rubric ID', type: 'string', description: 'sha256 of the published rubric bytes — the id, and the on-chain proof (§A.10)' },\n { path: 'resourceId', displayName: 'Linked Resource ID', type: 'string', description: 'The #rub LinkedResource id on the protocol entity' },\n { path: 'protocolDid', displayName: 'Protocol DID', type: 'string', description: 'Protocol entity the rubric is anchored on (carries #vct and #rub)' },\n { path: 'collectionId', displayName: 'Collection ID', type: 'string', description: 'Claim collection these rules govern' },\n { path: 'resourceUrl', displayName: 'Rubric URL', type: 'string', description: 'Public Matrix media URL of the rubric document' },\n { path: 'resourceTxHash', displayName: 'Anchor Tx', type: 'string', description: 'Transaction hash of the on-chain anchor (proof of publish)' },\n];\n\n// NOTE: `preflightEvalRubric`/`publishEvalRubric` (the real logic) live in `./evalRubric` and are\n// registered nowhere on their own — they are imported and called directly by `qi/eval.engine`\n// (`../evalEngine/evalEngine.ts`). This module exports only the shared output-schema constant.\n","import type { OutputSchemaField } from '../../types';\nimport { EVAL_REGISTER_OUTPUT_SCHEMA } from '../evalRegister';\nimport { EVAL_RUBRIC_OUTPUT_SCHEMA } from '../evalRubric';\n\n/**\n * Canonical action type for the SINGLE \"Evaluation Engine\" block — the merge of\n * `qi/eval.register` (enrolment) and `qi/eval.rubric` (publish rules) into one signed run,\n * ordered CHECK THE RULES → ENROL → PUBLISH (owner requirement, 2026-07-30: a rules error must\n * fail before any irreversible work, never after). Checks-first is load-bearing precisely because\n * enrolment mints a delegation, deposits it, registers the collection, and — when decisions go on\n * chain — signs an on-chain evaluate-authz grant: none of that may happen for a rubric the engine\n * would reject. This is possible without losing truthfulness only because the engine's rubric\n * pre-check (`previewRubric`) now accepts the `settings` the caller INTENDS to enrol with, so it\n * can judge AI rules correctly before any settings row exists — see `preflightEvalRubric` in\n * `../evalRubric/evalRubric.ts`. The legacy `qi/eval.register` / `qi/eval.rubric` actions stay\n * registered (existing flows built on them keep running) but their mantine block-picker/config UI\n * was removed outright, not hidden behind a flag — there is no `pickerHidden` mechanism.\n */\nexport const EVAL_ENGINE_ACTION_TYPE = 'qi/eval.engine';\n\n/** Union of both stages' outputs — `collectionId` appears once. */\nexport const EVAL_ENGINE_OUTPUT_SCHEMA: OutputSchemaField[] = [...EVAL_REGISTER_OUTPUT_SCHEMA, ...EVAL_RUBRIC_OUTPUT_SCHEMA.filter((f) => f.path !== 'collectionId')];\n","import { doneWhenCompleted, registerAction } from '../../registry';\nimport type { ActionResult } from '../../types';\nimport { runEvalRegister } from '../evalRegister/evalRegister';\nimport type { EvalRegisterRunInputs } from '../evalRegister/types';\nimport { preflightEvalRubric, publishEvalRubric } from '../evalRubric/evalRubric';\nimport type { EvalRubricRunInputs } from '../evalRubric/types';\nimport { EVAL_ENGINE_ACTION_TYPE, EVAL_ENGINE_OUTPUT_SCHEMA } from './index';\n\n/**\n * Core `run()` for the single \"Evaluation Engine\" block: CHECK THE RULES, then ENROL, then\n * PUBLISH THEM — `preflightEvalRubric` (re-validate → live-form re-check → engine pre-check)\n * first, followed by `runEvalRegister` (mint owner→oracle delegation → deposit → register with\n * the settings → evaluate-authz grant when decisions go on chain), followed by\n * `publishEvalRubric` (canonicalize → upload → anchor `#rub` → pin).\n *\n * THIS ORDER — checks, then enrol, then publish — is the point (owner requirement, 2026-07-30): a\n * rules error must fail the run, never publish, and never happen AFTER irreversible work. The\n * previous order ran the checks inside stage 2, after enrolment, because the engine's pre-check\n * used to read a collection's engine settings from a database row that only existed once\n * enrolled. That constraint is gone — the preview endpoint now accepts the settings the caller\n * INTENDS to enrol with, so passing them (computed here with the exact same coercion\n * `runEvalRegister` itself applies, so the preview can never disagree with what stage 2 is about\n * to register) makes the pre-check truthful even before the collection exists. A rules failure\n * now aborts before a single delegation is minted, nothing is deposited, nothing is registered,\n * and no on-chain evaluate-authz grant is ever signed — and so does the one other precondition\n * that could otherwise land all of that first: `runEvalRegister`'s own missing-`adminAddress`\n * check (needed only when `allowChainEvaluation` is on) used to throw at its OWN step 4, after\n * the mint/deposit/register already happened. That exact condition is hoisted to the very top of\n * `run()` below, before stage 1, so it fails before ANYTHING runs, not just before publish.\n *\n * PIN prompts, honestly: this is NOT a guaranteed single prompt. `preflightEvalRubric`'s engine\n * pre-check calls `previewRubric({ interactive: true, ... })`, which — on the portal host — mints a\n * UCAN invocation through the SAME module-scoped signer cache every `mintUcanInvocation` call\n * shares (`useUcanInvocationSigner`'s `getOrCreateSigner`, 1h TTL), and pops its own PIN modal\n * (\"Check Claim Approval Rules\") whenever that cache is cold. `runEvalRegister`'s own `requestPin`\n * is a SEPARATE, always-fresh, uncached prompt (it feeds `mintBotDelegation`, not that signer\n * cache) — unaffected by this reorder either way. Because the signer cache is shared and\n * session-scoped rather than per-call-site, whichever `mintUcanInvocation`-backed call runs FIRST\n * in a cold session is the one eligible to prompt, and every later one in the SAME run (register's\n * own `registerCollection` mint, then publish's `pinRubric`) reuses it silently — the reorder\n * relocates which call that is, it does not add a new one on top. In practice the flow-mode\n * authoring UI (`useRubricDraft.ts`'s debounced re-check, silent-first / interactive-fallback on\n * every edit — the same hook `EvalEngineFlowDetail` uses) already exercises this exact call while\n * the author is still configuring the block, so by the time they hit Execute the session is\n * normally already warm and this preflight call is silent too. A cold first-open with zero prior\n * edits is the one case that can still show a prompt here. Reported as an open UX item, not fixed\n * in this action: the fix (if wanted) is portal-side (`impacts-x-web`), not in this file.\n *\n * Both stages 2 and 3 are idempotent, so a failure there is retried by re-running the whole block:\n * register upserts and re-issues the grant; the rubric's canonical bytes give the same id, and the\n * anchor replaces `#rub` in one delete+add tx. `publishEvalRubric` takes the preflight's result\n * verbatim — the rubric it anchors is EXACTLY the one that was checked, never re-read from inputs.\n *\n * Proof declares all three fields — registrationId (enrolment landed), rubricId + resourceTxHash\n * (rules are on chain) — for the manifest and the reference picker to see the full composite\n * shape. NOTE: the kernel's `ActionProofDeclaration.fields` check is ANY-OF (`proof.ts`), so the\n * declaration alone would pass on just one. The real all-three guarantee comes from each stage's\n * own throw-on-empty guard (`preflightEvalRubric` throws before `rubricId` ever exists if the rules\n * fail; `publishEvalRubric` throws without `rubricId`/`resourceTxHash`; `runEvalRegister` throws\n * without `registrationId`) — any throw aborts this `run()` before it can return at all — backed up\n * by the FlowDetail's own composite completeness check (`isCompletedWithProof`) before it ever\n * renders a completed state.\n */\nregisterAction<EvalRegisterRunInputs & EvalRubricRunInputs>({\n type: EVAL_ENGINE_ACTION_TYPE,\n can: 'eval/engine',\n sideEffect: true,\n dynamicResolutionMode: 'replace',\n proof: { fields: ['registrationId', 'rubricId', 'resourceTxHash'] },\n done: doneWhenCompleted,\n executionOwner: 'human',\n cardinality: 'once',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n outputSchema: EVAL_ENGINE_OUTPUT_SCHEMA,\n getDynamicOutputSchema: () => EVAL_ENGINE_OUTPUT_SCHEMA,\n // Same listener story as qi/eval.register: a Claim Collection `created` event can bind the\n // collection; the rules are then authored in flow mode against that collection's form.\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['collectionId', 'deedDid', 'notifyEmail', 'rubric', 'claimSchemaSnapshot'],\n properties: {\n // ---- shared context ----\n collectionId: { type: 'string', description: 'Target claim collection to enroll and govern.' },\n deedDid: { type: 'string', description: 'Entity (deed) DID the collection belongs to.' },\n // ---- enrolment (qi/eval.register) ----\n displayName: { type: 'string', description: \"Optional collection name, shown on the engine's billing emails next to the collection id.\" },\n notifyEmail: { type: 'string', description: 'Required billing email — failed payments and paused evaluations are announced there.' },\n // The three plain answers about what this collection collects. They are composed into the\n // engine's one opaque `description` string inside `runEvalRegister` — an agent authoring\n // this block answers the questions, it never writes the sentence.\n whatIsCollected: { type: 'string', description: 'One sentence on what people do to make a claim here (max 300).' },\n repeatSubmissions: {\n type: 'string',\n enum: ['normal', 'sometimes', 'once'],\n description: 'Can the same person claim again tomorrow? normal = expected, sometimes = happens, once = one-off only.',\n },\n differentWhen: {\n type: 'array',\n description: 'What differs between two legitimate claims from the same person: date, amount, place, kind, photos.',\n },\n differentWhenOther: { type: 'string', description: 'Anything else that differs, in the owner’s own words (max 100).' },\n ownerDid: { type: 'string', description: 'Collection owner DID. Defaults to the connected actor.' },\n oracleDid: { type: 'string', description: 'Optional override of the engine DID (delegation audience). Blank = host default.' },\n ttlDays: { type: 'number', description: 'Optional delegation lifetime override in days. Blank = host default.' },\n ucanStoreUrl: { type: 'string', description: 'UCAN Store base URL. Optional; host resolves from network if omitted.' },\n evalEngineUrl: { type: 'string', description: 'Evaluation engine base URL. Optional; host resolves from network if omitted.' },\n adminAddress: { type: 'string', description: 'Granter entity admin account address — required when decisions are submitted on chain.' },\n oracleAddress: { type: 'string', description: 'Engine grantee address override for the on-chain grants. Blank = derived from the oracle DID.' },\n pin: { type: 'string', description: 'Verification PIN; requested at runtime if omitted.' },\n allowAiChecks: { type: 'boolean', default: true, description: 'Engine setting: allow paid AI checks for this collection.' },\n allowImageChecks: { type: 'boolean', default: true, description: 'Engine setting: allow fake-photo detection (needs AI checks on).' },\n allowChainEvaluation: { type: 'boolean', default: true, description: 'Engine setting: submit the decision on chain (releases payment); makes adminAddress required.' },\n allowZeroPayoutApprovals: {\n type: 'boolean',\n default: false,\n description: 'Engine setting: approve on chain even when the approval pays nothing (attestation-only collections). Opt-in — otherwise such approvals wait for the owner.',\n },\n evaluateMaxAmount: { type: 'array', description: \"Per-claim payout cap on the evaluate grant, base-unit coins in the owner's denoms.\" },\n // ---- rules (qi/eval.rubric) ----\n rubric: {\n type: 'object',\n description: 'The authored rubric body (§A.2), the duplicate-claim `unique` block included (dup-detection spec §6); envelope + @id computed at publish.',\n },\n claimSchemaSnapshot: { type: 'object', description: 'The field catalog the rules were authored against (§B.4).' },\n },\n },\n run: async (inputs, ctx): Promise<ActionResult> => {\n // Stage 0 — FAIL EARLY on the one precondition `runEvalRegister` only checks at its OWN\n // step 4 (evalRegister.ts): a missing `adminAddress` when `allowChainEvaluation` is on used to\n // throw AFTER the delegation was minted, deposited, and the collection registered — exactly\n // the \"irreversible before a failed check\" pattern the preflight reorder exists to close.\n // Mirrors that check's condition and message VERBATIM; `runEvalRegister`'s own check stays in\n // place below for the legacy `qi/eval.register` action, which has no earlier stage to hoist to.\n if (inputs.allowChainEvaluation !== false && !String(inputs.adminAddress || '').trim()) {\n throw new Error('adminAddress (entity admin account) is required to grant the engine evaluator rights for on-chain decisions.');\n }\n // Stage 1 — CHECK THE RULES. Nothing irreversible: no delegation minted, nothing deposited,\n // no collection registered, no on-chain grant signed. The engine pre-check inside this stage\n // MAY still raise a UCAN-signing PIN prompt of its own — see the header comment's \"PIN\n // prompts, honestly\" section, that is a separate, known, open item, not something this\n // comment claims away. `intendedSettings` mirrors the EXACT coercion `runEvalRegister` applies\n // below (default true, `!== false` opt-out, image checks nested under AI checks) — and the\n // same shape `EvalEngineFlowDetail`'s `intendedSettings` passes at authoring time — so the\n // pre-check judges these rules against what stage 2 is actually about to register, not a\n // stale or guessed settings row.\n const intendedSettings = {\n allowAiChecks: inputs.allowAiChecks !== false,\n allowImageChecks: inputs.allowAiChecks !== false && inputs.allowImageChecks !== false,\n allowChainEvaluation: inputs.allowChainEvaluation !== false,\n };\n const preflight = await preflightEvalRubric(inputs, ctx, intendedSettings);\n // Stage 2 — ENROL. Throws on any failure; the rules already passed, so a failure here is an\n // enrolment problem, never a rules problem. NOTE: no `rubricId` input is forwarded to register\n // (the merged block has none) — the pin happens in stage 3, after the anchor lands.\n const registered = await runEvalRegister(inputs, ctx);\n // Stage 3 — PUBLISH THE RULES. Uses the preflight's result verbatim, never re-validated or\n // re-read from inputs — what gets anchored is exactly what was checked in stage 1.\n const published = await publishEvalRubric(preflight, ctx);\n return { output: { ...registered.output, ...published.output } };\n },\n});\n","import { registerAction } from '../registry';\n\n/**\n * qi/kyc.verify — complete an identity (KYC) verification inside a flow.\n *\n * The KYC lifecycle is driven by an external KYC server that the editor never\n * calls directly — the host exposes it through the `kyc` service group\n * (`kycLoadForm` / `kycInitiate` / `kycGetVerificationUrl` / `kycGetStatus` /\n * `kycSaveCredential` handlers). The server's status is the single source of\n * truth: `verify → review → clear → issuing → issued → complete`, failure\n * states `rejected|attention|error`, plus `unknown`.\n *\n * Everything BEFORE the final save (form load, initiate, hosted-webview open,\n * 15s status polling) is done by the FlowDetail calling the host handlers\n * directly — the same handler-direct pattern the payment action uses. This\n * `run()` executes ONCE, at the final save step: it re-checks the server\n * status, refuses to complete unless the credential is `issued` (or already\n * `complete`), then saves the SD-JWT credential to the user's Vault\n * (idempotent on the host side).\n *\n * PII boundary: the output carries NO personal data — only the credential CID\n * (the proof), credential type, protocol id, and terminal status.\n */\nregisterAction({\n type: 'qi/kyc.verify',\n can: 'kyc/verify',\n sideEffect: true,\n proof: { fields: ['credentialCid'] },\n done: {\n isDone: (state) => state.state === 'completed' && typeof state.output?.credentialCid === 'string' && state.output.credentialCid.length > 0,\n check: async ({ inputs, actionState, ctx }) => {\n const service = ctx.services?.kyc;\n const protocolDid = String(inputs.protocolDid || '').trim();\n if (!service || !protocolDid) {\n return {\n done: 'unknown',\n source: 'kyc.server',\n reason: 'KYC read service or protocol DID is unavailable.',\n };\n }\n try {\n const { status } = await service.getStatus({\n protocolId: protocolDid,\n });\n if (status !== 'issued' && status !== 'complete') {\n if (status === 'unknown') {\n return { done: 'unknown', source: 'kyc.server' };\n }\n return {\n done: false,\n source: 'kyc.server',\n reason: `KYC status is ${status}.`,\n };\n }\n let credentialCid = String(actionState.output?.credentialCid || inputs.credentialCid || '').trim();\n let credentialType = String(actionState.output?.credentialType || inputs.credentialType || 'kycamllevel1').trim();\n if (!credentialCid) {\n const form = await service.loadForm({\n protocolDid,\n credentialType,\n });\n const credential = form.existingCredentials?.find((entry) => entry.credentialType === credentialType);\n credentialCid = credential?.cid || '';\n credentialType = credential?.credentialType || credentialType;\n }\n if (!credentialCid) {\n return {\n done: false,\n source: 'kyc.server',\n reason: 'KYC is terminal but no matching credential is in the Vault.',\n };\n }\n return {\n done: true,\n source: 'kyc.server',\n output: {\n credentialCid,\n credentialType,\n protocolId: protocolDid,\n status: 'complete',\n },\n };\n } catch (error) {\n return {\n done: 'unknown',\n source: 'kyc.server',\n reason: error instanceof Error ? error.message : 'KYC status could not be read.',\n };\n }\n },\n },\n defaultRequiresConfirmation: false,\n cardinality: 'once',\n // Human-driven (details form + hosted webview) — never event-triggered,\n // same as the human input actions.\n eligibleForEventTrigger: false,\n inputSchema: {\n type: 'object',\n required: ['protocolDid'],\n properties: {\n protocolDid: { type: 'string', description: 'DID of the KYC protocol entity to verify against. The protocol determines the KYC level and check plan.' },\n credentialType: {\n type: 'string',\n description: \"Vault index key of the credential the protocol issues (e.g. 'kycamllevel1', 'kycamllevel2'). Defaults to level 1 when omitted.\",\n },\n credentialCid: {\n type: 'string',\n description: 'Runtime-selected CID of an existing Vault credential to use (set by the FlowDetail when the user picks one of several).',\n },\n },\n },\n outputSchema: [\n { path: 'credentialCid', displayName: 'Credential CID', type: 'string', description: 'CID of the SD-JWT credential saved to the Vault (proof of completion).' },\n { path: 'credentialType', displayName: 'Credential Type', type: 'string', description: 'Type of the issued credential.' },\n { path: 'protocolId', displayName: 'Protocol ID', type: 'string', description: 'The KYC protocol this verification ran against.' },\n { path: 'status', displayName: 'Status', type: 'string', description: \"Terminal lifecycle status — 'complete' once the credential is saved.\" },\n ],\n events: [\n {\n name: 'kyc.completed',\n displayName: 'KYC completed',\n description: 'Fires when the issued credential has been saved to the Vault and the verification is complete.',\n payloadSchema: [\n { path: 'credentialCid', displayName: 'Credential CID', type: 'string' },\n { path: 'credentialType', displayName: 'Credential Type', type: 'string' },\n { path: 'protocolId', displayName: 'Protocol ID', type: 'string' },\n { path: 'status', displayName: 'Status', type: 'string' },\n ],\n pendingDisplayFields: ['credentialType', 'status'],\n },\n ],\n run: async (inputs, ctx) => {\n if (!ctx.services.kyc) {\n throw new Error('kyc handlers not available');\n }\n if (!inputs.protocolDid) throw new Error('protocolDid is required');\n const credentialType = typeof inputs.credentialType === 'string' && inputs.credentialType.trim() ? inputs.credentialType.trim() : undefined;\n const credentialCid = typeof inputs.credentialCid === 'string' && inputs.credentialCid.trim() ? inputs.credentialCid.trim() : undefined;\n\n // Server status is the single source of truth — re-check it at save time\n // instead of trusting anything the UI polled earlier.\n const { status } = await ctx.services.kyc.getStatus({ protocolId: inputs.protocolDid });\n let eligible = status === 'issued' || status === 'complete';\n if (!eligible) {\n // The server archives evaluations after completion (and credentials can\n // be acquired via other apps), so an existing vault credential of the\n // expected type counts as complete even when the server has no live\n // evaluation.\n try {\n const form = await ctx.services.kyc.loadForm({ protocolDid: inputs.protocolDid, credentialType });\n eligible = !!form.hasExistingCredential;\n } catch (err) {\n console.warn('[kyc.verify] vault fallback check failed', err);\n }\n }\n if (!eligible) {\n throw new Error(`KYC verification not complete — current status: ${status}`);\n }\n\n // Idempotent on the host side: re-saving an already-saved credential of\n // this type returns the existing CID (safe for the \"already verified\"\n // path); `credentialCid` pins the user's selection when they hold several.\n const saved = await ctx.services.kyc.saveCredential({ protocolId: inputs.protocolDid, credentialType, credentialCid });\n if (!saved?.credentialCid) {\n throw new Error('kyc.saveCredential returned no credentialCid. Check the [kyc:saveCredential] handler logs.');\n }\n\n const output = {\n credentialCid: saved.credentialCid,\n credentialType: saved.credentialType,\n protocolId: inputs.protocolDid,\n status: 'complete',\n };\n\n return {\n output,\n events: [{ name: 'kyc.completed', payload: output }],\n };\n },\n});\n","/**\n * Shared plumbing for \"delegated integration\" action blocks (Gmail, Outlook,\n * Slack — and any future toolkit). These blocks run a third-party tool on the\n * TEMPLATE AUTHOR's connected account: the author connects once and binds it to\n * the template; any runner then executes it via an opaque, server-side binding,\n * never holding the author's credential.\n *\n * NB this is distinct from `qi/email.send`, which sends a pre-defined templated\n * email from the PLATFORM owner's address. Delegated blocks send free-form\n * messages from the author's OWN account.\n *\n * Schemas are hardcoded + typed per tool (see each tool's `*.types.ts`). Tool\n * fields are stored FLAT on the inputs object (not nested) so the flow engine's\n * top-level `{{block.output.field}}` reference resolution works on them, exactly\n * like the calendar block.\n */\n\nimport type { IntegrationToolSchema } from '@/mantine/context/BlocknoteContext';\nimport type { ActionContext, BoundConnection, IntegrationExecuteOutcome } from '../../types';\n\n/** Stored inputs: the bound connection + each tool field as a flat string. */\nexport type DelegatedToolInputs = {\n connection: BoundConnection | null;\n} & Record<string, unknown>;\n\nexport interface DelegatedToolExecution {\n data: Record<string, unknown>;\n providerInvocationReceipt?: NonNullable<IntegrationExecuteOutcome['providerInvocationReceipt']>;\n}\n\n/** Complete JSON Schema shared by Portal, agents, and external executors. */\nexport function delegatedToolInputSchema(schema: IntegrationToolSchema): object {\n return {\n type: 'object',\n required: ['connection', ...schema.parameters.required],\n additionalProperties: false,\n properties: {\n connection: {\n type: 'object',\n required: ['bindingId', 'connectedAccountId', 'toolkit'],\n additionalProperties: false,\n properties: {\n bindingId: { type: 'string', minLength: 1, description: 'Opaque, server-side delegated credential binding.' },\n connectedAccountId: { type: 'string' },\n toolkit: { type: 'string' },\n label: { type: ['string', 'null'] },\n },\n },\n ...schema.parameters.properties,\n },\n };\n}\n\nexport function parseBoundConnection(raw: unknown): BoundConnection | null {\n if (!raw || typeof raw !== 'object') return null;\n const c = raw as Record<string, unknown>;\n if (typeof c.bindingId !== 'string' || !c.bindingId) return null;\n if (typeof c.connectedAccountId !== 'string') return null;\n if (typeof c.toolkit !== 'string') return null;\n return {\n bindingId: c.bindingId,\n connectedAccountId: c.connectedAccountId,\n toolkit: c.toolkit,\n label: typeof c.label === 'string' ? c.label : null,\n };\n}\n\nexport function parseDelegatedToolInputs(raw: string | Record<string, unknown> | undefined): DelegatedToolInputs {\n let parsed: Record<string, unknown> = {};\n try {\n parsed = typeof raw === 'string' ? (JSON.parse(raw || '{}') as Record<string, unknown>) : raw || {};\n } catch {\n parsed = {};\n }\n return { ...parsed, connection: parseBoundConnection(parsed.connection) };\n}\n\nexport function serializeDelegatedToolInputs(inputs: DelegatedToolInputs): string {\n return JSON.stringify(inputs);\n}\n\n/** String value of a tool field on the inputs, or '' when unset. */\nexport function fieldValue(inputs: DelegatedToolInputs, name: string): string {\n const v = inputs[name];\n return typeof v === 'string' ? v : '';\n}\n\n/** A plain {field: stringValue} view of the inputs, excluding `connection`. */\nexport function fieldValues(inputs: DelegatedToolInputs): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(inputs)) {\n if (k === 'connection') continue;\n if (typeof v === 'string') out[k] = v;\n }\n return out;\n}\n\n/** Required schema fields that are missing/blank in `values`. */\nexport function missingRequired(schema: IntegrationToolSchema, values: Record<string, string>): string[] {\n return (schema.parameters.required || []).filter((name) => !(values[name] ?? '').trim());\n}\n\n/**\n * `getMissingInputs` for a delegated tool action: the bound connection plus\n * the tool schema's own required fields. Mirrors executeDelegatedTool's gates\n * so orchestrators can ask for inputs before execution instead of hitting the\n * run-time throw.\n */\nexport function delegatedToolMissingInputs(schema: IntegrationToolSchema, rawInputs: Record<string, unknown>): string[] {\n const parsed = parseDelegatedToolInputs(rawInputs);\n const missing: string[] = [];\n if (!parsed.connection?.bindingId) missing.push('connection');\n missing.push(...missingRequired(schema, fieldValues(parsed)));\n return missing;\n}\n\n/**\n * Coerce the flat string field values into the typed `arguments` object the\n * underlying tool expects, driven by the hardcoded schema:\n * boolean → true/false, array → split on comma/newline, number → Number.\n * Empty values are omitted so the tool falls back to its own defaults.\n */\nexport function coerceToolArgs(schema: IntegrationToolSchema, values: Record<string, string>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, prop] of Object.entries(schema.parameters.properties || {})) {\n const raw = values[name];\n if (typeof raw !== 'string' || raw.trim() === '') continue;\n const type = prop.type;\n if (type === 'boolean') {\n out[name] = raw === 'true';\n } else if (type === 'array') {\n out[name] = raw\n .split(/[\\n,]+/)\n .map((s) => s.trim())\n .filter(Boolean);\n } else if (type === 'number' || type === 'integer') {\n const n = Number(raw);\n if (!Number.isNaN(n)) out[name] = n;\n } else {\n out[name] = raw;\n }\n }\n return out;\n}\n\n/**\n * Execute a delegated tool via the runner's binding. Resolves to the tool's\n * `data` payload on success; throws a human-meaningful Error on failure (the\n * messages distinguish \"author must reconnect\" from \"binding removed\" so the\n * runner knows whether the fix is theirs or the author's).\n */\nexport async function executeDelegatedTool(\n ctx: ActionContext,\n opts: {\n connection: BoundConnection | null;\n schema: IntegrationToolSchema;\n toolSlug: string;\n values: Record<string, string>;\n toolkitLabel: string;\n }\n): Promise<DelegatedToolExecution> {\n const svc = ctx.services.integrations;\n if (!svc?.executeBinding) {\n throw new Error(`${opts.toolkitLabel} integration is not configured.`);\n }\n const bindingId = opts.connection?.bindingId;\n if (!bindingId) {\n throw new Error(`No ${opts.toolkitLabel} account is bound. The template author must connect and bind ${opts.toolkitLabel}.`);\n }\n\n const missing = missingRequired(opts.schema, opts.values);\n if (missing.length > 0) {\n throw new Error(`Missing required field${missing.length === 1 ? '' : 's'}: ${missing.join(', ')}`);\n }\n\n const args = coerceToolArgs(opts.schema, opts.values);\n const result = await svc.executeBinding({ bindingId, toolSlug: opts.toolSlug, arguments: args });\n\n if (!result.successful) {\n if (result.code === 'AUTH_EXPIRED') {\n throw new Error(`The template author's ${opts.toolkitLabel} access expired — they need to reconnect it in the template.`);\n }\n if (result.code === 'UPSTREAM_4XX' && /not found|removed/i.test(result.error || '')) {\n throw new Error(`This ${opts.toolkitLabel} integration was removed by the template author.`);\n }\n throw new Error(result.error || `${opts.toolkitLabel} action failed.`);\n }\n\n return {\n data: (result.data as Record<string, unknown>) ?? {},\n providerInvocationReceipt: result.providerInvocationReceipt,\n };\n}\n","import type { IntegrationToolSchema } from '@/mantine/context/BlocknoteContext';\nimport type { OutputSchemaField } from '../../types';\n\n/**\n * Hardcoded, verified schema for Gmail's send-email tool (GMAIL_SEND_EMAIL).\n * Verified live against the Composio v3 tool schema on 2026-06-30. This is the\n * single source of truth: it drives the config form, the runner form, argument\n * coercion in run(), and the agent-facing action metadata. Field names mirror\n * the tool verbatim — no translation layer.\n *\n * Curated subset of the tool's parameters (the full tool also exposes\n * `attachment`, `extra_recipients`, etc. which we intentionally don't surface).\n */\n\nexport const GMAIL_SEND_SLUG = 'GMAIL_SEND_EMAIL';\nexport const GMAIL_SENT_EVENT = 'email.sent';\n\nexport const GMAIL_SEND_SCHEMA: IntegrationToolSchema = {\n slug: GMAIL_SEND_SLUG,\n name: 'Send Email',\n description: \"Send an email from the template author's Gmail account.\",\n parameters: {\n type: 'object',\n required: ['recipient_email', 'body'],\n properties: {\n recipient_email: { type: 'string', title: 'To', description: \"Recipient's email address.\" },\n subject: { type: 'string', title: 'Subject' },\n body: { type: 'string', title: 'Body', description: 'Email body. Plain text unless \"HTML body\" is set.' },\n cc: { type: 'array', title: 'Cc', description: 'Comma-separated email addresses.' },\n bcc: { type: 'array', title: 'Bcc', description: 'Comma-separated email addresses.' },\n is_html: { type: 'boolean', title: 'HTML body', description: 'Render the body as HTML.' },\n },\n },\n};\n\nexport const GMAIL_SEND_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'messageId', displayName: 'Message ID', type: 'string', description: 'Gmail id of the sent message' },\n { path: 'threadId', displayName: 'Thread ID', type: 'string' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'ISO timestamp when sent' },\n { path: 'providerReceiptId', displayName: 'Provider Receipt ID', type: 'string', description: 'Signed integration-host invocation receipt identifier' },\n { path: 'providerInvocationReceipt', displayName: 'Provider Receipt', type: 'object', description: 'Signed integration-host invocation receipt' },\n];\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport {\n delegatedToolInputSchema,\n delegatedToolMissingInputs,\n executeDelegatedTool,\n fieldValues,\n parseDelegatedToolInputs,\n type DelegatedToolInputs,\n} from '../_shared/delegatedTool';\nimport { GMAIL_SEND_OUTPUT_SCHEMA, GMAIL_SEND_SCHEMA, GMAIL_SEND_SLUG, GMAIL_SENT_EVENT } from './emailSend.types';\n\n/**\n * Send an email from the TEMPLATE AUTHOR's connected Gmail account (delegated).\n * The author binds their account once; any runner sends as them via an opaque\n * server-side binding — runners never hold the credential.\n *\n * Distinct from `qi/email.send`, which sends a templated email from the\n * platform owner's address. This one is free-form, from the author's own inbox.\n */\nregisterAction<DelegatedToolInputs>({\n type: 'qi/gmail.email.send',\n can: 'gmail.email/send',\n sideEffect: true,\n // Proof of execution: Gmail returns the sent message id. Matches qi/email.send.\n proof: { fields: ['messageId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n // Can be wired to another block's event (e.g. form submitted → send email).\n eligibleForEventTrigger: true,\n inputSchema: delegatedToolInputSchema(GMAIL_SEND_SCHEMA),\n\n // Mirrors executeDelegatedTool's gates: the bound connection plus the\n // tool schema's required fields, so orchestrators ask before run() throws.\n getMissingInputs: (inputs) => delegatedToolMissingInputs(GMAIL_SEND_SCHEMA, inputs),\n\n outputSchema: GMAIL_SEND_OUTPUT_SCHEMA,\n\n events: [\n {\n name: GMAIL_SENT_EVENT,\n displayName: 'Email sent',\n description: 'Fired after the email is sent from the author’s Gmail.',\n payloadSchema: [\n { path: 'messageId', displayName: 'Message ID', type: 'string' },\n { path: 'recipient_email', displayName: 'To', type: 'string' },\n ],\n pendingDisplayFields: ['messageId'],\n },\n ],\n\n run: async (inputs, ctx) => {\n const parsed = parseDelegatedToolInputs(inputs as unknown as Record<string, unknown>);\n const values = fieldValues(parsed);\n\n const execution = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: GMAIL_SEND_SCHEMA,\n toolSlug: GMAIL_SEND_SLUG,\n values,\n toolkitLabel: 'Gmail',\n });\n const { data, providerInvocationReceipt } = execution;\n\n // Composio wraps tool output under data.response_data for most tools.\n const envelope = (data.response_data as Record<string, unknown>) ?? data;\n const messageId = String(envelope.id ?? envelope.messageId ?? '');\n const threadId = String(envelope.threadId ?? '');\n\n return {\n output: {\n messageId,\n threadId,\n sentAt: new Date().toISOString(),\n providerReceiptId: providerInvocationReceipt?.id || '',\n providerInvocationReceipt,\n },\n events: messageId ? [{ name: GMAIL_SENT_EVENT, payload: { messageId, recipient_email: values.recipient_email ?? '' } }] : undefined,\n };\n },\n});\n","import type { IntegrationToolSchema } from '@/mantine/context/BlocknoteContext';\nimport type { OutputSchemaField } from '../../types';\n\n/**\n * Hardcoded, verified schema for Outlook's send-email tool\n * (OUTLOOK_OUTLOOK_SEND_EMAIL). Verified live against the Composio v3 tool\n * schema on 2026-06-30. Single source of truth for form + coercion + metadata.\n * Note the doubled `OUTLOOK_OUTLOOK_` prefix — that is the real Composio slug.\n */\n\nexport const OUTLOOK_SEND_SLUG = 'OUTLOOK_OUTLOOK_SEND_EMAIL';\nexport const OUTLOOK_SENT_EVENT = 'email.sent';\n\nexport const OUTLOOK_SEND_SCHEMA: IntegrationToolSchema = {\n slug: OUTLOOK_SEND_SLUG,\n name: 'Send Email',\n description: \"Send an email from the template author's Outlook account.\",\n parameters: {\n type: 'object',\n required: ['subject', 'body', 'to_email'],\n properties: {\n to_email: { type: 'string', title: 'To', description: \"Recipient's email address.\" },\n to_name: { type: 'string', title: 'To name', description: 'Optional display name for the recipient.' },\n subject: { type: 'string', title: 'Subject' },\n body: { type: 'string', title: 'Body', description: 'Email body. Plain text unless \"HTML body\" is set.' },\n cc_emails: { type: 'array', title: 'Cc', description: 'Comma-separated email addresses.' },\n bcc_emails: { type: 'array', title: 'Bcc', description: 'Comma-separated email addresses.' },\n is_html: { type: 'boolean', title: 'HTML body', description: 'Render the body as HTML.' },\n },\n },\n};\n\nexport const OUTLOOK_SEND_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'messageId', displayName: 'Message ID', type: 'string' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'ISO timestamp when sent' },\n { path: 'providerReceiptId', displayName: 'Provider Receipt ID', type: 'string', description: 'Required signed proof when Outlook returns no message id' },\n { path: 'providerInvocationReceipt', displayName: 'Provider Receipt', type: 'object', description: 'Signed integration-host invocation receipt' },\n];\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport {\n delegatedToolInputSchema,\n delegatedToolMissingInputs,\n executeDelegatedTool,\n fieldValues,\n parseDelegatedToolInputs,\n type DelegatedToolInputs,\n} from '../_shared/delegatedTool';\nimport { OUTLOOK_SEND_OUTPUT_SCHEMA, OUTLOOK_SEND_SCHEMA, OUTLOOK_SEND_SLUG, OUTLOOK_SENT_EVENT } from './emailSend.types';\n\n/**\n * Send an email from the TEMPLATE AUTHOR's connected Outlook account (delegated).\n * The author binds their account once; any runner sends as them via an opaque\n * server-side binding — runners never hold the credential.\n *\n * Distinct from `qi/email.send`, which sends a templated email from the\n * platform owner's address. This one is free-form, from the author's own inbox.\n */\nregisterAction<DelegatedToolInputs>({\n type: 'qi/outlook.email.send',\n can: 'outlook.email/send',\n sideEffect: true,\n // Outlook often returns no message id. The integration host must therefore\n // return a signed provider invocation receipt for proof of the side effect.\n proof: { fields: ['messageId', 'providerReceiptId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n // Can be wired to another block's event (e.g. form submitted → send email).\n eligibleForEventTrigger: true,\n inputSchema: delegatedToolInputSchema(OUTLOOK_SEND_SCHEMA),\n\n // Mirrors executeDelegatedTool's gates: the bound connection plus the\n // tool schema's required fields, so orchestrators ask before run() throws.\n getMissingInputs: (inputs) => delegatedToolMissingInputs(OUTLOOK_SEND_SCHEMA, inputs),\n\n outputSchema: OUTLOOK_SEND_OUTPUT_SCHEMA,\n\n events: [\n {\n name: OUTLOOK_SENT_EVENT,\n displayName: 'Email sent',\n description: 'Fired after the email is sent from the author’s Outlook.',\n payloadSchema: [\n { path: 'messageId', displayName: 'Message ID', type: 'string' },\n { path: 'to_email', displayName: 'To', type: 'string' },\n ],\n pendingDisplayFields: ['messageId'],\n },\n ],\n\n run: async (inputs, ctx) => {\n const parsed = parseDelegatedToolInputs(inputs as unknown as Record<string, unknown>);\n const values = fieldValues(parsed);\n\n const execution = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: OUTLOOK_SEND_SCHEMA,\n toolSlug: OUTLOOK_SEND_SLUG,\n values,\n toolkitLabel: 'Outlook',\n });\n const { data, providerInvocationReceipt } = execution;\n\n // Composio wraps tool output under data.response_data for most tools.\n // Outlook's send tool may not return a message id; map defensively.\n const envelope = (data.response_data as Record<string, unknown>) ?? data;\n const messageId = String(envelope.id ?? envelope.messageId ?? '');\n if (!messageId && !providerInvocationReceipt?.id) {\n throw new Error('Outlook returned no message id and the integration host returned no signed provider invocation receipt.');\n }\n\n return {\n output: {\n messageId,\n sentAt: new Date().toISOString(),\n providerReceiptId: providerInvocationReceipt?.id || '',\n providerInvocationReceipt,\n },\n // Outlook often returns no id, so emit unconditionally.\n events: [{ name: OUTLOOK_SENT_EVENT, payload: { messageId, to_email: values.to_email ?? '' } }],\n };\n },\n});\n","import type { IntegrationToolSchema } from '@/mantine/context/BlocknoteContext';\nimport type { OutputSchemaField } from '../../types';\n\n/**\n * Hardcoded, verified schema for Slack's post-message tool\n * (SLACK_CHAT_POST_MESSAGE). Verified live against the Composio v3 tool schema\n * on 2026-06-30. This is the single source of truth: it drives the config form,\n * the runner form, argument coercion in run(), and the agent-facing action\n * metadata. Field names mirror the tool verbatim — no translation layer.\n */\n\nexport const SLACK_SEND_SLUG = 'SLACK_CHAT_POST_MESSAGE';\nexport const SLACK_SENT_EVENT = 'message.sent';\n\nexport const SLACK_SEND_SCHEMA: IntegrationToolSchema = {\n slug: SLACK_SEND_SLUG,\n name: 'Post Message',\n description: \"Post a message to a Slack channel from the template author's Slack account.\",\n parameters: {\n type: 'object',\n required: ['channel'],\n properties: {\n channel: { type: 'string', title: 'Channel', description: 'Channel ID or name, e.g. #general or C0123456.' },\n markdown_text: {\n type: 'string',\n title: 'Message',\n description: 'Message text in Slack markdown. Preferred over the deprecated plain text field.',\n },\n thread_ts: { type: 'string', title: 'Thread', description: 'Optional parent message timestamp to reply within a thread.' },\n },\n },\n};\n\nexport const SLACK_SEND_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'messageTs', displayName: 'Message ts', type: 'string' },\n { path: 'channel', displayName: 'Channel', type: 'string' },\n { path: 'sentAt', displayName: 'Sent At', type: 'string', description: 'ISO timestamp when sent' },\n { path: 'providerReceiptId', displayName: 'Provider Receipt ID', type: 'string', description: 'Signed integration-host invocation receipt identifier' },\n { path: 'providerInvocationReceipt', displayName: 'Provider Receipt', type: 'object', description: 'Signed integration-host invocation receipt' },\n];\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport {\n delegatedToolInputSchema,\n delegatedToolMissingInputs,\n executeDelegatedTool,\n fieldValues,\n parseDelegatedToolInputs,\n type DelegatedToolInputs,\n} from '../_shared/delegatedTool';\nimport { SLACK_SEND_OUTPUT_SCHEMA, SLACK_SEND_SCHEMA, SLACK_SEND_SLUG, SLACK_SENT_EVENT } from './messageSend.types';\n\n/**\n * Post a message to Slack from the TEMPLATE AUTHOR's connected Slack account\n * (delegated). The author binds their account once; any runner posts as them\n * via an opaque server-side binding — runners never hold the credential.\n *\n * Distinct from `qi/email.send`, which sends a templated email from the\n * platform owner's address. This one is free-form, from the author's own\n * Slack workspace.\n */\nregisterAction<DelegatedToolInputs>({\n type: 'qi/slack.message.send',\n can: 'slack.message/send',\n sideEffect: true,\n // Proof of execution: Slack returns the posted message timestamp (ts).\n proof: { fields: ['messageTs'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n // Can be wired to another block's event (e.g. form submitted → post message).\n eligibleForEventTrigger: true,\n inputSchema: delegatedToolInputSchema(SLACK_SEND_SCHEMA),\n\n // Mirrors executeDelegatedTool's gates: the bound connection plus the\n // tool schema's required fields, so orchestrators ask before run() throws.\n getMissingInputs: (inputs) => delegatedToolMissingInputs(SLACK_SEND_SCHEMA, inputs),\n\n outputSchema: SLACK_SEND_OUTPUT_SCHEMA,\n\n events: [\n {\n name: SLACK_SENT_EVENT,\n displayName: 'Message posted',\n description: 'Fired after the message is posted to Slack.',\n payloadSchema: [\n { path: 'messageTs', displayName: 'Message ts', type: 'string' },\n { path: 'channel', displayName: 'Channel', type: 'string' },\n ],\n pendingDisplayFields: ['messageTs'],\n },\n ],\n\n run: async (inputs, ctx) => {\n const parsed = parseDelegatedToolInputs(inputs as unknown as Record<string, unknown>);\n const values = fieldValues(parsed);\n\n const execution = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: SLACK_SEND_SCHEMA,\n toolSlug: SLACK_SEND_SLUG,\n values,\n toolkitLabel: 'Slack',\n });\n const { data, providerInvocationReceipt } = execution;\n\n // Composio wraps tool output under data.response_data for most tools.\n const envelope = (data.response_data as Record<string, unknown>) ?? data;\n const messageTs = String(envelope.ts ?? '');\n const channel = String(envelope.channel ?? values.channel ?? '');\n\n return {\n output: {\n messageTs,\n channel,\n sentAt: new Date().toISOString(),\n providerReceiptId: providerInvocationReceipt?.id || '',\n providerInvocationReceipt,\n },\n events: messageTs ? [{ name: SLACK_SENT_EVENT, payload: { messageTs, channel } }] : undefined,\n };\n },\n});\n","import type { IntegrationToolSchema } from '@/mantine/context/BlocknoteContext';\nimport type { OutputSchemaField } from '../../types';\n\n/**\n * Hardcoded, verified schema for Google Calendar's create-event tool\n * (GOOGLECALENDAR_CREATE_EVENT). Verified live against the Composio v3 tool\n * schema on 2026-06-30. Single source of truth for form + coercion + metadata.\n *\n * This is the DELEGATED variant: the event is created on the template author's\n * connected calendar. (Distinct from the older self-connected\n * `qi/calendar.event.create`, where each runner connects their own calendar.)\n */\n\nexport const GOOGLECALENDAR_CREATE_SLUG = 'GOOGLECALENDAR_CREATE_EVENT';\nexport const GOOGLECALENDAR_CREATED_EVENT = 'event.created';\n\nexport const GOOGLECALENDAR_CREATE_SCHEMA: IntegrationToolSchema = {\n slug: GOOGLECALENDAR_CREATE_SLUG,\n name: 'Create Event',\n description: \"Create an event on the template author's Google Calendar.\",\n parameters: {\n type: 'object',\n required: ['start_datetime'],\n properties: {\n start_datetime: { type: 'string', title: 'Start time', description: 'ISO 8601, e.g. 2026-05-12T09:00:00.' },\n summary: { type: 'string', title: 'Title' },\n description: { type: 'string', title: 'Description' },\n location: { type: 'string', title: 'Location' },\n timezone: { type: 'string', title: 'Timezone', description: 'IANA name, e.g. Europe/London.' },\n attendees: { type: 'array', title: 'Attendees', description: 'Comma-separated email addresses.' },\n calendar_id: { type: 'string', title: 'Calendar', description: \"Use 'primary' for the author's main calendar.\" },\n event_duration_minutes: { type: 'number', title: 'Duration (minutes)', description: 'Defaults to the calendar default if blank.' },\n },\n },\n};\n\nexport const GOOGLECALENDAR_CREATE_OUTPUT_SCHEMA: OutputSchemaField[] = [\n { path: 'eventId', displayName: 'Event ID', type: 'string' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n { path: 'startIso', displayName: 'Start', type: 'string' },\n { path: 'providerReceiptId', displayName: 'Provider Receipt ID', type: 'string', description: 'Signed integration-host invocation receipt identifier' },\n { path: 'providerInvocationReceipt', displayName: 'Provider Receipt', type: 'object', description: 'Signed integration-host invocation receipt' },\n];\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport {\n delegatedToolInputSchema,\n delegatedToolMissingInputs,\n executeDelegatedTool,\n fieldValues,\n parseDelegatedToolInputs,\n type DelegatedToolInputs,\n} from '../_shared/delegatedTool';\nimport { GOOGLECALENDAR_CREATE_OUTPUT_SCHEMA, GOOGLECALENDAR_CREATE_SCHEMA, GOOGLECALENDAR_CREATE_SLUG, GOOGLECALENDAR_CREATED_EVENT } from './eventCreate.types';\n\n/**\n * Create an event on the TEMPLATE AUTHOR's connected Google Calendar\n * (delegated). The author binds their calendar once; any runner creates events\n * on it via an opaque server-side binding — runners never hold the credential.\n *\n * Distinct from `qi/calendar.event.create` (the older self-connected block,\n * where each runner connects their own calendar).\n */\nregisterAction<DelegatedToolInputs>({\n type: 'qi/googlecalendar.event.create',\n can: 'googlecalendar.event/create',\n sideEffect: true,\n // Proof of execution: the created event's id. Matches qi/calendar.event.create.\n proof: { fields: ['eventId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: delegatedToolInputSchema(GOOGLECALENDAR_CREATE_SCHEMA),\n\n // Mirrors executeDelegatedTool's gates: the bound connection plus the\n // tool schema's required fields, so orchestrators ask before run() throws.\n getMissingInputs: (inputs) => delegatedToolMissingInputs(GOOGLECALENDAR_CREATE_SCHEMA, inputs),\n\n outputSchema: GOOGLECALENDAR_CREATE_OUTPUT_SCHEMA,\n\n events: [\n {\n name: GOOGLECALENDAR_CREATED_EVENT,\n displayName: 'Calendar event created',\n description: 'Fired after the event is created on the author’s calendar.',\n payloadSchema: [\n { path: 'eventId', displayName: 'Event ID', type: 'string' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n ],\n pendingDisplayFields: ['summary', 'eventId'],\n },\n ],\n\n run: async (inputs, ctx) => {\n const parsed = parseDelegatedToolInputs(inputs as unknown as Record<string, unknown>);\n const values = fieldValues(parsed);\n\n const execution = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: GOOGLECALENDAR_CREATE_SCHEMA,\n toolSlug: GOOGLECALENDAR_CREATE_SLUG,\n values,\n toolkitLabel: 'Google Calendar',\n });\n const { data, providerInvocationReceipt } = execution;\n\n const envelope = (data.response_data as Record<string, unknown>) ?? data;\n const eventId = String(envelope.id ?? '');\n const htmlLink = String(envelope.htmlLink ?? '');\n const summary = String(envelope.summary ?? values.summary ?? '');\n const start = envelope.start as Record<string, unknown> | undefined;\n const startIso = String(start?.dateTime ?? start?.date ?? values.start_datetime ?? '');\n\n return {\n output: { eventId, htmlLink, summary, startIso, providerReceiptId: providerInvocationReceipt?.id || '', providerInvocationReceipt },\n events: eventId ? [{ name: GOOGLECALENDAR_CREATED_EVENT, payload: { eventId, htmlLink, summary } }] : undefined,\n };\n },\n});\n","import { sha256Digest } from '../digest';\nimport { generateActionManifest } from '../manifest';\nimport { doneWhenCompleted, getAction, registerAction } from '../registry';\nimport { getTopicSemanticRecordDefinitions } from '../topicSemanticRecords';\nimport type { ActionContext, ActionDefinition, TopicActionBaseKind, TopicActionMetadata, TopicActionRecord } from '../types';\n\nconst ALL_KINDS: TopicActionBaseKind[] = ['task', 'agent_task', 'proposal', 'evaluation', 'claims', 'question', 'discussion', 'incident'];\n\nfunction topicMetadata(\n supportedBaseKinds: TopicActionBaseKind[],\n permittedTopicRecordTypes: string[],\n requiredTopicAbilities: string[],\n relevance: TopicActionMetadata['relevance'] = 'recommended',\n sensitiveInputPaths: string[] = [],\n sensitiveOutputPaths: string[] = []\n): TopicActionMetadata {\n const semanticRecordTypes = getTopicSemanticRecordDefinitions(permittedTopicRecordTypes);\n if (semanticRecordTypes.length !== permittedTopicRecordTypes.length) {\n throw new Error(`Topic Action metadata names a semantic record type without a complete definition`);\n }\n return {\n supportedBaseKinds,\n relevance,\n writeBackMode: permittedTopicRecordTypes.length > 0 ? 'semantic-record' : 'receipt-only',\n semanticRecordTypes,\n permittedTopicRecordTypes: semanticRecordTypes.map((definition) => definition.type),\n lifecycleEffect: 'none',\n requiredTopicAbilities,\n redactionPolicy: { mode: 'paths', sensitiveInputPaths, sensitiveOutputPaths },\n };\n}\n\nfunction requiredString(value: unknown, name: string): string {\n const normalized = String(value || '').trim();\n if (!normalized) throw new Error(`${name} is required`);\n return normalized;\n}\n\nfunction requiredArray(value: unknown, name: string): string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) throw new Error(`${name} must be an array of strings`);\n return value.map(String);\n}\n\nfunction topicContext(ctx: ActionContext): NonNullable<ActionContext['topic']> {\n if (!ctx.topic) throw new Error('This Action requires a revision-bound Topic execution context');\n return ctx.topic;\n}\n\nfunction topicService(ctx: ActionContext): NonNullable<ActionContext['services']['topic']> {\n topicContext(ctx);\n if (!ctx.services.topic) throw new Error('The host did not grant the capability-checked Topic service');\n return ctx.services.topic;\n}\n\nfunction idempotencyKey(actionType: string, inputs: Record<string, unknown>, ctx: ActionContext): string {\n const explicit = String(inputs.idempotencyKey || '').trim();\n if (explicit) return explicit;\n const topic = topicContext(ctx);\n return sha256Digest({ actionType, topicId: topic.topicId, topicRevision: topic.topicRevision, requestId: topic.requestId, inputs });\n}\n\nfunction semanticRecord(type: string, value: Record<string, unknown>, ctx: ActionContext): { record: TopicActionRecord; digest: string } {\n const topic = topicContext(ctx);\n const digest = sha256Digest(value);\n return {\n digest,\n record: {\n type,\n id: sha256Digest({ type, topicId: topic.topicId, requestId: topic.requestId, digest }),\n version: 1,\n value,\n evidenceReferences: Array.isArray(value.evidenceReferences) ? (value.evidenceReferences as string[]) : undefined,\n },\n };\n}\n\ninterface TopicOperationSpec {\n type: string;\n can: string;\n operationType: string;\n inputSchema: object;\n confirmation?: boolean;\n owner?: 'agent' | 'human';\n ability: string;\n kinds?: TopicActionBaseKind[];\n hidden?: boolean;\n buildPayload: (inputs: Record<string, unknown>, ctx: ActionContext) => Promise<Record<string, unknown>> | Record<string, unknown>;\n}\n\nfunction registerTopicOperation(spec: TopicOperationSpec): void {\n registerAction({\n type: spec.type,\n can: spec.can,\n sideEffect: true,\n proof: { fields: ['operationId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: spec.confirmation === true,\n requiredCapability: 'flow/block/execute',\n executionOwner: spec.owner || 'agent',\n hiddenFromAuthoring: spec.hidden,\n riskTier: spec.confirmation ? 'high' : 'medium',\n requiredServices: ['topic'],\n topic: topicMetadata(spec.kinds || ALL_KINDS, [], [spec.ability]),\n inputSchema: spec.inputSchema,\n outputSchema: [\n { path: 'operationId', displayName: 'Topic operation ID', type: 'string' },\n { path: 'topicRevision', displayName: 'Topic revision', type: 'string' },\n { path: 'proofReference', displayName: 'Operation proof', type: 'string' },\n ],\n run: async (inputs, ctx) => {\n const service = topicService(ctx);\n const payload = await spec.buildPayload(inputs, ctx);\n return {\n output: await service.appendOperation({\n context: topicContext(ctx),\n actorDid: ctx.actorDid,\n operationType: spec.operationType,\n payload,\n idempotencyKey: idempotencyKey(spec.type, inputs, ctx),\n }),\n };\n },\n });\n}\n\nregisterTopicOperation({\n type: 'qi/topic.flow.bind',\n can: 'topic/flow.bind',\n operationType: 'bind-flow',\n confirmation: true,\n owner: 'human',\n ability: 'topic/bind-flow',\n inputSchema: {\n type: 'object',\n required: ['flowUri', 'flowRevision', 'flowDigest', 'actionManifestDigest', 'controllerDid', 'role', 'startPolicy', 'triggerPolicy', 'receiptPolicy'],\n additionalProperties: false,\n properties: {\n bindingId: { type: 'string' },\n flowUri: { type: 'string' },\n flowRevision: { type: 'string' },\n flowDigest: { type: 'string', pattern: '^sha256:' },\n actionManifestDigest: { type: 'string', pattern: '^sha256:' },\n controllerDid: { type: 'string', pattern: '^did:' },\n role: { type: 'string', enum: ['primary', 'supporting'] },\n startPolicy: { type: 'string', enum: ['manual', 'on-topic-active', 'scheduled', 'event'] },\n triggerPolicy: { type: 'object' },\n receiptPolicy: { type: 'string', enum: ['all', 'terminal'] },\n capabilityReferences: { type: 'array', minItems: 2, uniqueItems: true, items: { type: 'string' } },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs, ctx) => {\n const topic = topicContext(ctx);\n return {\n binding: {\n version: 1,\n bindingId: String(inputs.bindingId || sha256Digest({ topicId: topic.topicId, flowUri: inputs.flowUri, flowRevision: inputs.flowRevision })),\n topicId: topic.topicId,\n flowUri: requiredString(inputs.flowUri, 'flowUri'),\n flowRevision: requiredString(inputs.flowRevision, 'flowRevision'),\n flowDigest: requiredString(inputs.flowDigest, 'flowDigest'),\n actionManifestDigest: requiredString(inputs.actionManifestDigest, 'actionManifestDigest'),\n controllerDid: requiredString(inputs.controllerDid, 'controllerDid'),\n role: requiredString(inputs.role, 'role'),\n startPolicy: requiredString(inputs.startPolicy, 'startPolicy'),\n triggerPolicy: inputs.triggerPolicy || {},\n receiptPolicy: requiredString(inputs.receiptPolicy, 'receiptPolicy'),\n status: 'active',\n capability: topic.topicCapabilityReference,\n capabilityReferences: Array.isArray(inputs.capabilityReferences) ? inputs.capabilityReferences.map(String) : [],\n createdBy: ctx.actorDid,\n createdAt: new Date().toISOString(),\n },\n };\n },\n});\n\nregisterTopicOperation({\n type: 'qi/topic.flow.unbind',\n can: 'topic/flow.unbind',\n operationType: 'unbind-flow',\n confirmation: true,\n owner: 'human',\n ability: 'topic/bind-flow',\n inputSchema: {\n type: 'object',\n required: ['bindingId'],\n additionalProperties: false,\n properties: { bindingId: { type: 'string' }, reason: { type: 'string' }, idempotencyKey: { type: 'string' } },\n },\n buildPayload: (inputs) => ({ bindingId: requiredString(inputs.bindingId, 'bindingId'), reason: String(inputs.reason || '') }),\n});\n\nregisterTopicOperation({\n type: 'qi/topic.action.request',\n can: 'topic/action.request',\n operationType: 'request-action',\n ability: 'topic/request-action',\n inputSchema: {\n type: 'object',\n required: ['actionType', 'actionContractDigest', 'inputDigest'],\n additionalProperties: false,\n properties: {\n actionType: { type: 'string' },\n actionContractDigest: { type: 'string', pattern: '^sha256:' },\n inputDigest: { type: 'string', pattern: '^sha256:' },\n inputReference: { type: 'string' },\n requestId: { type: 'string' },\n safeInputSummary: { type: 'object' },\n executorPreference: { type: 'string', enum: ['qi-flow', 'qiforge', 'mcp'] },\n bindingId: { type: 'string' },\n confirmationPolicy: { type: 'string', enum: ['inherit', 'required'] },\n transitionCode: { type: 'string' },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs, ctx) => {\n const actionType = requiredString(inputs.actionType, 'actionType');\n if (actionType === 'qi/topic.action.request') throw new Error('A Topic Action request cannot recursively request itself');\n const target = getAction(actionType);\n if (!target) throw new Error(`Unknown Action type '${actionType}'`);\n const manifestEntry = generateActionManifest().actions.find((entry) => entry.type === target.type);\n const suppliedDigest = requiredString(inputs.actionContractDigest, 'actionContractDigest');\n if (!manifestEntry || manifestEntry.contractDigest !== suppliedDigest) throw new Error('Action contract digest does not match the live registry');\n const kind = topicContext(ctx).kind;\n const baseKind = kind.source === 'standard' ? kind.kind : kind.baseKind;\n if (!target.topic?.supportedBaseKinds.includes(baseKind)) throw new Error(`Action '${actionType}' does not support Topic base Kind '${baseKind}'`);\n const topic = topicContext(ctx);\n const inputDigest = requiredString(inputs.inputDigest, 'inputDigest');\n // The requested Action is a NEW request, not this one. Reusing `topic.requestId`\n // collides with the row this execution already owns in the Topic projection, so\n // `requestAction` rejects it as a duplicate every time. Derive a distinct id\n // instead — deterministically, so a replay of this Action dedupes to the same\n // request rather than queueing a second copy of the same work.\n const derived = (purpose: string) => sha256Digest({ purpose, parentRequestId: topic.requestId, topicId: topic.topicId, actionType: target.type, inputDigest });\n return {\n ...(inputs.transitionCode ? { transitionCode: String(inputs.transitionCode) } : {}),\n request: {\n version: 1,\n requestId: String(inputs.requestId || derived('topic-action-request')),\n topicId: topic.topicId,\n topicRevision: topic.topicRevision,\n actionType: target.type,\n actionContractDigest: suppliedDigest,\n executor: inputs.executorPreference || 'qi-flow',\n inputs: { digest: inputDigest, ...(inputs.inputReference ? { ref: String(inputs.inputReference) } : {}) },\n requestedBy: ctx.actorDid,\n requestedAt: new Date().toISOString(),\n idempotencyKey: String(inputs.idempotencyKey || derived('topic-action-idempotency')),\n confirmation: target.defaultRequiresConfirmation || inputs.confirmationPolicy === 'required' ? 'required' : topic.confirmationReference ? 'confirmed' : 'not-required',\n ...(inputs.bindingId ? { flowBindingId: String(inputs.bindingId) } : {}),\n capability: topic.topicCapabilityReference,\n },\n };\n },\n});\n\nregisterTopicOperation({\n type: 'qi/topic.action.receipt.record',\n can: 'topic/action.receipt.record',\n operationType: 'record-action-receipt',\n ability: 'topic/record-action',\n hidden: true,\n inputSchema: {\n type: 'object',\n required: ['receipt'],\n additionalProperties: false,\n properties: { receipt: { type: 'object' }, idempotencyKey: { type: 'string' } },\n },\n buildPayload: (inputs, ctx) => {\n if (!inputs.receipt || typeof inputs.receipt !== 'object' || Array.isArray(inputs.receipt)) throw new Error('receipt must be an ActionReceiptV2 object');\n const receipt = inputs.receipt as Record<string, unknown>;\n if (receipt.topicId !== topicContext(ctx).topicId) throw new Error('Receipt Topic does not match the execution context');\n if (receipt.version !== 2 || !receipt.signature || !receipt.issuerDid) throw new Error('Receipt requires a v2 issuer signature');\n const receiptAction = receipt.action as Record<string, unknown> | undefined;\n const action = getAction(String(receiptAction?.type || ''));\n const manifestEntry = action && generateActionManifest().actions.find((entry) => entry.type === action.type);\n if (!manifestEntry || manifestEntry.contractDigest !== receiptAction?.contractDigest) throw new Error('Receipt Action contract digest does not match the live registry');\n return { receipt };\n },\n});\n\nregisterTopicOperation({\n type: 'qi/topic.action.cancel',\n can: 'topic/action.cancel',\n operationType: 'cancel-action',\n ability: 'topic/cancel-action',\n inputSchema: {\n type: 'object',\n required: ['requestId', 'reason'],\n additionalProperties: false,\n properties: { requestId: { type: 'string' }, reason: { type: 'string' }, idempotencyKey: { type: 'string' } },\n },\n buildPayload: (inputs) => ({ requestId: requiredString(inputs.requestId, 'requestId'), reason: requiredString(inputs.reason, 'reason') }),\n});\n\nregisterTopicOperation({\n type: 'qi/topic.status.transition',\n can: 'topic/status.transition',\n operationType: 'change-status',\n confirmation: true,\n owner: 'human',\n ability: 'topic/change-status',\n inputSchema: {\n type: 'object',\n required: ['from', 'to', 'transitionCode', 'reason'],\n additionalProperties: false,\n properties: {\n from: { type: 'string' },\n to: { type: 'string' },\n transitionCode: { type: 'string' },\n reason: { type: 'string' },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: async (inputs, ctx) => {\n const from = requiredString(inputs.from, 'from');\n const to = requiredString(inputs.to, 'to');\n if (to === 'resolved') {\n const topic = topicContext(ctx);\n const projection = await topicService(ctx).readProjection?.({ topicId: topic.topicId, topicRevision: topic.topicRevision, requestId: topic.requestId });\n if (!projection) throw new Error('Resolution requires a current Topic projection so completion policy can be verified');\n const completion = projection.completion as Record<string, unknown> | undefined;\n const outcome = projection.outcome as Record<string, unknown> | undefined;\n if (completion?.requiresOutcomeRecord === true && !outcome?.outcomeRecordId) throw new Error('Topic policy requires an accepted outcome record before resolution');\n }\n return {\n from,\n to,\n transitionCode: requiredString(inputs.transitionCode, 'transitionCode'),\n reason: requiredString(inputs.reason, 'reason'),\n };\n },\n});\n\nregisterTopicOperation({\n type: 'qi/topic.contract.confirm-setup',\n can: 'topic/contract.confirm-setup',\n operationType: 'confirm-setup',\n confirmation: true,\n owner: 'human',\n ability: 'topic/confirm-setup',\n inputSchema: {\n type: 'object',\n required: ['contractRevision', 'contractDigest', 'confirmationReference'],\n additionalProperties: false,\n properties: {\n contractRevision: { type: 'string' },\n contractDigest: { type: 'string', pattern: '^sha256:' },\n confirmationReference: { type: 'string' },\n transitionCode: { type: 'string' },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs, ctx) => {\n const revision = requiredString(inputs.contractRevision, 'contractRevision');\n const digest = requiredString(inputs.contractDigest, 'contractDigest');\n if (revision !== topicContext(ctx).contract.revision || digest !== topicContext(ctx).contract.digest)\n throw new Error('Setup confirmation must target the exact proposed contract revision and digest');\n return {\n contractRevision: revision,\n contractDigest: digest,\n confirmationReference: requiredString(inputs.confirmationReference, 'confirmationReference'),\n ...(inputs.transitionCode ? { transitionCode: String(inputs.transitionCode) } : {}),\n };\n },\n});\n\nregisterTopicOperation({\n type: 'qi/topic.outcome.propose',\n can: 'topic/outcome.propose',\n operationType: 'update-contract',\n ability: 'topic/update-contract',\n inputSchema: {\n type: 'object',\n required: ['statement'],\n additionalProperties: false,\n properties: { statement: { type: 'string' }, evidenceReferences: { type: 'array', items: { type: 'string' } }, idempotencyKey: { type: 'string' } },\n },\n buildPayload: (inputs) => ({\n patch: {\n outcome: {\n statement: requiredString(inputs.statement, 'statement'),\n status: 'proposed',\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n },\n },\n }),\n});\n\nregisterTopicOperation({\n type: 'qi/topic.decision.record',\n can: 'topic/decision.record',\n operationType: 'record-decision',\n ability: 'topic/record-decision',\n inputSchema: {\n type: 'object',\n required: ['decision', 'authorityDid', 'rationale'],\n additionalProperties: false,\n properties: {\n decision: { type: 'string' },\n authorityDid: { type: 'string', pattern: '^did:' },\n rationale: { type: 'string' },\n alternatives: { type: 'array', items: { type: 'string' } },\n receiptReferences: { type: 'array', items: { type: 'string' } },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs) => ({\n decision: requiredString(inputs.decision, 'decision'),\n authorityDid: requiredString(inputs.authorityDid, 'authorityDid'),\n rationale: requiredString(inputs.rationale, 'rationale'),\n alternatives: requiredArray(inputs.alternatives || [], 'alternatives'),\n receiptReferences: requiredArray(inputs.receiptReferences || [], 'receiptReferences'),\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n }),\n});\n\nregisterTopicOperation({\n type: 'qi/topic.context.link',\n can: 'topic/context.link',\n operationType: 'link-context',\n ability: 'topic/link-context',\n inputSchema: {\n type: 'object',\n required: ['contextType', 'id'],\n additionalProperties: false,\n properties: {\n contextType: { type: 'string', enum: ['ixo.resource', 'ixo.flow', 'matrix.conversation', 'ixo.entity', 'ixo.service'] },\n id: { type: 'string' },\n label: { type: 'string' },\n reference: { type: 'string' },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs) => ({\n type: requiredString(inputs.contextType, 'contextType'),\n id: requiredString(inputs.id, 'id'),\n label: String(inputs.label || ''),\n reference: String(inputs.reference || ''),\n }),\n});\n\nregisterTopicOperation({\n type: 'qi/topic.file.attach-reference',\n can: 'topic/file.attach-reference',\n operationType: 'attach-files',\n ability: 'topic/attach-files',\n inputSchema: {\n type: 'object',\n required: ['resource', 'fileId', 'version', 'cid', 'contentHash', 'path', 'name', 'mimeType', 'size'],\n additionalProperties: false,\n properties: {\n resource: { type: 'string' },\n fileId: { type: 'string' },\n version: { type: 'number' },\n cid: { type: 'string' },\n contentHash: { type: 'string' },\n path: { type: 'string' },\n name: { type: 'string' },\n mimeType: { type: 'string' },\n size: { type: 'number' },\n idempotencyKey: { type: 'string' },\n },\n },\n buildPayload: (inputs) => {\n if ('bytes' in inputs || 'content' in inputs || 'capability' in inputs)\n throw new Error('Topic file Actions accept pinned references only; bytes and access grants are forbidden');\n return {\n attachments: [\n {\n provider: 'ixo.vfs',\n resource: inputs.resource,\n fileId: inputs.fileId,\n version: inputs.version,\n cid: inputs.cid,\n contentHash: inputs.contentHash,\n path: inputs.path,\n name: inputs.name,\n mimeType: inputs.mimeType,\n size: inputs.size,\n },\n ],\n };\n },\n});\n\ninterface SemanticSpec {\n type: string;\n can: string;\n kinds: TopicActionBaseKind[];\n recordType: string;\n inputSchema: object;\n confirmation?: boolean;\n owner?: 'agent' | 'human';\n riskTier?: ActionDefinition['riskTier'];\n requiredServices?: string[];\n sensitiveInputPaths?: string[];\n sensitiveOutputPaths?: string[];\n execute: (inputs: Record<string, unknown>, ctx: ActionContext) => Promise<Record<string, unknown>> | Record<string, unknown>;\n}\n\nfunction registerSemanticAction(spec: SemanticSpec): void {\n registerAction({\n type: spec.type,\n can: spec.can,\n sideEffect: true,\n proof: { fields: ['recordDigest'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: spec.confirmation === true,\n requiredCapability: 'flow/block/execute',\n executionOwner: spec.owner || 'agent',\n riskTier: spec.riskTier,\n requiredServices: spec.requiredServices || ['topic'],\n sensitiveInputPaths: spec.sensitiveInputPaths,\n sensitiveOutputPaths: spec.sensitiveOutputPaths,\n topic: topicMetadata(spec.kinds, [spec.recordType], ['topic/request-action', 'topic/record-action'], 'recommended', spec.sensitiveInputPaths, spec.sensitiveOutputPaths),\n inputSchema: spec.inputSchema,\n outputSchema: [\n { path: 'recordId', displayName: 'Semantic record ID', type: 'string' },\n { path: 'recordType', displayName: 'Semantic record type', type: 'string' },\n { path: 'recordDigest', displayName: 'Semantic record digest', type: 'string' },\n { path: 'record', displayName: 'Semantic record', type: 'object' },\n ],\n run: async (inputs, ctx) => {\n topicContext(ctx);\n const value = await spec.execute(inputs, ctx);\n const { record, digest } = semanticRecord(spec.recordType, value, ctx);\n return { output: { recordId: record.id, recordType: record.type, recordDigest: digest, record: value }, topicRecords: [record] };\n },\n });\n}\n\nconst WORK_PHASES: Record<string, string> = {\n 'qi/work.assign': 'requested',\n 'qi/work.dispatch': 'dispatched',\n 'qi/work.checkpoint': 'in_progress',\n 'qi/work.submit': 'ready_for_review',\n 'qi/work.accept': 'completed',\n};\nfor (const [type, phase] of Object.entries(WORK_PHASES)) {\n registerSemanticAction({\n type,\n can: type.replace('qi/', '').replace('.', '/'),\n kinds: ['task', 'discussion', 'incident'],\n recordType: 'org.ixo.topic.work-event',\n confirmation: type === 'qi/work.accept',\n owner: type === 'qi/work.accept' ? 'human' : 'agent',\n inputSchema: {\n type: 'object',\n required: ['workId', 'resourceType'],\n additionalProperties: false,\n properties: {\n workId: { type: 'string' },\n resourceType: { type: 'string' },\n assigneeDid: { type: 'string' },\n note: { type: 'string' },\n artifactReferences: { type: 'array', items: { type: 'string' } },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n },\n },\n execute: (inputs, ctx) => ({\n workId: requiredString(inputs.workId, 'workId'),\n resourceType: requiredString(inputs.resourceType, 'resourceType'),\n phase,\n assigneeDid: String(inputs.assigneeDid || ''),\n note: String(inputs.note || ''),\n artifactReferences: requiredArray(inputs.artifactReferences || [], 'artifactReferences'),\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n actorDid: ctx.actorDid,\n occurredAt: new Date().toISOString(),\n }),\n });\n}\n\nregisterSemanticAction({\n type: 'qi/agent.invoke',\n can: 'agent/invoke',\n kinds: ['agent_task', 'question', 'task'],\n recordType: 'org.ixo.topic.agent-result',\n requiredServices: ['agents'],\n sensitiveInputPaths: ['prompt', 'toolPolicy'],\n sensitiveOutputPaths: ['record.result'],\n inputSchema: {\n type: 'object',\n required: ['agentDid', 'capsuleReference', 'toolPolicy'],\n additionalProperties: false,\n properties: {\n agentDid: { type: 'string', pattern: '^did:' },\n capsuleReference: { type: 'string' },\n toolPolicy: { type: 'object' },\n budget: { type: 'object' },\n deadline: { type: 'string' },\n executorPreference: { type: 'string', enum: ['qi-flow', 'qiforge', 'mcp'] },\n prompt: { type: 'string' },\n },\n },\n execute: async (inputs, ctx) => {\n if (!ctx.services.agents) throw new Error('Agent runtime service is not configured');\n const result = await ctx.services.agents.invoke({\n agentDid: requiredString(inputs.agentDid, 'agentDid'),\n capsuleReference: requiredString(inputs.capsuleReference, 'capsuleReference'),\n toolPolicy: (inputs.toolPolicy as Record<string, unknown>) || {},\n budget: inputs.budget as Record<string, unknown> | undefined,\n deadline: inputs.deadline as string | undefined,\n executorPreference: inputs.executorPreference as 'qi-flow' | 'qiforge' | 'mcp' | undefined,\n prompt: inputs.prompt as string | undefined,\n });\n return {\n sessionId: result.sessionId,\n result: result.result,\n resultDigest: sha256Digest(result.result),\n evidenceReferences: result.evidenceReferences || [],\n evidenceDigest: sha256Digest(result.evidenceReferences || []),\n providerReceiptReference: result.providerReceiptReference,\n };\n },\n});\n\nregisterSemanticAction({\n type: 'qi/agent.cancel',\n can: 'agent/cancel',\n kinds: ['agent_task', 'question', 'task'],\n recordType: 'org.ixo.topic.agent-cancellation',\n requiredServices: ['agents'],\n inputSchema: { type: 'object', required: ['sessionId'], additionalProperties: false, properties: { sessionId: { type: 'string' }, reason: { type: 'string' } } },\n execute: async (inputs, ctx) => {\n if (!ctx.services.agents) throw new Error('Agent runtime service is not configured');\n return ctx.services.agents.cancel({ sessionId: requiredString(inputs.sessionId, 'sessionId'), reason: String(inputs.reason || '') });\n },\n});\n\nregisterSemanticAction({\n type: 'qi/evidence.collect',\n can: 'evidence/collect',\n kinds: ['question', 'evaluation'],\n recordType: 'org.ixo.topic.evidence',\n requiredServices: ['evidence'],\n sensitiveOutputPaths: ['record.evidence'],\n inputSchema: {\n type: 'object',\n required: ['question', 'sourceReferences'],\n additionalProperties: false,\n properties: { question: { type: 'string' }, sourceReferences: { type: 'array', items: { type: 'string' } }, constraints: { type: 'object' } },\n },\n execute: async (inputs, ctx) => {\n if (!ctx.services.evidence) throw new Error('Evidence service is not configured');\n const result = await ctx.services.evidence.collect({\n question: requiredString(inputs.question, 'question'),\n sourceReferences: requiredArray(inputs.sourceReferences, 'sourceReferences'),\n constraints: inputs.constraints as Record<string, unknown> | undefined,\n });\n return {\n question: inputs.question,\n evidence: result.evidence,\n provenance: result.provenance,\n evidenceReferences: result.evidenceReferences,\n evidenceDigest: sha256Digest(result.evidence),\n };\n },\n});\n\nfor (const accepted of [false, true]) {\n registerSemanticAction({\n type: accepted ? 'qi/answer.accept' : 'qi/answer.propose',\n can: accepted ? 'answer/accept' : 'answer/propose',\n kinds: ['question'],\n recordType: accepted ? 'org.ixo.topic.accepted-answer' : 'org.ixo.topic.proposed-answer',\n confirmation: accepted,\n owner: accepted ? 'human' : 'agent',\n inputSchema: {\n type: 'object',\n required: accepted ? ['answer', 'acceptanceAuthorityDid', 'proposedAnswerRecordId'] : ['answer'],\n additionalProperties: false,\n properties: {\n answer: { type: 'string' },\n proposedAnswerRecordId: { type: 'string' },\n acceptanceAuthorityDid: { type: 'string', pattern: '^did:' },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n limitations: { type: 'string' },\n },\n },\n execute: (inputs, ctx) => ({\n answer: requiredString(inputs.answer, 'answer'),\n status: accepted ? 'accepted' : 'proposed',\n proposedAnswerRecordId: String(inputs.proposedAnswerRecordId || ''),\n authorityDid: accepted ? requiredString(inputs.acceptanceAuthorityDid, 'acceptanceAuthorityDid') : ctx.actorDid,\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n limitations: String(inputs.limitations || ''),\n occurredAt: new Date().toISOString(),\n }),\n });\n}\n\nfor (const review of [false, true]) {\n registerSemanticAction({\n type: review ? 'qi/evaluation.review' : 'qi/evaluation.run',\n can: review ? 'evaluation/review' : 'evaluation/run',\n kinds: ['evaluation', 'claims'],\n recordType: review ? 'org.ixo.topic.evaluation-review' : 'org.ixo.topic.evaluation-assertion',\n requiredServices: ['evaluations'],\n confirmation: review,\n owner: review ? 'human' : 'agent',\n inputSchema: {\n type: 'object',\n required: review ? ['assertionReference', 'methodologyRevision', 'rubricRevision'] : ['subjectReference', 'methodologyRevision', 'rubricRevision'],\n additionalProperties: true,\n properties: {\n subjectReference: { type: 'string' },\n assertionReference: { type: 'string' },\n methodologyRevision: { type: 'string' },\n rubricRevision: { type: 'string' },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n },\n },\n execute: async (inputs, ctx) => {\n if (!ctx.services.evaluations) throw new Error('Evaluation runtime service is not configured');\n const result = review ? await ctx.services.evaluations.review(inputs) : await ctx.services.evaluations.run(inputs);\n const value = 'assertion' in result ? result.assertion : result.review;\n return {\n providerResult: value,\n assertionId: 'assertionId' in result ? result.assertionId : undefined,\n reviewId: 'reviewId' in result ? result.reviewId : undefined,\n methodologyRevision: inputs.methodologyRevision,\n rubricRevision: inputs.rubricRevision,\n evaluatorDid: ctx.actorDid,\n evidenceReferences: result.evidenceReferences,\n signature: result.signature,\n };\n },\n });\n}\n\nregisterSemanticAction({\n type: 'qi/settlement.execute',\n can: 'settlement/execute',\n kinds: ['claims'],\n recordType: 'org.ixo.topic.settlement-record',\n confirmation: true,\n owner: 'human',\n riskTier: 'critical',\n requiredServices: ['settlement'],\n inputSchema: {\n type: 'object',\n required: ['approvedClaimReference', 'amount', 'asset', 'recipient', 'policyReference', 'confirmationReference'],\n additionalProperties: false,\n properties: {\n approvedClaimReference: { type: 'string' },\n amount: { type: 'string' },\n asset: { type: 'string' },\n recipient: { type: 'string' },\n policyReference: { type: 'string' },\n confirmationReference: { type: 'string' },\n },\n },\n execute: async (inputs, ctx) => {\n if (!ctx.services.settlement) throw new Error('Settlement service is not configured');\n return ctx.services.settlement.execute({\n approvedClaimReference: requiredString(inputs.approvedClaimReference, 'approvedClaimReference'),\n amount: requiredString(inputs.amount, 'amount'),\n asset: requiredString(inputs.asset, 'asset'),\n recipient: requiredString(inputs.recipient, 'recipient'),\n policyReference: requiredString(inputs.policyReference, 'policyReference'),\n confirmationReference: requiredString(inputs.confirmationReference, 'confirmationReference'),\n });\n },\n});\n\nregisterSemanticAction({\n type: 'qi/incident.escalate',\n can: 'incident/escalate',\n kinds: ['incident'],\n recordType: 'org.ixo.topic.incident-escalation',\n confirmation: true,\n requiredServices: ['incidents'],\n inputSchema: {\n type: 'object',\n required: ['severity', 'affectedResources', 'recipients', 'summary'],\n additionalProperties: false,\n properties: {\n severity: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },\n affectedResources: { type: 'array', items: { type: 'string' } },\n recipients: { type: 'array', items: { type: 'string' } },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n summary: { type: 'string' },\n },\n },\n execute: async (inputs, ctx) => {\n if (!ctx.services.incidents) throw new Error('Incident service is not configured');\n const payload = {\n severity: requiredString(inputs.severity, 'severity'),\n affectedResources: requiredArray(inputs.affectedResources, 'affectedResources'),\n recipients: requiredArray(inputs.recipients, 'recipients'),\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n summary: requiredString(inputs.summary, 'summary'),\n };\n return { ...payload, ...(await ctx.services.incidents.escalate(payload)) };\n },\n});\n\nregisterSemanticAction({\n type: 'qi/incident.mitigation.record',\n can: 'incident/mitigation.record',\n kinds: ['incident'],\n recordType: 'org.ixo.topic.incident-mitigation',\n inputSchema: {\n type: 'object',\n required: ['mitigation', 'affectedResources'],\n additionalProperties: false,\n properties: {\n mitigation: { type: 'string' },\n affectedResources: { type: 'array', items: { type: 'string' } },\n evidenceReferences: { type: 'array', items: { type: 'string' } },\n occurredAt: { type: 'string' },\n },\n },\n execute: (inputs, ctx) => ({\n mitigation: requiredString(inputs.mitigation, 'mitigation'),\n affectedResources: requiredArray(inputs.affectedResources, 'affectedResources'),\n evidenceReferences: requiredArray(inputs.evidenceReferences || [], 'evidenceReferences'),\n recordedBy: ctx.actorDid,\n occurredAt: String(inputs.occurredAt || new Date().toISOString()),\n }),\n});\n\n/**\n * Deliver a Topic reminder.\n *\n * Registered with plain `registerAction` rather than `registerTopicOperation`:\n * that helper exists for Actions whose `run` appends a Topic document\n * operation, and a reminder mutates nothing. It posts a message and leaves a\n * receipt — which is exactly what `writeBackMode: 'receipt-only'` describes.\n *\n * `eligibleForTimeTrigger` is the point of the whole registration: it is what\n * lets a schedule name this Action, and the scheduling contract below crosses\n * the manifest JSON boundary so flow-manager enforces it out of process.\n *\n * R0 because the only effect is a message in a room the recipient is already\n * in. R0 also buys the 60-minute misfire grace, which is the right trade for a\n * reminder: delivering late beats not delivering at all.\n *\n * CROSS-REPO CONTRACT: flow-manager (apps/app/src/scheduling/topic-reminder.ts)\n * fires this Action type and writes the matching thread notice.\n */\nregisterAction({\n type: 'qi/topic.remind',\n can: 'topic/reminder.deliver',\n displayName: 'Send a Topic reminder',\n description: 'Posts a reminder into the Topic thread and notifies the people responsible for it.',\n sideEffect: true,\n proof: { fields: ['deliveredAt'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n executionOwner: 'agent',\n riskTier: 'low',\n requiredServices: ['topic'],\n eligibleForTimeTrigger: true,\n scheduling: {\n riskTier: 'R0',\n misfirePolicies: ['run_once_immediately', 'skip'],\n // Reminders never queue: two firings of the same reminder are the same\n // reminder, and delivering it twice is the failure mode, not the goal.\n overlapPolicies: ['skip'],\n approvalRequirement: 'none',\n idempotencyStrategy: 'idempotency_key',\n inputModes: ['resolve_at_fire'],\n runModes: ['new_run_per_occurrence'],\n },\n topic: topicMetadata(ALL_KINDS, [], ['topic/manage-reminder'], 'contextual'),\n inputSchema: {\n type: 'object',\n required: ['recipients'],\n additionalProperties: false,\n properties: {\n recipients: { type: 'array', items: { type: 'string' } },\n message: { type: 'string' },\n idempotencyKey: { type: 'string' },\n },\n },\n outputSchema: [\n { path: 'deliveredAt', displayName: 'Delivered at', type: 'string' },\n { path: 'recipients', displayName: 'Reminded', type: 'string' },\n ],\n run: async (inputs, ctx) => {\n const service = topicService(ctx);\n if (!service.deliverReminder) throw new Error('The host did not grant a Topic reminder delivery service');\n const recipients = requiredArray(inputs.recipients, 'recipients');\n if (recipients.length === 0) throw new Error('A reminder needs at least one recipient');\n return {\n output: await service.deliverReminder({\n context: topicContext(ctx),\n recipients,\n message: String(inputs.message || ''),\n idempotencyKey: idempotencyKey('qi/topic.remind', inputs, ctx),\n }),\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { parseAttendeesField, type CalendarEventCreateInputs } from './eventCreate.types';\n\nexport const CALENDAR_EVENT_CREATE_SLUG = 'GOOGLECALENDAR_CREATE_EVENT';\n\nregisterAction<CalendarEventCreateInputs>({\n // Provider-explicit identity (IXO-4420 §5): this block is Google Calendar\n // via Composio with a per-runner pinned connection — `-self` distinguishes\n // it from the delegated `qi/googlecalendar.event.create`. The retired\n // `qi/calendar.event.create` name resolves here via ACTION_TYPE_ALIASES.\n // The `can` deliberately keeps its historical value so existing UCAN grants\n // keep matching; `qi/ixo.calendar.event.*` (M4) gets its own can namespace.\n type: 'qi/googlecalendar.event.create-self',\n can: 'calendar.event/create',\n sideEffect: true,\n proof: { fields: ['eventId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['connection', 'start_datetime'],\n properties: {\n connection: { type: 'object', description: 'Pinned Calendar connection with a connectedAccountId.' },\n start_datetime: { type: 'string', description: 'Event start time (ISO 8601).' },\n end_datetime: { type: 'string', description: 'Optional event end time (ISO 8601).' },\n calendar_id: { type: 'string', description: 'Calendar to write to; defaults to \"primary\".' },\n summary: { type: 'string', description: 'Optional event title.' },\n description: { type: 'string', description: 'Optional event description.' },\n location: { type: 'string', description: 'Optional event location.' },\n timezone: { type: 'string', description: 'Optional timezone for the event.' },\n send_updates: { type: 'string', description: 'Optional attendee-notification mode passed through to Calendar.' },\n attendees: { type: 'string', description: 'Optional attendees as a JSON array, newline-, or comma-separated emails.' },\n },\n },\n outputSchema: [\n { path: 'eventId', displayName: 'Event ID', type: 'string', description: 'Opaque identifier of the created event' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string', description: 'Web UI link to the created event' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n { path: 'startIso', displayName: 'Start', type: 'string', description: 'Resolved start time (ISO 8601)' },\n { path: 'endIso', displayName: 'End', type: 'string', description: 'Resolved end time (ISO 8601)' },\n { path: 'hangoutLink', displayName: 'Meet link', type: 'string' },\n ],\n events: [\n {\n name: 'event.created',\n displayName: 'Calendar event created',\n description: 'Fired after a new event is written to Calendar',\n payloadSchema: [\n { path: 'eventId', displayName: 'Event ID', type: 'string' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n ],\n pendingDisplayFields: ['summary', 'eventId'],\n },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Calendar integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Calendar before running this action.');\n }\n\n // Entity-switch guard. See gotchas §2.\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Calendar to use it here.');\n }\n\n const start = (inputs.start_datetime || '').trim();\n if (!start) {\n throw new Error('Start time is required.');\n }\n\n const args: Record<string, unknown> = {\n start_datetime: start,\n calendar_id: (inputs.calendar_id || 'primary').trim() || 'primary',\n };\n\n const end = (inputs.end_datetime || '').trim();\n if (end) args.end_datetime = end;\n if (inputs.summary) args.summary = inputs.summary;\n if (inputs.description) args.description = inputs.description;\n if (inputs.location) args.location = inputs.location;\n if (inputs.timezone) args.timezone = inputs.timezone;\n if (inputs.send_updates) args.send_updates = inputs.send_updates;\n\n const attendees = parseAttendeesField(inputs.attendees || '');\n if (attendees.length > 0) args.attendees = attendees;\n\n const result = await svc.executeTool({\n toolSlug: CALENDAR_EVENT_CREATE_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Calendar event creation failed');\n }\n\n // Composio wraps the tool response under `data.response_data`. See the tool\n // schema in docs/integrations-reference/tools/GOOGLECALENDAR_CREATE_EVENT.json.\n const envelope = result.data as any;\n const event = envelope?.response_data || envelope?.data?.response_data || envelope || {};\n\n const eventId = String(event.id || '');\n const htmlLink = String(event.htmlLink || envelope?.display_url || '');\n const summary = String(event.summary || inputs.summary || '');\n const startIso = String(event.start?.dateTime || event.start?.date || start);\n const endIso = String(event.end?.dateTime || event.end?.date || end || '');\n const hangoutLink = String(event.hangoutLink || '');\n\n return {\n output: {\n eventId,\n htmlLink,\n summary,\n startIso,\n endIso,\n hangoutLink,\n },\n events: eventId ? [{ name: 'event.created', payload: { eventId, htmlLink, summary } }] : undefined,\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport { parseAttendeesField } from './eventCreate.types';\nimport type { CalendarEventUpdateInputs } from './eventUpdate.types';\n\nexport const CALENDAR_EVENT_UPDATE_SLUG = 'GOOGLECALENDAR_UPDATE_EVENT';\nexport const CALENDAR_EVENT_GET_SLUG = 'GOOGLECALENDAR_EVENTS_GET';\n\nregisterAction<CalendarEventUpdateInputs>({\n // Provider-explicit identity (IXO-4420 §5); `qi/calendar.event.update` is\n // a permanent alias. `can` keeps its historical value — see eventCreate.ts.\n type: 'qi/googlecalendar.event.update-self',\n can: 'calendar.event/update',\n sideEffect: true,\n proof: { fields: ['eventId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['connection', 'event_id', 'start_datetime'],\n properties: {\n connection: { type: 'object', description: 'Pinned Calendar connection with a connectedAccountId.' },\n event_id: { type: 'string', description: 'Identifier of the existing event to update.' },\n start_datetime: { type: 'string', description: 'Event start time (ISO 8601).' },\n end_datetime: { type: 'string', description: 'Optional event end time (ISO 8601).' },\n calendar_id: { type: 'string', description: 'Calendar containing the event; defaults to \"primary\".' },\n summary: { type: 'string', description: 'Optional event title.' },\n description: { type: 'string', description: 'Optional event description.' },\n location: { type: 'string', description: 'Optional event location.' },\n timezone: { type: 'string', description: 'Optional timezone for the event.' },\n send_updates: { type: 'string', description: 'Optional attendee-notification mode passed through to Calendar.' },\n attendees: { type: 'string', description: 'Optional attendees as a JSON array, newline-, or comma-separated emails.' },\n },\n },\n outputSchema: [\n { path: 'eventId', displayName: 'Event ID', type: 'string' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n { path: 'startIso', displayName: 'Start', type: 'string' },\n { path: 'endIso', displayName: 'End', type: 'string' },\n ],\n events: [\n {\n name: 'event.updated',\n displayName: 'Calendar event updated',\n description: 'Fired after an existing event is replaced',\n payloadSchema: [\n { path: 'eventId', displayName: 'Event ID', type: 'string' },\n { path: 'htmlLink', displayName: 'Event link', type: 'string' },\n { path: 'summary', displayName: 'Summary', type: 'string' },\n ],\n pendingDisplayFields: ['summary', 'eventId'],\n },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Calendar integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Calendar before running this action.');\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Calendar to use it here.');\n }\n\n const eventId = (inputs.event_id || '').trim();\n if (!eventId) {\n throw new Error('Event ID is required to update an event.');\n }\n const start = (inputs.start_datetime || '').trim();\n if (!start) {\n throw new Error('Start time is required.');\n }\n\n const args: Record<string, unknown> = {\n event_id: eventId,\n start_datetime: start,\n calendar_id: (inputs.calendar_id || 'primary').trim() || 'primary',\n };\n\n const end = (inputs.end_datetime || '').trim();\n if (end) args.end_datetime = end;\n if (inputs.summary) args.summary = inputs.summary;\n if (inputs.description) args.description = inputs.description;\n if (inputs.location) args.location = inputs.location;\n if (inputs.timezone) args.timezone = inputs.timezone;\n if (inputs.send_updates) args.send_updates = inputs.send_updates;\n\n const attendees = parseAttendeesField(inputs.attendees || '');\n if (attendees.length > 0) args.attendees = attendees;\n\n const result = await svc.executeTool({\n toolSlug: CALENDAR_EVENT_UPDATE_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Calendar event update failed');\n }\n\n const envelope = result.data as any;\n const event = envelope?.response_data || envelope?.data?.response_data || envelope || {};\n\n const outId = String(event.id || eventId);\n const htmlLink = String(event.htmlLink || envelope?.display_url || '');\n const summary = String(event.summary || inputs.summary || '');\n const startIso = String(event.start?.dateTime || event.start?.date || start);\n const endIso = String(event.end?.dateTime || event.end?.date || end || '');\n\n return {\n output: {\n eventId: outId,\n htmlLink,\n summary,\n startIso,\n endIso,\n },\n events: [{ name: 'event.updated', payload: { eventId: outId, htmlLink, summary } }],\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport type { CalendarEventListInputs } from './eventList.types';\n\nexport const CALENDAR_EVENT_LIST_SLUG = 'GOOGLECALENDAR_EVENTS_LIST';\n\nregisterAction<CalendarEventListInputs>({\n // Provider-explicit identity (IXO-4420 §5); `qi/calendar.event.list` is\n // a permanent alias. `can` keeps its historical value — see eventCreate.ts.\n type: 'qi/googlecalendar.event.list-self',\n can: 'calendar.event/list',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: false,\n inputSchema: {\n type: 'object',\n required: ['connection'],\n properties: {\n connection: { type: 'object', description: 'Pinned Calendar connection with a connectedAccountId.' },\n calendarId: { type: 'string', description: 'Calendar to list from; defaults to \"primary\".' },\n q: { type: 'string', description: 'Optional free-text search query for events.' },\n timeMin: { type: 'string', description: 'Optional lower bound for event start time (ISO 8601).' },\n timeMax: { type: 'string', description: 'Optional upper bound for event start time (ISO 8601).' },\n timeZone: { type: 'string', description: 'Optional timezone for the returned times.' },\n orderBy: { type: 'string', description: 'Optional ordering of results (e.g. startTime).' },\n singleEvents: { type: 'boolean', description: 'Optional flag to expand recurring events into single instances.' },\n maxResults: { type: 'string', description: 'Optional maximum number of events to return (parsed as an integer).' },\n },\n },\n outputSchema: [\n { path: 'items', displayName: 'Events', type: 'array', description: 'Raw event objects as returned by Calendar' },\n { path: 'count', displayName: 'Count', type: 'number' },\n { path: 'firstId', displayName: 'First event ID', type: 'string' },\n { path: 'ids', displayName: 'Event IDs', type: 'array' },\n { path: 'nextPageToken', displayName: 'Next page token', type: 'string' },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Calendar integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Calendar before running this action.');\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Calendar to use it here.');\n }\n\n const args: Record<string, unknown> = {\n calendarId: (inputs.calendarId || 'primary').trim() || 'primary',\n };\n if (inputs.q) args.q = inputs.q;\n if (inputs.timeMin) args.timeMin = inputs.timeMin;\n if (inputs.timeMax) args.timeMax = inputs.timeMax;\n if (inputs.timeZone) args.timeZone = inputs.timeZone;\n if (inputs.orderBy) args.orderBy = inputs.orderBy;\n if (typeof inputs.singleEvents === 'boolean') args.singleEvents = inputs.singleEvents;\n if (inputs.maxResults) {\n const n = Number.parseInt(inputs.maxResults, 10);\n if (Number.isFinite(n) && n > 0) args.maxResults = n;\n }\n\n const result = await svc.executeTool({\n toolSlug: CALENDAR_EVENT_LIST_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Calendar list failed');\n }\n\n const envelope = result.data as any;\n const list = envelope?.items ? envelope : envelope?.data || envelope;\n const items: any[] = Array.isArray(list?.items) ? list.items : [];\n const ids = items.map((e) => String(e?.id || '')).filter(Boolean);\n\n return {\n output: {\n items,\n count: items.length,\n firstId: ids[0] ?? null,\n ids,\n nextPageToken: String(list?.nextPageToken || ''),\n },\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport type { XeroContactCreateInputs } from './contactCreate.types';\n\nexport const XERO_CREATE_CONTACT_SLUG = 'XERO_CREATE_CONTACT';\n\nregisterAction<XeroContactCreateInputs>({\n type: 'qi/xero.contact.create',\n can: 'xero.contact/create',\n sideEffect: true,\n proof: { fields: ['contactId'] },\n done: doneWhenCompleted,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['connection', 'Name'],\n properties: {\n connection: { type: 'object', description: 'Pinned Xero connection with connectedAccountId and entityDid.' },\n tenant_id: { type: 'string', description: 'Xero org identifier; empty uses the connection default.' },\n Name: { type: 'string', description: 'Contact display name.' },\n FirstName: { type: 'string', description: 'Contact first name.' },\n LastName: { type: 'string', description: 'Contact last name.' },\n EmailAddress: { type: 'string', description: 'Contact email address.' },\n phone_number: { type: 'string', description: 'Contact phone number.' },\n mobile_number: { type: 'string', description: 'Contact mobile number.' },\n Website: { type: 'string', description: 'Contact website URL.' },\n TaxNumber: { type: 'string', description: 'Contact tax number.' },\n AccountNumber: { type: 'string', description: 'Contact account number.' },\n DefaultCurrency: { type: 'string', description: 'Default currency code for the contact.' },\n BankAccountDetails: { type: 'string', description: 'Contact bank account details.' },\n IsCustomer: { type: 'boolean', description: 'Whether the contact is a customer.' },\n IsSupplier: { type: 'boolean', description: 'Whether the contact is a supplier.' },\n },\n },\n outputSchema: [\n { path: 'contactId', displayName: 'Contact ID', type: 'string' },\n { path: 'name', displayName: 'Name', type: 'string' },\n { path: 'emailAddress', displayName: 'Email', type: 'string' },\n ],\n events: [\n {\n name: 'contact.created',\n displayName: 'Xero contact created',\n description: 'Fired after a new Xero contact is written',\n payloadSchema: [\n { path: 'contactId', displayName: 'Contact ID', type: 'string' },\n { path: 'name', displayName: 'Name', type: 'string' },\n ],\n pendingDisplayFields: ['name', 'contactId'],\n },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Xero integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Xero before running this action.');\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Xero to use it here.');\n }\n\n const name = (inputs.Name || '').trim();\n if (!name) throw new Error('Name is required.');\n\n const args: Record<string, unknown> = { Name: name };\n if (inputs.tenant_id) args.tenant_id = inputs.tenant_id;\n if (inputs.FirstName) args.FirstName = inputs.FirstName;\n if (inputs.LastName) args.LastName = inputs.LastName;\n if (inputs.EmailAddress) args.EmailAddress = inputs.EmailAddress;\n if (inputs.phone_number) args.phone_number = inputs.phone_number;\n if (inputs.mobile_number) args.mobile_number = inputs.mobile_number;\n if (inputs.Website) args.Website = inputs.Website;\n if (inputs.TaxNumber) args.TaxNumber = inputs.TaxNumber;\n if (inputs.AccountNumber) args.AccountNumber = inputs.AccountNumber;\n if (inputs.DefaultCurrency) args.DefaultCurrency = inputs.DefaultCurrency;\n if (inputs.BankAccountDetails) args.BankAccountDetails = inputs.BankAccountDetails;\n if (typeof inputs.IsCustomer === 'boolean') args.IsCustomer = inputs.IsCustomer;\n if (typeof inputs.IsSupplier === 'boolean') args.IsSupplier = inputs.IsSupplier;\n\n const result = await svc.executeTool({\n toolSlug: XERO_CREATE_CONTACT_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Xero contact creation failed');\n }\n\n // Xero returns Contacts in a Contacts[] array. Grab the first.\n const envelope = result.data as any;\n const contact = envelope?.Contacts?.[0] || envelope?.data?.Contacts?.[0] || envelope?.contact || envelope || {};\n const contactId = String(contact.ContactID || contact.contactID || contact.id || '');\n\n return {\n output: {\n contactId,\n name: String(contact.Name || name),\n emailAddress: String(contact.EmailAddress || inputs.EmailAddress || ''),\n },\n events: contactId ? [{ name: 'contact.created', payload: { contactId, name: String(contact.Name || name) } }] : undefined,\n };\n },\n});\n","import { registerAction, neverDone } from '../../registry';\nimport type { XeroInvoiceCreateInputs } from './invoiceCreate.types';\n\nexport const XERO_CREATE_INVOICE_SLUG = 'XERO_CREATE_INVOICE';\n\n/**\n * Runtime shape passed to `run()`. The flow detail component resolves each\n * line-item cell (including `{{item.*}}` iterator refs) before calling the\n * action, so `run()` receives a final array of finalised line-item objects.\n */\nexport interface XeroInvoiceCreateRunInputs extends Omit<XeroInvoiceCreateInputs, 'LineItems'> {\n LineItems: Array<Record<string, unknown>>;\n}\n\nregisterAction<XeroInvoiceCreateRunInputs>({\n type: 'qi/xero.invoice.create',\n can: 'xero.invoice/create',\n sideEffect: true,\n proof: { fields: ['invoiceId'] },\n done: neverDone,\n // Repeatable: many invoices are created over the flow's life. Never latches\n // to a terminal Done. See cardinality.\n cardinality: 'many',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n inputSchema: {\n type: 'object',\n required: ['connection', 'LineItems'],\n properties: {\n connection: { type: 'object', description: 'Pinned Xero connection with connectedAccountId and entityDid.' },\n tenant_id: { type: 'string', description: 'Xero org identifier; empty uses the connection default.' },\n Type: { type: 'string', description: \"Invoice type: 'ACCREC' (sale) or 'ACCPAY' (bill); defaults to ACCREC.\" },\n Status: { type: 'string', description: 'Invoice status (e.g. DRAFT, AUTHORISED).' },\n Date: { type: 'string', description: 'Invoice date.' },\n DueDate: { type: 'string', description: 'Invoice due date.' },\n ContactID: { type: 'string', description: 'Xero contact UUID; preferred over ContactName.' },\n ContactName: { type: 'string', description: 'Contact name fallback when ContactID is absent.' },\n Reference: { type: 'string', description: 'Invoice reference text.' },\n InvoiceNumber: { type: 'string', description: 'Invoice number.' },\n CurrencyCode: { type: 'string', description: 'Invoice currency code.' },\n LineItems: { type: 'array', description: 'Finalised array of invoice line-item objects.' },\n },\n },\n outputSchema: [\n { path: 'invoiceId', displayName: 'Invoice ID', type: 'string' },\n { path: 'invoiceNumber', displayName: 'Invoice number', type: 'string' },\n { path: 'total', displayName: 'Total', type: 'number' },\n { path: 'status', displayName: 'Status', type: 'string' },\n ],\n events: [\n {\n name: 'invoice.created',\n displayName: 'Xero invoice created',\n description: 'Fired after a new Xero invoice is written',\n payloadSchema: [\n { path: 'invoiceId', displayName: 'Invoice ID', type: 'string' },\n { path: 'invoiceNumber', displayName: 'Invoice number', type: 'string' },\n { path: 'total', displayName: 'Total', type: 'number' },\n ],\n pendingDisplayFields: ['invoiceNumber', 'total'],\n },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Xero integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Xero before running this action.');\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Xero to use it here.');\n }\n\n const type = (inputs.Type || '').trim().toUpperCase() || 'ACCREC';\n if (type !== 'ACCREC' && type !== 'ACCPAY') {\n throw new Error('Invoice type must be ACCREC (sale) or ACCPAY (bill).');\n }\n\n if (!Array.isArray(inputs.LineItems) || inputs.LineItems.length === 0) {\n throw new Error('At least one line item is required.');\n }\n\n const args: Record<string, unknown> = {\n Type: type,\n LineItems: inputs.LineItems,\n };\n if (inputs.tenant_id) args.tenant_id = inputs.tenant_id;\n if (inputs.Status) args.Status = inputs.Status;\n if (inputs.Date) args.Date = inputs.Date;\n if (inputs.DueDate) args.DueDate = inputs.DueDate;\n if (inputs.ContactID) args.ContactID = inputs.ContactID;\n else if (inputs.ContactName) args.ContactName = inputs.ContactName;\n if (inputs.Reference) args.Reference = inputs.Reference;\n if (inputs.InvoiceNumber) args.InvoiceNumber = inputs.InvoiceNumber;\n if (inputs.CurrencyCode) args.CurrencyCode = inputs.CurrencyCode;\n\n const result = await svc.executeTool({\n toolSlug: XERO_CREATE_INVOICE_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Xero invoice creation failed');\n }\n\n const envelope = result.data as any;\n const invoice = envelope?.Invoices?.[0] || envelope?.data?.Invoices?.[0] || envelope?.invoice || envelope || {};\n const invoiceId = String(invoice.InvoiceID || invoice.invoiceID || invoice.id || '');\n const invoiceNumber = String(invoice.InvoiceNumber || inputs.InvoiceNumber || '');\n const total = typeof invoice.Total === 'number' ? invoice.Total : Number(invoice.Total) || 0;\n const status = String(invoice.Status || inputs.Status || 'DRAFT');\n\n return {\n output: {\n invoiceId,\n invoiceNumber,\n total,\n status,\n },\n events: invoiceId ? [{ name: 'invoice.created', payload: { invoiceId, invoiceNumber, total } }] : undefined,\n };\n },\n});\n","import { registerAction, doneWhenCompleted } from '../../registry';\nimport type { XeroInvoiceListInputs } from './invoiceList.types';\n\nexport const XERO_LIST_INVOICES_SLUG = 'XERO_LIST_INVOICES';\n\nregisterAction<XeroInvoiceListInputs>({\n type: 'qi/xero.invoice.list',\n can: 'xero.invoice/list',\n sideEffect: false,\n proof: 'none',\n done: doneWhenCompleted,\n defaultRequiresConfirmation: false,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: false,\n inputSchema: {\n type: 'object',\n required: ['connection'],\n properties: {\n connection: { type: 'object', description: 'Pinned Xero connection with connectedAccountId and entityDid.' },\n tenantId: { type: 'string', description: 'Xero org identifier (camelCase for the list tool).' },\n page: { type: 'string', description: 'Page number; parsed to an integer >= 1.' },\n order: { type: 'string', description: 'Sort order expression.' },\n Statuses: { type: 'string', description: 'Filter by invoice statuses.' },\n ContactIDs: { type: 'string', description: 'Filter by contact IDs.' },\n InvoiceIDs: { type: 'string', description: 'Filter by invoice IDs.' },\n where: { type: 'string', description: 'Xero where-clause filter.' },\n createdByMyApp: { type: 'boolean', description: 'Limit to invoices created by this app.' },\n includeArchived: { type: 'boolean', description: 'Include archived invoices.' },\n },\n },\n outputSchema: [\n { path: 'items', displayName: 'Invoices', type: 'array' },\n { path: 'count', displayName: 'Count', type: 'number' },\n { path: 'firstId', displayName: 'First invoice ID', type: 'string' },\n { path: 'ids', displayName: 'Invoice IDs', type: 'array' },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Xero integration is not configured');\n }\n\n const connection = inputs.connection;\n if (!connection?.connectedAccountId) {\n throw new Error('Connect Xero before running this action.');\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && connection.entityDid && currentEntityDid !== connection.entityDid) {\n throw new Error('This block was configured for a different workspace. Reconnect Xero to use it here.');\n }\n\n const args: Record<string, unknown> = {};\n if (inputs.tenantId) args.tenantId = inputs.tenantId;\n if (inputs.page) {\n const p = Number.parseInt(inputs.page, 10);\n if (Number.isFinite(p) && p >= 1) args.page = p;\n }\n if (inputs.order) args.order = inputs.order;\n if (inputs.Statuses) args.Statuses = inputs.Statuses;\n if (inputs.ContactIDs) args.ContactIDs = inputs.ContactIDs;\n if (inputs.InvoiceIDs) args.InvoiceIDs = inputs.InvoiceIDs;\n if (inputs.where) args.where = inputs.where;\n if (typeof inputs.createdByMyApp === 'boolean') args.createdByMyApp = inputs.createdByMyApp;\n if (typeof inputs.includeArchived === 'boolean') args.includeArchived = inputs.includeArchived;\n\n const result = await svc.executeTool({\n toolSlug: XERO_LIST_INVOICES_SLUG,\n connectedAccountId: connection.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Xero invoice list failed');\n }\n\n const envelope = result.data as any;\n const list = envelope?.Invoices ? envelope : envelope?.data || envelope;\n const items: any[] = Array.isArray(list?.Invoices) ? list.Invoices : Array.isArray(list?.items) ? list.items : [];\n // Remap InvoiceID → id for downstream uniformity, keep PascalCase inside items untouched.\n const ids = items.map((i) => String(i?.InvoiceID || i?.id || '')).filter(Boolean);\n\n return {\n output: {\n items,\n count: items.length,\n firstId: ids[0] ?? null,\n ids,\n },\n };\n },\n});\n","import { registerAction, neverDone } from '../../registry';\nimport { readFlowXeroBinding } from './flowBinding';\nimport type { XeroPaymentCreateInputs } from './paymentCreate.types';\n\nexport const XERO_CREATE_PAYMENT_SLUG = 'XERO_CREATE_PAYMENT';\n\n/**\n * Runtime shape passed to `run()`. Same as the storage shape — the flow\n * detail component does the resolution + numeric coercion before calling.\n *\n * `AccountID` is not part of it: the bank account comes from the flow's Xero\n * binding. In-flight work items minted before the binding existed may still\n * carry one, so it is accepted as a fallback and nothing more.\n */\nexport interface XeroPaymentCreateRunInputs extends Omit<XeroPaymentCreateInputs, 'Amount' | 'CurrencyRate'> {\n Amount: number;\n CurrencyRate?: number;\n /** @deprecated Superseded by the flow's Xero binding; read only as a fallback. */\n AccountID?: string;\n}\n\nregisterAction<XeroPaymentCreateRunInputs>({\n type: 'qi/xero.payment.create',\n can: 'xero.payment/create',\n sideEffect: true,\n proof: { fields: ['paymentId'] },\n done: neverDone,\n // Repeatable: many payments are created over the flow's life. Never latches\n // to a terminal Done. See cardinality.\n cardinality: 'many',\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\n // The Xero account and the bank account it debits are not inputs: they come\n // from the flow's connection binding, which is in place before a session can\n // start. Only what varies per payment is asked for here.\n inputSchema: {\n type: 'object',\n required: ['InvoiceID', 'Amount'],\n properties: {\n tenant_id: { type: 'string', description: \"Xero org identifier; empty uses the flow binding's organisation.\" },\n InvoiceID: { type: 'string', description: 'UUID of the invoice being paid.' },\n Date: { type: 'string', description: 'Payment date (YYYY-MM-DD); defaults to today if blank.' },\n Amount: { type: 'number', description: 'Payment amount; must be a positive number.' },\n Reference: { type: 'string', description: 'Free-text reference, typically the on-chain tx hash.' },\n CurrencyRate: { type: 'number', description: 'Optional currency rate for multicurrency payments.' },\n },\n },\n outputSchema: [\n { path: 'paymentId', displayName: 'Payment ID', type: 'string' },\n { path: 'invoiceId', displayName: 'Invoice ID', type: 'string' },\n { path: 'amount', displayName: 'Amount', type: 'number' },\n { path: 'date', displayName: 'Date', type: 'string' },\n { path: 'reference', displayName: 'Reference', type: 'string' },\n { path: 'status', displayName: 'Status', type: 'string' },\n ],\n events: [\n {\n name: 'payment.created',\n displayName: 'Xero payment recorded',\n description: 'Fired after a payment is recorded against a Xero invoice — settles the bill in the books.',\n payloadSchema: [\n { path: 'paymentId', displayName: 'Payment ID', type: 'string' },\n { path: 'invoiceId', displayName: 'Invoice ID', type: 'string' },\n { path: 'amount', displayName: 'Amount', type: 'number' },\n { path: 'reference', displayName: 'Reference', type: 'string' },\n ],\n pendingDisplayFields: ['invoiceId', 'amount'],\n },\n ],\n run: async (inputs, ctx) => {\n const svc = ctx.services.integrations;\n if (!svc?.executeTool) {\n throw new Error('Xero integration is not configured');\n }\n\n const binding = readFlowXeroBinding(ctx.yDoc);\n if (!binding?.connectedAccountId) {\n throw new Error(\"Connect Xero in this flow's connections before running this action.\");\n }\n\n const currentEntityDid = svc.getEntityDid?.();\n if (currentEntityDid && binding.entityDid && currentEntityDid !== binding.entityDid) {\n throw new Error('This flow was connected in a different workspace. Reconnect Xero to use it here.');\n }\n\n const invoiceId = String(inputs.InvoiceID || '').trim();\n if (!invoiceId) {\n throw new Error('InvoiceID is required; work items usually supply it from invoice.create completion.');\n }\n // The flow binding is the source; a work item minted before the binding\n // existed may still carry its own account, and settles with it.\n const accountId = (binding.bankAccountId || '').trim() || String(inputs.AccountID || '').trim();\n if (!accountId) {\n throw new Error(\"Pick the bank account in this flow's Xero connection before running this action.\");\n }\n\n if (!Number.isFinite(inputs.Amount) || inputs.Amount <= 0) {\n throw new Error('Amount must be a positive number.');\n }\n\n const date = String(inputs.Date || '').trim() || new Date().toISOString().slice(0, 10);\n\n // Composio's XERO_CREATE_PAYMENT flattens what Xero's HTTP API nests:\n // top-level `InvoiceID` / `AccountID`, not `Invoice: { InvoiceID }` /\n // `Account: { AccountID }`. See integrations-reference rule: mirror\n // Composio's arg names verbatim.\n const args: Record<string, unknown> = {\n InvoiceID: invoiceId,\n AccountID: accountId,\n Date: date,\n Amount: inputs.Amount,\n };\n // A block-level org overrides the one on the flow binding; blank uses it.\n const tenantId = String(inputs.tenant_id || '').trim() || (binding.tenantId || '').trim();\n if (tenantId) args.tenant_id = tenantId;\n if (inputs.Reference) args.Reference = inputs.Reference;\n if (typeof inputs.CurrencyRate === 'number' && Number.isFinite(inputs.CurrencyRate)) {\n args.CurrencyRate = inputs.CurrencyRate;\n }\n\n const result = await svc.executeTool({\n toolSlug: XERO_CREATE_PAYMENT_SLUG,\n connectedAccountId: binding.connectedAccountId,\n arguments: args,\n });\n\n if (!result.successful) {\n throw new Error(result.error || 'Xero payment creation failed');\n }\n\n const envelope = result.data as any;\n const payment = envelope?.Payments?.[0] || envelope?.data?.Payments?.[0] || envelope?.payment || envelope || {};\n const paymentId = String(payment.PaymentID || payment.paymentID || payment.id || '');\n const amount = typeof payment.Amount === 'number' ? payment.Amount : Number(payment.Amount) || inputs.Amount;\n const status = String(payment.Status || 'AUTHORISED');\n const reference = String(payment.Reference || inputs.Reference || '');\n\n return {\n output: {\n paymentId,\n invoiceId,\n amount,\n date,\n reference,\n status,\n },\n events: paymentId ? [{ name: 'payment.created', payload: { paymentId, invoiceId, amount, reference } }] : undefined,\n };\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('bid', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n if (!inputs.surveyStarted) return [];\n\n const collectionId = String(inputs.collectionId || '').trim();\n const role = String(inputs.role || '').trim();\n const roleLabel = role === 'evaluation_agent' || role === 'ea' ? 'Evaluator' : role ? 'Contributor' : 'Selected at runtime';\n\n return [\n {\n key: 'applicationStatus',\n label: 'Application Status',\n before: 'None',\n after: 'Pending',\n changeType: 'replace',\n severity: 'info',\n },\n {\n key: 'role',\n label: 'Role',\n before: 'None',\n after: roleLabel,\n changeType: role ? 'replace' : 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'surveyAnswers',\n label: 'Survey Answers',\n before: 'None',\n after: 'Submitted at runtime',\n changeType: 'replace',\n },\n ];\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nconst USDC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\n// maxAmounts are carried in base/micro units (6 decimals) — see\n// EvaluateBidFlowDetail.buildMaxAmounts. Divide for human display in the diff.\nconst DECIMALS = 6;\n\nfunction formatCoin(coin: { denom: string; amount: string }): string {\n const denom = coin.denom === USDC_DENOM ? 'USDC' : coin.denom === 'uixo' ? 'IXO' : coin.denom;\n const rawAmount = Number(coin.amount);\n const displayAmount = Number.isFinite(rawAmount) ? String(rawAmount / Math.pow(10, DECIMALS)) : String(coin.amount);\n return `${displayAmount} ${denom}`;\n}\n\nregisterDiffResolver('evaluateBid', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const bidId = String(inputs.bidId || '').trim();\n if (!bidId) return [];\n\n const decision = String(inputs.decision || '')\n .trim()\n .toLowerCase();\n const role = String(inputs.role || '').trim();\n const collectionId = String(inputs.collectionId || '').trim();\n const applicantDid = String(inputs.applicantDid || '').trim();\n\n const roleLower = role.toLowerCase();\n const isEvaluator = roleLower === 'evaluation_agent' || roleLower === 'ea';\n const roleLabel = isEvaluator ? 'Evaluator' : roleLower === 'service_agent' || roleLower === 'sa' ? 'Contributor' : role || 'Unknown';\n\n const isApprove = decision === 'approve';\n const isReject = decision === 'reject';\n const decisionLabel = isApprove ? 'Approve' : isReject ? 'Reject' : 'Not selected';\n const afterStatus = isApprove ? 'Approved' : isReject ? 'Rejected' : 'Pending';\n\n const results: DiffResult[] = [\n {\n key: 'bidStatus',\n label: 'Bid Status',\n before: 'Pending',\n after: afterStatus,\n changeType: decision ? 'replace' : 'unchanged',\n severity: isReject ? 'warning' : 'info',\n },\n {\n key: 'decision',\n label: 'Decision',\n before: 'None',\n after: decisionLabel,\n changeType: decision ? 'replace' : 'unchanged',\n },\n {\n key: 'applicantRole',\n label: 'Applicant Role',\n before: roleLabel,\n after: roleLabel,\n changeType: 'unchanged',\n },\n {\n key: 'bidId',\n label: 'Bid ID',\n before: bidId || 'Not selected',\n after: bidId || 'Not selected',\n changeType: 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n ];\n\n if (isEvaluator) {\n let amountsLabel = 'None';\n try {\n const parsed = typeof inputs.maxAmounts === 'string' ? JSON.parse(inputs.maxAmounts) : inputs.maxAmounts;\n if (Array.isArray(parsed) && parsed.length > 0) {\n amountsLabel = parsed.map((a: any) => formatCoin(a)).join(', ');\n }\n } catch {\n /* ignore */\n }\n\n results.push({\n key: 'maxAmounts',\n label: 'Max Amounts',\n before: 'None',\n after: amountsLabel,\n changeType: amountsLabel !== 'None' ? 'replace' : 'unchanged',\n });\n }\n\n if (isReject) {\n const reason = String(inputs.rejectReason || inputs.reason || '').trim();\n results.push({\n key: 'reason',\n label: 'Rejection Reason',\n before: 'None',\n after: reason || 'Not provided',\n changeType: reason ? 'replace' : 'unchanged',\n severity: 'warning',\n });\n }\n\n if (applicantDid) {\n results.push({\n key: 'applicant',\n label: 'Applicant',\n before: applicantDid,\n after: applicantDid,\n changeType: 'unchanged',\n });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('claim', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n if (!inputs.claimStarted) return [];\n\n const collectionId = String(inputs.collectionId || '').trim();\n const deedDid = String(inputs.deedDid || '').trim();\n\n return [\n {\n key: 'claimStatus',\n label: 'Claim Status',\n before: 'None',\n after: 'Pending',\n changeType: 'replace',\n severity: 'info',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'deed',\n label: 'Deed',\n before: deedDid || 'Not configured',\n after: deedDid || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'surveyAnswers',\n label: 'Survey Answers',\n before: 'None',\n after: 'Submitted at runtime',\n changeType: 'replace',\n },\n ];\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\nimport { formatCoin } from '@/core/utils/numbers';\n\nregisterDiffResolver('evaluateClaim', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const claimId = String(inputs.claimId || '').trim();\n if (!claimId || inputs.alreadyEvaluated) return [];\n\n const decision = String(inputs.decision || '')\n .trim()\n .toLowerCase();\n const collectionId = String(inputs.collectionId || '').trim();\n const createUdid = Boolean(inputs.createUdid);\n\n const isApprove = decision === 'approve';\n const isReject = decision === 'reject';\n const isDispute = decision === 'dispute';\n const decisionLabel = isApprove ? 'Approve' : isReject ? 'Reject' : isDispute ? 'Dispute' : 'Not selected';\n const afterStatus = isApprove ? 'Approved' : isReject ? 'Rejected' : isDispute ? 'Disputed' : 'Pending';\n\n const results: DiffResult[] = [\n {\n key: 'claimStatus',\n label: 'Claim Status',\n before: 'Pending',\n after: afterStatus,\n changeType: decision ? 'replace' : 'unchanged',\n severity: isReject || isDispute ? 'warning' : 'info',\n },\n {\n key: 'decision',\n label: 'Decision',\n before: 'None',\n after: decisionLabel,\n changeType: decision ? 'replace' : 'unchanged',\n },\n {\n key: 'claimId',\n label: 'Claim ID',\n before: claimId || 'Not selected',\n after: claimId || 'Not selected',\n changeType: 'unchanged',\n },\n {\n key: 'collection',\n label: 'Collection',\n before: collectionId || 'Not configured',\n after: collectionId || 'Not configured',\n changeType: 'unchanged',\n },\n {\n key: 'udidProof',\n label: 'UDID Proof',\n before: 'None',\n after: createUdid ? 'Will be generated' : 'Skipped',\n changeType: createUdid ? 'replace' : 'unchanged',\n },\n ];\n\n // Show payment info if configured\n let amountsLabel = 'None';\n try {\n const raw = typeof inputs.amount === 'string' ? JSON.parse(inputs.amount) : inputs.amount;\n if (Array.isArray(raw) && raw.length > 0) {\n amountsLabel = raw.map((a: any) => formatCoin(a)).join(', ');\n } else if (raw && typeof raw === 'object' && raw.denom) {\n amountsLabel = formatCoin(raw);\n }\n } catch {\n /* ignore */\n }\n results.push({\n key: 'payment',\n label: 'Payment',\n before: 'None',\n after: amountsLabel,\n changeType: amountsLabel !== 'None' ? 'replace' : 'unchanged',\n });\n\n if (isDispute) {\n const reason = String(inputs.reason || '').trim();\n results.push({\n key: 'reason',\n label: 'Dispute Reason',\n before: 'None',\n after: reason || 'Not provided',\n changeType: reason ? 'replace' : 'unchanged',\n severity: reason ? 'warning' : 'info',\n });\n }\n\n // Show outcome status if template exists\n if (inputs.outcomeComplete !== undefined) {\n results.push({\n key: 'outcome',\n label: 'Outcome Template',\n before: 'None',\n after: inputs.outcomeComplete ? 'Completed' : 'Not completed',\n changeType: inputs.outcomeComplete ? 'replace' : 'unchanged',\n severity: inputs.outcomeComplete ? 'info' : 'warning',\n });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\nimport { parseAttendeesField } from './eventCreate.types';\n\n/**\n * Diff resolver for `qi/calendar.event.create`.\n *\n * Create actions have no \"before\" state — every change is an `add`.\n * See integrations-plan.md §9 for the diff pattern.\n */\nregisterDiffResolver('qi/googlecalendar.event.create-self', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const attendees = parseAttendeesField(String(inputs.attendees || ''));\n const calendarId = String(inputs.calendar_id || '').trim() || 'primary';\n\n const results: DiffResult[] = [\n {\n key: 'summary',\n label: 'Title',\n before: null,\n after: String(inputs.summary || '').trim() || '(no title)',\n changeType: 'add',\n },\n {\n key: 'start_datetime',\n label: 'Start',\n before: null,\n after: String(inputs.start_datetime || '').trim() || '(required — set start time)',\n changeType: 'add',\n },\n ];\n\n const end = String(inputs.end_datetime || '').trim();\n if (end) {\n results.push({\n key: 'end_datetime',\n label: 'End',\n before: null,\n after: end,\n changeType: 'add',\n });\n }\n\n const timezone = String(inputs.timezone || '').trim();\n if (timezone) {\n results.push({\n key: 'timezone',\n label: 'Timezone',\n before: null,\n after: timezone,\n changeType: 'add',\n });\n }\n\n const location = String(inputs.location || '').trim();\n if (location) {\n results.push({\n key: 'location',\n label: 'Location',\n before: null,\n after: location,\n changeType: 'add',\n });\n }\n\n if (attendees.length > 0) {\n results.push({\n key: 'attendees',\n label: 'Attendees',\n before: null,\n after: attendees.join(', '),\n changeType: 'add',\n });\n }\n\n results.push({\n key: 'calendar_id',\n label: 'Calendar',\n before: null,\n after: calendarId,\n changeType: 'add',\n });\n\n const description = String(inputs.description || '').trim();\n if (description) {\n results.push({\n key: 'description',\n label: 'Description',\n before: null,\n after: description.length > 120 ? description.slice(0, 117) + '...' : description,\n changeType: 'add',\n });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\nimport { parseAttendeesField } from './eventCreate.types';\nimport { CALENDAR_EVENT_GET_SLUG } from './eventUpdate';\n\n/**\n * Diff resolver for `qi/calendar.event.update`.\n *\n * Fetches the current event via `GOOGLECALENDAR_EVENTS_GET` to populate the\n * \"before\" column. If the fetch fails (auth, network, missing event) we fall\n * back to `before: null` and still render the intended changes — the slider\n * stays unlocked by the flow detail component, which owns validation.\n * See integrations-plan.md §9 and gotchas §5.\n */\nregisterDiffResolver('qi/googlecalendar.event.update-self', {\n resolver: async (inputs: Record<string, any>, ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const connection = inputs.connection || {};\n const connectedAccountId = connection.connectedAccountId;\n const eventId = String(inputs.event_id || '').trim();\n const calendarId = String(inputs.calendar_id || '').trim() || 'primary';\n\n let before: any = null;\n if (connectedAccountId && eventId && ctx.handlers?.integrations?.fetchCurrentState) {\n try {\n const current = await ctx.handlers.integrations.fetchCurrentState({\n toolSlug: CALENDAR_EVENT_GET_SLUG,\n connectedAccountId,\n arguments: { event_id: eventId, calendar_id: calendarId },\n });\n // The GET tool wraps the event under `data` in the envelope. Some\n // transports unwrap it, so accept both shapes.\n before = current?.data || current || null;\n } catch {\n before = null;\n }\n }\n\n const results: DiffResult[] = [];\n\n const afterSummary = String(inputs.summary || '').trim();\n results.push({\n key: 'summary',\n label: 'Title',\n before: before?.summary ?? null,\n after: afterSummary || null,\n changeType: diffChange(before?.summary, afterSummary),\n });\n\n const afterStart = String(inputs.start_datetime || '').trim();\n const beforeStart = before?.start?.dateTime || before?.start?.date || null;\n results.push({\n key: 'start_datetime',\n label: 'Start',\n before: beforeStart,\n after: afterStart || null,\n changeType: diffChange(beforeStart, afterStart),\n });\n\n const afterEnd = String(inputs.end_datetime || '').trim();\n const beforeEnd = before?.end?.dateTime || before?.end?.date || null;\n if (afterEnd || beforeEnd) {\n results.push({\n key: 'end_datetime',\n label: 'End',\n before: beforeEnd,\n after: afterEnd || null,\n changeType: diffChange(beforeEnd, afterEnd),\n });\n }\n\n const afterLocation = String(inputs.location || '').trim();\n if (afterLocation || before?.location) {\n results.push({\n key: 'location',\n label: 'Location',\n before: before?.location ?? null,\n after: afterLocation || null,\n changeType: diffChange(before?.location, afterLocation),\n });\n }\n\n const afterAttendees = parseAttendeesField(String(inputs.attendees || ''));\n const beforeAttendees: string[] = Array.isArray(before?.attendees) ? before.attendees.map((a: any) => a?.email).filter(Boolean) : [];\n if (afterAttendees.length > 0 || beforeAttendees.length > 0) {\n const beforeStr = beforeAttendees.join(', ');\n const afterStr = afterAttendees.join(', ');\n results.push({\n key: 'attendees',\n label: 'Attendees',\n before: beforeStr || null,\n after: afterStr || null,\n changeType: diffChange(beforeStr, afterStr),\n });\n }\n\n const afterDescription = String(inputs.description || '').trim();\n if (afterDescription || before?.description) {\n const clip = (s: string | undefined | null) => (s && s.length > 120 ? s.slice(0, 117) + '...' : s ?? null);\n results.push({\n key: 'description',\n label: 'Description',\n before: clip(before?.description),\n after: clip(afterDescription) ?? null,\n changeType: diffChange(before?.description, afterDescription),\n });\n }\n\n return results;\n },\n});\n\nfunction diffChange(beforeVal: unknown, afterVal: unknown): DiffResult['changeType'] {\n const b = beforeVal === undefined || beforeVal === null ? '' : String(beforeVal).trim();\n const a = afterVal === undefined || afterVal === null ? '' : String(afterVal).trim();\n if (b === a) return 'unchanged';\n if (!b && a) return 'add';\n if (b && !a) return 'remove';\n return 'replace';\n}\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\n/**\n * Diff resolver for `qi/xero.contact.create` — create actions have no before state.\n */\nregisterDiffResolver('qi/xero.contact.create', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const results: DiffResult[] = [\n {\n key: 'Name',\n label: 'Name',\n before: null,\n after: String(inputs.Name || '').trim() || '(required)',\n changeType: 'add',\n },\n ];\n\n const fields: Array<[keyof typeof inputs, string]> = [\n ['EmailAddress', 'Email'],\n ['phone_number', 'Phone'],\n ['mobile_number', 'Mobile'],\n ['Website', 'Website'],\n ['TaxNumber', 'Tax number'],\n ['AccountNumber', 'Account number'],\n ['DefaultCurrency', 'Default currency'],\n ];\n\n for (const [key, label] of fields) {\n const v = String(inputs[key] || '').trim();\n if (v) {\n results.push({ key: String(key), label, before: null, after: v, changeType: 'add' });\n }\n }\n\n const roles: string[] = [];\n if (inputs.IsCustomer) roles.push('Customer');\n if (inputs.IsSupplier) roles.push('Supplier');\n if (roles.length > 0) {\n results.push({ key: 'role', label: 'Role', before: null, after: roles.join(' + '), changeType: 'add' });\n }\n\n if (inputs.tenant_id) {\n results.push({ key: 'tenant_id', label: 'Xero org', before: null, after: String(inputs.tenant_id), changeType: 'add' });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('qi/xero.invoice.create', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const results: DiffResult[] = [\n {\n key: 'Type',\n label: 'Type',\n before: null,\n after: String(inputs.Type || 'ACCREC').toUpperCase() === 'ACCPAY' ? 'ACCPAY (bill)' : 'ACCREC (sale)',\n changeType: 'add',\n },\n {\n key: 'Status',\n label: 'Status',\n before: null,\n after: String(inputs.Status || 'DRAFT'),\n changeType: 'add',\n },\n ];\n\n const contact = String(inputs.ContactID || '').trim() || String(inputs.ContactName || '').trim();\n if (contact) {\n results.push({\n key: 'Contact',\n label: 'Contact',\n before: null,\n after: contact,\n changeType: 'add',\n });\n }\n\n // LineItems is structured — manual rows or iterative binding. We report\n // the count and totals best-effort without resolving refs (the diff runs\n // in config context where we may not have runtime output yet).\n let lineItemSummary = '(required)';\n let totalAmount = 0;\n const lineItems = (inputs as any).LineItems;\n if (lineItems && typeof lineItems === 'object') {\n if (lineItems.mode === 'manual' && Array.isArray(lineItems.rows)) {\n lineItemSummary = `${lineItems.rows.length} item${lineItems.rows.length === 1 ? '' : 's'}`;\n totalAmount = lineItems.rows.reduce((sum: number, row: any) => {\n const qty = Number(row?.Quantity) || 0;\n const price = Number(row?.UnitAmount) || 0;\n return sum + qty * price;\n }, 0);\n } else if (lineItems.mode === 'iterative') {\n lineItemSummary = lineItems.source ? `per item from ${String(lineItems.source).slice(0, 80)}` : '(source not picked)';\n }\n }\n results.push({\n key: 'LineItems',\n label: 'Line items',\n before: null,\n after: lineItemSummary,\n changeType: 'add',\n });\n\n if (totalAmount > 0) {\n const currency = String(inputs.CurrencyCode || '').trim();\n results.push({\n key: 'Total',\n label: 'Total (est.)',\n before: null,\n after: currency ? `${totalAmount.toFixed(2)} ${currency}` : totalAmount.toFixed(2),\n changeType: 'add',\n });\n }\n\n if (inputs.DueDate) {\n results.push({ key: 'DueDate', label: 'Due', before: null, after: String(inputs.DueDate), changeType: 'add' });\n }\n if (inputs.Reference) {\n results.push({ key: 'Reference', label: 'Reference', before: null, after: String(inputs.Reference), changeType: 'add' });\n }\n if (inputs.tenant_id) {\n results.push({ key: 'tenant_id', label: 'Xero org', before: null, after: String(inputs.tenant_id), changeType: 'add' });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\nregisterDiffResolver('qi/xero.payment.create', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const results: DiffResult[] = [];\n\n const invoiceId = String(inputs.InvoiceID || '').trim();\n if (invoiceId) {\n results.push({\n key: 'InvoiceID',\n label: 'Invoice',\n before: null,\n after: invoiceId,\n changeType: 'add',\n });\n }\n\n const accountId = String(inputs.AccountID || '').trim();\n if (accountId) {\n results.push({\n key: 'AccountID',\n label: 'Bank account',\n before: null,\n after: accountId,\n changeType: 'add',\n });\n }\n\n const amountRaw = String(inputs.Amount ?? '').trim();\n if (amountRaw) {\n const n = Number(amountRaw);\n results.push({\n key: 'Amount',\n label: 'Amount',\n before: null,\n after: Number.isFinite(n) ? n.toFixed(2) : amountRaw,\n changeType: 'add',\n });\n }\n\n if (inputs.Date) {\n results.push({ key: 'Date', label: 'Date', before: null, after: String(inputs.Date), changeType: 'add' });\n }\n if (inputs.Reference) {\n results.push({ key: 'Reference', label: 'Reference (tx hash)', before: null, after: String(inputs.Reference), changeType: 'add' });\n }\n if (inputs.tenant_id) {\n results.push({ key: 'tenant_id', label: 'Xero org', before: null, after: String(inputs.tenant_id), changeType: 'add' });\n }\n\n return results;\n },\n});\n","import { registerDiffResolver } from '../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../diffTypes';\nimport { formatTokenAmount } from '../../../utils/tokenAmount';\n\n/** What a flow saved before multi-token support sent, and still sends. */\nconst FALLBACK_DENOM = 'uixo';\n\n/**\n * Resolve the token's symbol and decimals from the source wallet's balances so\n * the preview reads \"0.25 IXO\" rather than \"250000\". Falls back to the raw\n * base amount when the host cannot tell us the decimals — an unlabelled\n * `250000 uixo` is honest, `250000 IXO` would not be.\n */\nasync function describeToken(ctx: DiffResolverContext, walletAddress: string, denom: string): Promise<{ symbol?: string; exponent?: number }> {\n if (!walletAddress || !ctx.handlers?.getBalances) return {};\n try {\n const res = await ctx.handlers.getBalances(walletAddress);\n const match = (res?.data || []).find((b: { denom: string }) => b.denom === denom);\n return { symbol: match?.tokenName, exponent: match?.exponent };\n } catch {\n return {};\n }\n}\n\nregisterDiffResolver('qi/wallet.fund', {\n resolver: async (inputs: Record<string, any>, ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const address = String(inputs.address || '').trim();\n const amount = String(inputs.amount || '250000').trim();\n const denom = String(inputs.denom || '').trim() || FALLBACK_DENOM;\n const fromAddress = String(inputs.fromAddress || '').trim();\n\n const signerAddress = (() => {\n try {\n return ctx.handlers?.getCurrentUser?.()?.address || '';\n } catch {\n return '';\n }\n })();\n const source = fromAddress || signerAddress;\n const { symbol, exponent } = await describeToken(ctx, source, denom);\n\n return [\n {\n key: 'from',\n label: 'From',\n before: 'N/A',\n // Naming the mechanism matters: spending another wallet's tokens is an\n // authz exec, and the signer should see that before they slide.\n after: fromAddress ? `${fromAddress} (authorized send)` : source ? `${source} (your wallet)` : 'Your wallet',\n changeType: 'replace',\n severity: fromAddress ? 'warning' : 'info',\n },\n {\n key: 'recipient',\n label: 'Recipient',\n before: 'N/A',\n after: address || 'Pending wallet generation',\n changeType: address ? 'replace' : 'unchanged',\n },\n {\n key: 'amount',\n label: 'Amount',\n before: '0',\n after: exponent === undefined ? `${amount} ${denom}` : `${formatTokenAmount(amount, denom, exponent, symbol)} (${amount} ${denom})`,\n changeType: 'replace',\n severity: 'info',\n },\n ];\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\nimport { COLLECTION_LIFECYCLE_ACTION_TYPE } from './index';\nimport { CollectionStateEnum, type CollectionIntentOptions, type CollectionOperation, type CollectionPayment, type CollectionState, type Payments } from './types';\n\n/**\n * Per-operation diff resolver for the single `qi/collection.lifecycle` block\n * (IXO-2576). Because one block performs many operations, the resolver branches\n * on the `operation` runtime input and returns the relevant `DiffResult[]` for\n * that op only.\n *\n * `before` = the current on-chain `CollectionState`. The FlowDetail (IXO-2575)\n * is responsible for merging `runtime.output` (the latest `CollectionState`,\n * per IXO-2573 `output` always holds full on-chain truth) into the inputs it\n * feeds the diff system. We read it tolerantly from a few keys so the resolver\n * is robust to the exact wiring and NEVER throws on missing/empty `output`\n * (the pre-create state, where `output` is blank).\n *\n * `after` = the proposed values (the per-op runtime inputs).\n *\n * `refresh` is read-only and returns an empty diff so it does not block the UI.\n */\n\n// ---------------------------------------------------------------------------\n// Helpers — all defensive; none throw on missing/partial data.\n// ---------------------------------------------------------------------------\n\nconst STATE_LABELS: Record<number, string> = {\n [CollectionStateEnum.OPEN]: 'Open',\n [CollectionStateEnum.PAUSED]: 'Paused',\n [CollectionStateEnum.CLOSED]: 'Closed',\n};\n\nfunction stateLabel(value: unknown): string | null {\n if (value === undefined || value === null || value === '') return null;\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) return null;\n return STATE_LABELS[n] ?? `Unknown (${n})`;\n}\n\n/** Pull the current on-chain CollectionState out of the merged inputs. */\nfunction readCurrentState(inputs: Record<string, any>): Partial<CollectionState> {\n const candidate = inputs?.currentState ?? inputs?.__currentState ?? inputs?.__currentOutput ?? inputs?.currentOutput ?? inputs?.output ?? undefined;\n if (candidate && typeof candidate === 'object') return candidate as Partial<CollectionState>;\n return {};\n}\n\n/** Format a quota string for display; `0`/empty = unlimited. */\nfunction formatQuota(value: unknown): string {\n if (value === undefined || value === null || value === '') return 'Unlimited';\n const s = String(value).trim();\n if (s === '' || s === '0') return 'Unlimited';\n return s;\n}\n\nfunction toNumberOrNull(value: unknown): number | null {\n if (value === undefined || value === null || value === '') return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction formatDate(value: unknown): string {\n if (value === undefined || value === null || value === '') return 'Not set';\n return String(value);\n}\n\nconst USDC_IBC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\n\n/**\n * Normalise a coin to display units so before/after read consistently. The\n * \"after\" side carries display denoms (IXO/USDC) straight from the editor,\n * while the \"before\" side comes from on-chain state in base denoms (uixo,\n * ibc/…) and micro amounts — map those back to IXO/USDC ÷ 1e6.\n */\nfunction formatCoin(amount: string | undefined, denom: string | undefined): string {\n const rawAmount = amount ?? '?';\n if (denom === 'uixo') {\n const n = Number(rawAmount);\n return `${Number.isFinite(n) ? n / 1_000_000 : rawAmount} IXO`;\n }\n if (denom === USDC_IBC_DENOM || (denom ?? '').startsWith('ibc/')) {\n const n = Number(rawAmount);\n return `${Number.isFinite(n) ? n / 1_000_000 : rawAmount} USDC`;\n }\n return `${rawAmount} ${denom ?? ''}`.trim();\n}\n\n/** A compact human-readable summary of a single payment leg. */\nfunction summarisePaymentLeg(leg: CollectionPayment | undefined): string {\n if (!leg || typeof leg !== 'object') return 'None';\n const parts: string[] = [];\n const coins = Array.isArray(leg.amount) ? leg.amount : [];\n if (coins.length > 0) {\n parts.push(coins.map((c) => formatCoin(c?.amount, c?.denom)).join(', '));\n }\n if (Array.isArray(leg.cw20Payment) && leg.cw20Payment.length > 0) {\n parts.push(`${leg.cw20Payment.length} CW20`);\n }\n if (leg.contract_1155Payment) {\n parts.push('1155');\n }\n if (leg.account) {\n parts.push(`→ ${leg.account}`);\n }\n if (leg.isOraclePayment) {\n parts.push('(oracle)');\n }\n return parts.length > 0 ? parts.join(' ') : 'None';\n}\n\nfunction summarisePayments(payments: Payments | undefined): { submission: string; evaluation: string; approval: string; rejection: string } {\n const p = payments && typeof payments === 'object' ? payments : ({} as Payments);\n return {\n submission: summarisePaymentLeg(p.submission),\n evaluation: summarisePaymentLeg(p.evaluation),\n approval: summarisePaymentLeg(p.approval),\n rejection: summarisePaymentLeg(p.rejection),\n };\n}\n\nfunction summariseIntents(intents: CollectionIntentOptions | undefined): { allowed: string; timeout: string; payment: string } {\n const i = intents && typeof intents === 'object' ? intents : ({} as CollectionIntentOptions);\n return {\n allowed: i.allowed === undefined ? 'Not set' : i.allowed ? 'Allowed' : 'Disallowed',\n timeout: i.timeoutNs ? String(i.timeoutNs) : 'Not set',\n payment: summarisePaymentLeg(i.payment),\n };\n}\n\nfunction changeFor<T extends string | number | null>(before: T, after: T): DiffResult['changeType'] {\n if (before === after) return 'unchanged';\n if (before === null || before === undefined || before === '') return 'add';\n if (after === null || after === undefined || after === '') return 'remove';\n if (typeof before === 'number' && typeof after === 'number') {\n if (after > before) return 'increase';\n if (after < before) return 'decrease';\n }\n return 'replace';\n}\n\n// ---------------------------------------------------------------------------\n// Per-operation builders\n// ---------------------------------------------------------------------------\n\nfunction diffCreate(inputs: Record<string, any>): DiffResult[] {\n const results: DiffResult[] = [];\n\n if (inputs.entity) {\n results.push({ key: 'entity', label: 'Entity', before: null, after: String(inputs.entity), changeType: 'add' });\n }\n if (inputs.protocol) {\n results.push({ key: 'protocol', label: 'Protocol', before: null, after: String(inputs.protocol), changeType: 'add' });\n }\n\n results.push({\n key: 'state',\n label: 'State',\n before: null,\n after: stateLabel(inputs.state) ?? STATE_LABELS[CollectionStateEnum.OPEN],\n changeType: 'add',\n });\n\n results.push({\n key: 'startDate',\n label: 'Start Date',\n before: null,\n after: inputs.startDate ? String(inputs.startDate) : 'Not set',\n changeType: inputs.startDate ? 'add' : 'unchanged',\n });\n results.push({\n key: 'endDate',\n label: 'End Date',\n before: null,\n after: inputs.endDate ? String(inputs.endDate) : 'Not set',\n changeType: inputs.endDate ? 'add' : 'unchanged',\n });\n\n // Quota: editable, but historically immutable-feeling — flag it.\n results.push({\n key: 'quota',\n label: 'Quota',\n before: null,\n after: formatQuota(inputs.quota),\n changeType: 'add',\n severity: 'warning',\n unit: formatQuota(inputs.quota) === 'Unlimited' ? undefined : 'claims',\n });\n\n if (inputs.payments) {\n const after = summarisePayments(inputs.payments as Payments);\n (['submission', 'evaluation', 'approval', 'rejection'] as const).forEach((leg) => {\n if (after[leg] !== 'None') {\n results.push({\n key: `payments.${leg}`,\n label: `Payment — ${leg.charAt(0).toUpperCase()}${leg.slice(1)}`,\n before: null,\n after: after[leg],\n changeType: 'add',\n });\n }\n });\n }\n\n if (inputs.intents) {\n const after = summariseIntents(inputs.intents as CollectionIntentOptions);\n results.push({ key: 'intents.allowed', label: 'Intents — Allowed', before: null, after: after.allowed, changeType: 'add' });\n if (after.timeout !== 'Not set') {\n results.push({ key: 'intents.timeout', label: 'Intents — Timeout (ns)', before: null, after: after.timeout, changeType: 'add' });\n }\n if (after.payment !== 'None') {\n results.push({ key: 'intents.payment', label: 'Intents — Payment', before: null, after: after.payment, changeType: 'add' });\n }\n }\n\n return results;\n}\n\nfunction diffUpdateState(inputs: Record<string, any>, current: Partial<CollectionState>): DiffResult[] {\n const before = stateLabel(current.state);\n const after = stateLabel(inputs.state);\n return [\n {\n key: 'state',\n label: 'State',\n before: before ?? 'Unknown',\n after: after ?? 'Unchanged',\n changeType: changeFor(before, after),\n severity: after === STATE_LABELS[CollectionStateEnum.CLOSED] ? 'warning' : 'info',\n },\n ];\n}\n\nfunction diffUpdateDates(inputs: Record<string, any>, current: Partial<CollectionState>): DiffResult[] {\n const results: DiffResult[] = [];\n const beforeStart = formatDate(current.startDate);\n const afterStart = inputs.startDate !== undefined ? formatDate(inputs.startDate) : beforeStart;\n results.push({\n key: 'startDate',\n label: 'Start Date',\n before: beforeStart,\n after: afterStart,\n changeType: changeFor(beforeStart === 'Not set' ? null : beforeStart, afterStart === 'Not set' ? null : afterStart),\n });\n\n const beforeEnd = formatDate(current.endDate);\n const afterEnd = inputs.endDate !== undefined ? formatDate(inputs.endDate) : beforeEnd;\n results.push({\n key: 'endDate',\n label: 'End Date',\n before: beforeEnd,\n after: afterEnd,\n changeType: changeFor(beforeEnd === 'Not set' ? null : beforeEnd, afterEnd === 'Not set' ? null : afterEnd),\n });\n\n return results;\n}\n\nfunction diffUpdateQuota(inputs: Record<string, any>, current: Partial<CollectionState>): DiffResult[] {\n const beforeQuotaStr = formatQuota(current.quota);\n const afterQuotaStr = formatQuota(inputs.quota);\n\n // Numeric comparison for increase/decrease (treat unlimited as a sentinel, not numeric).\n const beforeNum = beforeQuotaStr === 'Unlimited' ? null : toNumberOrNull(current.quota);\n const afterNum = afterQuotaStr === 'Unlimited' ? null : toNumberOrNull(inputs.quota);\n\n let changeType: DiffResult['changeType'];\n if (beforeQuotaStr === afterQuotaStr) {\n changeType = 'unchanged';\n } else if (beforeNum !== null && afterNum !== null) {\n changeType = afterNum > beforeNum ? 'increase' : afterNum < beforeNum ? 'decrease' : 'replace';\n } else {\n changeType = 'replace';\n }\n\n // Warn if the requested quota would fall below the number of claims already\n // submitted — the chain rejects this (ErrCollectionQuotaBelowCount).\n const count = toNumberOrNull(current.count);\n const belowCount = afterNum !== null && count !== null && afterNum < count;\n\n return [\n {\n key: 'quota',\n label: 'Quota',\n before: beforeQuotaStr,\n after: belowCount ? `${afterQuotaStr} (below current count ${count} — chain will reject)` : afterQuotaStr,\n changeType,\n severity: belowCount ? 'critical' : 'info',\n unit: afterQuotaStr === 'Unlimited' ? undefined : 'claims',\n },\n ];\n}\n\nfunction diffUpdatePayments(inputs: Record<string, any>, current: Partial<CollectionState>): DiffResult[] {\n const before = summarisePayments(current.payments);\n const after = summarisePayments(inputs.payments as Payments);\n return (['submission', 'evaluation', 'approval', 'rejection'] as const).map((leg) => ({\n key: `payments.${leg}`,\n label: `Payment — ${leg.charAt(0).toUpperCase()}${leg.slice(1)}`,\n before: before[leg],\n after: after[leg],\n changeType: changeFor(before[leg] === 'None' ? null : before[leg], after[leg] === 'None' ? null : after[leg]),\n }));\n}\n\nfunction diffUpdateIntents(inputs: Record<string, any>, current: Partial<CollectionState>): DiffResult[] {\n const before = summariseIntents(current.intents);\n const after = summariseIntents(inputs.intents as CollectionIntentOptions);\n return [\n {\n key: 'intents.allowed',\n label: 'Intents — Allowed',\n before: before.allowed,\n after: after.allowed,\n changeType: changeFor(before.allowed === 'Not set' ? null : before.allowed, after.allowed === 'Not set' ? null : after.allowed),\n },\n {\n key: 'intents.timeout',\n label: 'Intents — Timeout (ns)',\n before: before.timeout,\n after: after.timeout,\n changeType: changeFor(before.timeout === 'Not set' ? null : before.timeout, after.timeout === 'Not set' ? null : after.timeout),\n },\n {\n key: 'intents.payment',\n label: 'Intents — Payment',\n before: before.payment,\n after: after.payment,\n changeType: changeFor(before.payment === 'None' ? null : before.payment, after.payment === 'None' ? null : after.payment),\n },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Registration\n// ---------------------------------------------------------------------------\n\nregisterDiffResolver(COLLECTION_LIFECYCLE_ACTION_TYPE, {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const safeInputs = inputs && typeof inputs === 'object' ? inputs : {};\n const operation = String(safeInputs.operation || '').trim() as CollectionOperation;\n const current = readCurrentState(safeInputs);\n\n switch (operation) {\n case 'create':\n return diffCreate(safeInputs);\n case 'updateState':\n return diffUpdateState(safeInputs, current);\n case 'updateDates':\n return diffUpdateDates(safeInputs, current);\n case 'updateQuota':\n return diffUpdateQuota(safeInputs, current);\n case 'updatePayments':\n return diffUpdatePayments(safeInputs, current);\n case 'updateIntents':\n return diffUpdateIntents(safeInputs, current);\n case 'refresh':\n // Read-only; no proposed change. Empty diff must not block the UI.\n return [];\n default:\n // Unknown / not-yet-selected operation — no diff.\n return [];\n }\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\nimport { COLLECTION_USERS_ACTION_TYPE, COLLECTION_USERS_MAX_GRANTS_PER_TX, collectionUsersBatchCount } from './index';\nimport type { CollectionUsersOp } from './types';\n\n/**\n * Per-operation diff resolver for the single `qi/collection.users` block\n * (IXO-2586). Because one block performs many operations, the resolver branches\n * on the `operation` runtime input and returns the relevant `DiffResult[]`.\n *\n * `add` → the new grant being conferred (collection, role, quota, grantee or\n * fan-out member count) — all `add` change types.\n * `revoke` → the grant being removed — a `remove` change, flagged `warning`.\n * `list` → read-only; empty diff so it does not block the UI.\n *\n * All helpers are defensive; none throw on missing/partial data.\n */\n\n// Agent quota is a finite per-agent claim/evaluation countdown the chain\n// requires to be > 0 (see x/claims/types/authz.go ValidateBasic). There is no\n// \"0 = unlimited\" sentinel for it, so we never render 0 as \"Unlimited\".\nfunction formatQuota(value: unknown): string {\n if (value === undefined || value === null) return '—';\n const s = String(value).trim();\n if (s === '') return '—';\n return s;\n}\n\nfunction roleLabel(value: unknown): string {\n const r = String(value || '')\n .trim()\n .toLowerCase();\n if (r === 'submit') return 'Submit (Contributor)';\n if (r === 'evaluate') return 'Evaluate (Evaluator)';\n return 'Unknown role';\n}\n\nconst IXO_DENOM = 'uixo';\nconst USDC_DENOM = 'ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B';\n// maxAmount coins are carried in base/micro units (6 decimals) — see\n// CollectionUsersFlowDetail.buildMaxAmounts and the consumer grant handler.\n// Divide for human display in the diff.\nconst DENOM_DECIMALS = 6;\n\n// A pasted list can hold hundreds of accounts; name the first few in the diff\n// and count the rest so the pre-sign summary stays readable.\nconst MAX_LISTED_ADDRESSES = 5;\n\nfunction formatCoin(value: unknown): string {\n const coin = value as { denom?: unknown; amount?: unknown };\n const denomValue = String(coin?.denom || '');\n const denom = denomValue === IXO_DENOM ? 'IXO' : denomValue === USDC_DENOM ? 'USDC' : denomValue;\n const rawAmount = Number(coin?.amount);\n const displayAmount = Number.isFinite(rawAmount) ? String(rawAmount / Math.pow(10, DENOM_DECIMALS)) : String(coin?.amount || '');\n return `${displayAmount} ${denom}`.trim();\n}\n\nfunction diffAdd(inputs: Record<string, any>): DiffResult[] {\n const results: DiffResult[] = [];\n const kind = String(inputs.granteeKind || 'user');\n const role = String(inputs.role || '')\n .trim()\n .toLowerCase();\n\n results.push({ key: 'role', label: 'Role', before: null, after: roleLabel(inputs.role), changeType: 'add' });\n\n if (inputs.collectionId) {\n results.push({ key: 'collectionId', label: 'Collection', before: null, after: String(inputs.collectionId), changeType: 'add' });\n }\n\n if (kind === 'address-list' || kind === 'group-members') {\n // A fan-out confers the identical grant on every account, so the diff shows\n // the count first (the number the user must sanity-check before signing),\n // then names them, then how many signatures it will take.\n const addresses =\n kind === 'address-list'\n ? (Array.isArray(inputs.granteeAddresses) ? inputs.granteeAddresses : []).map((a: any) => String(a || '').trim()).filter(Boolean)\n : (Array.isArray(inputs.members) ? inputs.members : []).map((m: any) => String(m?.address || '').trim()).filter(Boolean);\n\n results.push({\n key: 'grantees',\n label: kind === 'address-list' ? 'Grantees (pasted list)' : 'Grantees (fan-out)',\n before: null,\n after: kind === 'address-list' ? `${addresses.length} account${addresses.length === 1 ? '' : 's'}` : `${addresses.length} group member${addresses.length === 1 ? '' : 's'}`,\n changeType: 'add',\n severity: 'warning',\n });\n\n if (addresses.length > 0) {\n results.push({\n key: 'granteeAddresses',\n label: 'Accounts',\n before: null,\n after:\n addresses.length > MAX_LISTED_ADDRESSES\n ? `${addresses.slice(0, MAX_LISTED_ADDRESSES).join(', ')} … +${addresses.length - MAX_LISTED_ADDRESSES} more`\n : addresses.join(', '),\n changeType: 'add',\n });\n // How many times the user will be asked to sign — the one number a bulk\n // add can surprise them with, so it is stated before they start.\n const batches = collectionUsersBatchCount(addresses.length);\n results.push({\n key: 'transactions',\n label: 'Transactions to sign',\n before: null,\n after: `${batches} (up to ${COLLECTION_USERS_MAX_GRANTS_PER_TX} grants each)`,\n changeType: 'add',\n severity: batches > 1 ? 'warning' : undefined,\n });\n }\n } else {\n const label = kind === 'group-account' ? 'Grantee (group account)' : 'Grantee';\n results.push({ key: 'grantee', label, before: null, after: String(inputs.granteeAddress || '—'), changeType: 'add' });\n }\n\n results.push({\n key: 'agentQuota',\n label: 'Agent Quota',\n before: null,\n after: formatQuota(inputs.agentQuota),\n changeType: 'add',\n unit: formatQuota(inputs.agentQuota) === '—' ? undefined : 'claims',\n });\n\n if (role === 'evaluate') {\n const maxAmount = Array.isArray(inputs.maxAmount) ? inputs.maxAmount : [];\n results.push({\n key: 'maxAmount',\n label: 'Max Amounts',\n before: null,\n after: maxAmount.length > 0 ? maxAmount.map(formatCoin).join(', ') : 'None',\n changeType: maxAmount.length > 0 ? 'add' : 'unchanged',\n });\n }\n\n return results;\n}\n\nfunction diffRevoke(inputs: Record<string, any>): DiffResult[] {\n const results: DiffResult[] = [];\n results.push({ key: 'role', label: 'Role', before: roleLabel(inputs.role), after: null, changeType: 'remove', severity: 'warning' });\n if (inputs.collectionId) {\n results.push({ key: 'collectionId', label: 'Collection', before: String(inputs.collectionId), after: null, changeType: 'remove', severity: 'warning' });\n }\n results.push({\n key: 'grantee',\n label: 'Grantee',\n before: String(inputs.granteeAddress || '—'),\n after: null,\n changeType: 'remove',\n severity: 'warning',\n });\n return results;\n}\n\nregisterDiffResolver(COLLECTION_USERS_ACTION_TYPE, {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const safeInputs = inputs && typeof inputs === 'object' ? inputs : {};\n const operation = String(safeInputs.operation || '').trim() as CollectionUsersOp;\n\n switch (operation) {\n case 'add':\n return diffAdd(safeInputs);\n case 'revoke':\n return diffRevoke(safeInputs);\n case 'list':\n // Read-only; no proposed change. Empty diff must not block the UI.\n return [];\n default:\n return [];\n }\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\n/**\n * Diff preview for qi/carbon.harvest. Reads the resolved selection the\n * FlowDetail pushed via registerRuntimeInputs (`selectedBatches`) and renders a\n * per-batch claimable→wallet transfer plus a roll-up. Pure derivation — no\n * network. Empty selection → empty diff (the slider stays locked anyway).\n */\nregisterDiffResolver('qi/carbon.harvest', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const selected = Array.isArray(inputs.selectedBatches) ? inputs.selectedBatches : [];\n if (selected.length === 0) return [];\n\n const rows: DiffResult[] = selected.map((b: any) => {\n const claimable = Number(b?.claimable) || 0;\n return {\n key: `batch-${b?.id}`,\n label: b?.alsoKnownAs || b?.id || 'Batch',\n before: 0,\n after: claimable,\n changeType: 'increase',\n unit: 'CARBON',\n };\n });\n\n const total = selected.reduce((s: number, b: any) => s + (Number(b?.claimable) || 0), 0);\n rows.push({\n key: 'total',\n label: 'Total harvested to wallet',\n before: 0,\n after: total,\n changeType: 'increase',\n unit: 'CARBON',\n severity: 'info',\n });\n\n return rows;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\n/**\n * Diff preview for qi/carbon.retire. Reads the resolved selection the\n * FlowDetail pushed via registerRuntimeInputs (`selectedBatches`) and renders a\n * per-batch burn (available→retired) plus a roll-up flagged as a permanent,\n * irreversible change. Pure derivation — no network.\n */\nregisterDiffResolver('qi/carbon.retire', {\n resolver: async (inputs: Record<string, any>, _ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const selected = Array.isArray(inputs.selectedBatches) ? inputs.selectedBatches : [];\n if (selected.length === 0) return [];\n\n const rows: DiffResult[] = selected.map((b: any) => {\n const amount = Number(b?.amount) || 0;\n return {\n key: `batch-${b?.id}`,\n label: b?.alsoKnownAs || b?.id || 'Batch',\n before: amount,\n after: 0,\n changeType: 'decrease',\n unit: 'CARBON',\n severity: 'warning',\n };\n });\n\n const total = selected.reduce((s: number, b: any) => s + (Number(b?.amount) || 0), 0);\n rows.push({\n key: 'total',\n label: 'Total retired (permanent, irreversible)',\n before: total,\n after: 0,\n changeType: 'decrease',\n unit: 'CARBON',\n severity: 'critical',\n });\n\n return rows;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult, DiffResolverContext } from '../../diffTypes';\n\n/**\n * Diff preview for qi/entity.transfer. Reads the resolved selection the\n * FlowDetail pushed via registerRuntimeInputs (recipientDid + resolved\n * entityDid/ownerDid) and renders the single ownership change as a permanent,\n * irreversible replace. Pure derivation — no network.\n */\nregisterDiffResolver('qi/entity.transfer', {\n resolver: async (inputs: Record<string, any>, ctx: DiffResolverContext): Promise<DiffResult[]> => {\n const recipient = String(inputs.recipientDid || '').trim();\n if (!recipient) return [];\n\n const entityDid = String(inputs.entityDid || '').trim();\n const currentOwner = String(inputs.ownerDid || '').trim() || ctx.actorDid || 'current owner';\n\n const rows: DiffResult[] = [\n {\n key: 'owner',\n label: 'Owner',\n before: currentOwner,\n after: recipient,\n changeType: 'replace',\n severity: 'critical',\n },\n ];\n\n if (entityDid) {\n rows.push({\n key: 'entity',\n label: 'Entity',\n before: entityDid,\n after: entityDid,\n changeType: 'unchanged',\n severity: 'info',\n });\n }\n\n return rows;\n },\n});\n","import { registerDiffResolver } from '../../diffRegistry';\nimport type { DiffResult } from '../../diffTypes';\nimport { parseEvalRubricInputs } from '../evalRubric/types';\nimport { EVAL_ENGINE_ACTION_TYPE } from './index';\n\n/**\n * Signing preview for the merged \"Evaluation Engine\" block: the qi/eval.register rows (what\n * enabling the engine does + the evaluate-authz disclosure) followed by the qi/eval.rubric rows\n * (what rules are being published). Empty until a collection is bound, same as both parents.\n */\nregisterDiffResolver(EVAL_ENGINE_ACTION_TYPE, {\n resolver: async (inputs: Record<string, any>): Promise<DiffResult[]> => {\n const collectionId = String(inputs?.collectionId || '').trim();\n if (!collectionId) return [];\n const displayName = String(inputs?.displayName || '').trim();\n const rows: DiffResult[] = [\n { key: 'collection', label: 'Claim collection', before: null, after: displayName ? `${displayName} (${collectionId})` : collectionId, changeType: 'add' },\n { key: 'access', label: 'Evaluation Engine', before: null, after: 'Reads & evaluates this collection’s claims on your behalf', changeType: 'add' },\n {\n key: 'decisions',\n label: 'Decisions',\n before: null,\n after:\n inputs?.allowChainEvaluation === false\n ? 'Recorded only — nothing is submitted on chain'\n : inputs?.allowZeroPayoutApprovals === true\n ? 'Submitted on chain, including approvals that pay nothing — you grant the engine evaluator rights'\n : 'Submitted on chain, which releases payment — you grant the engine evaluator rights',\n changeType: 'add',\n },\n ];\n const { rubric } = parseEvalRubricInputs(inputs);\n if (rubric) {\n const rejectRules = rubric.gates?.length ?? 0;\n const scoredQuestions = rubric.scoring?.criteria?.length ?? 0;\n const humanChecks = rubric.review?.tasks?.length ?? 0;\n rows.push({\n key: 'rules',\n label: 'Rules',\n before: null,\n after: [plural(rejectRules, 'reject rule'), plural(scoredQuestions, 'scored question'), plural(humanChecks, 'human check')].join(' · '),\n changeType: 'add',\n });\n if (typeof rubric.scoring?.approveAt === 'number') {\n rows.push({ key: 'approveAt', label: 'Approved at a score of', before: null, after: `${Math.trunc(rubric.scoring.approveAt / 100)} / 100`, changeType: 'add' });\n }\n }\n return rows;\n },\n});\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AA4DvC,SAAS,eAA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A,IACF;AACA,WAAO;AAAA,EACT;AACF,CAAC;AAED,SAAS,OAAO,OAAe,MAAsB;AACnD,SAAO,GAAG,KAAK,IAAI,IAAI,GAAG,UAAU,IAAI,KAAK,GAAG;AAClD;","names":["record","record","USDC_DENOM","DECIMALS","output","missing","record","transactionHash","receipt","minted","responseDigest","lifecycle","output","claimId","BASELINE_OUTPUT","normalizeDecision","idempotencyKey","requiredString","SENSITIVE_PLAINTEXT_KEYS","SENSITIVE_PLAINTEXT_KEYS","transactionHash","collectionId","grantees","transactionHashes","requiredString","record","roleLabel","formatCoin","roleLabel","formatCoin","formatQuota","USDC_DENOM","formatCoin"]}