@ixo/editor 6.18.0 → 6.19.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/services/ucanService.ts","../src/core/lib/matrixDm.ts","../src/core/lib/warnOnce.ts","../src/core/lib/actionRegistry/registry.ts","../src/core/lib/actionRegistry/manifest.ts","../src/core/lib/actionRegistry/inputRequirements.ts","../src/core/lib/actionRegistry/canMapping.ts","../src/core/lib/actionRegistry/serviceCan.ts","../src/core/lib/actionRegistry/adapters.ts","../src/core/lib/xeroWorkItems.ts","../src/core/lib/actionRegistry/diffRegistry.ts","../src/core/lib/actionRegistry/actions/pod/domainIndexerLookup.ts","../src/core/lib/did.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/memberProposal.ts","../src/core/lib/actionRegistry/actions/governance/settingsProposal.ts","../src/core/lib/actionRegistry/actions/governance/_shared.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/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/surveySchema.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/domainCard/transformSurveyToCredentialSubject.ts","../src/core/lib/domainCard/buildVerifiableCredential.ts","../src/core/lib/domainCard/extractSurveyAnswersTemplate.ts","../src/core/lib/domainCard/buildLinkedEntityResource.ts","../src/core/lib/domainCard/defaultSurvey.ts","../src/core/lib/actionRegistry/actions/domainSign.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/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/types.ts","../src/core/lib/actionRegistry/actions/collection/collection.ts","../src/core/lib/actionRegistry/actions/collectionUsers/index.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/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/calendar/eventCreate.types.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/utils/numbers.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/types/baseUcan.ts","../src/core/lib/flowEngine/triggers.ts","../src/core/lib/flowEngine/referenceResolver.ts","../src/core/lib/flowEngine/versionManifest.ts","../src/core/lib/flowEngine/reconcile.ts","../src/core/lib/flowEngine/emitEvents.ts","../src/core/lib/flowEngine/utils.ts","../src/core/lib/flowEngine/runtime.ts","../src/core/lib/flowCompiler/resolveRefs.ts","../src/core/lib/flowEngine/authorization.ts","../src/core/lib/flowEngine/executor.ts","../src/core/lib/flowEngine/proof.ts","../src/core/lib/flowEngine/verifiedCompletion.ts","../src/core/lib/ucanDelegationStore.ts","../src/core/lib/invocationStore.ts","../src/core/lib/flowEngine/actionExecutor.ts","../src/core/lib/flowEngine/readBackReconciler.ts","../src/core/lib/flowEngine/blockPhase.ts","../src/core/lib/flowEngine/validateBlockConfig.ts","../src/core/lib/flowEngine/migration.ts","../src/core/lib/flowEngine/migrations/v0_3_to_v1_0_0.ts","../src/core/types/nodeContext.ts","../src/core/lib/flowCompiler/conditions.ts","../src/core/lib/flowCompiler/blockMapping.ts","../src/core/lib/flowCompiler/compiler.ts","../src/core/lib/flowCompiler/documentFragment.ts","../src/core/lib/flowCompiler/readFlow.ts","../src/core/lib/flowCompiler/mergeFlows.ts","../src/core/lib/flowCompiler/decompile.ts","../src/core/lib/flowCompiler/setup.ts","../src/core/lib/flowCompiler/hydrate.ts","../src/core/lib/flowAgent/store.ts","../src/core/lib/flowAgent/utils.ts","../src/core/lib/flowAgent/policy.ts","../src/core/lib/flowAgent/commands.ts","../src/core/lib/flowAgent/context.ts","../src/core/lib/flowAgent/lease.ts","../src/core/lib/flowAgent/state.ts","../src/core/lib/flowAgent/actionExecutionPolicy.ts","../src/core/lib/flowAgent/orchestrator.ts","../src/core/lib/flowAgent/execution.ts","../src/core/lib/flowAgent/service.ts"],"sourcesContent":["/**\n * UCAN Service using @ixo/ucan directly\n *\n * This service provides a high-level API for:\n * - Creating and managing delegations (CAR format)\n * - Creating and validating invocations\n * - Executing actions with invocation-based authorization\n *\n * The host app only needs to provide the signer (private key) after PIN decryption.\n * All UCAN operations are performed using @ixo/ucan directly.\n */\n\nimport {\n createDelegation as ucanCreateDelegation,\n createInvocation as ucanCreateInvocation,\n serializeDelegation,\n serializeInvocation,\n parseDelegation,\n parseSigner,\n signerFromMnemonic,\n type Signer,\n type Delegation,\n type Capability as UcantoCapability,\n type SupportedDID,\n} from '@ixo/ucan';\n\nimport type { UcanDelegationStore } from '../lib/ucanDelegationStore';\nimport type { InvocationStore } from '../lib/invocationStore';\nimport type {\n StoredDelegation,\n StoredInvocation,\n UcanCapability,\n InvocationResult,\n ExecutionWithInvocationResult,\n DelegationChainValidationResult,\n FindProofsResult,\n CreateRootDelegationParams,\n CreateDelegationParams,\n CreateInvocationParams,\n} from '../types/ucan';\n\n/**\n * Signer session scope type\n */\nexport type SignerSessionScope = 'session' | 'operation';\n\n/**\n * Signer session returned by createSignerSession\n */\nexport interface SignerSessionInfo {\n sessionId: string;\n did: string;\n publicKey: string;\n keyId: string;\n expiresAt: number;\n scope: SignerSessionScope;\n}\n\n/**\n * Handler functions for getting signers from the host application\n * The host app handles PIN decryption and key management\n */\nexport interface UcanServiceHandlers {\n /**\n * Get a signer for the given DID after PIN verification\n * The host app decrypts the private key using the PIN\n *\n * @returns The private key in multibase format (for parseSigner)\n * @deprecated Prefer createSignerSession for better security\n */\n getPrivateKey?: (params: { did: string; didType: 'entity' | 'user'; entityRoomId?: string; pin: string }) => Promise<string>;\n\n /**\n * Get a signer from mnemonic (alternative to getPrivateKey)\n * The host app retrieves and decrypts the mnemonic using the PIN\n *\n * @returns The mnemonic phrase\n * @deprecated Prefer createSignerSession for better security\n */\n getMnemonic?: (params: { did: string; didType: 'entity' | 'user'; entityRoomId?: string; pin: string }) => Promise<string>;\n\n // ============================================================================\n // Handle-based signer session handlers (preferred approach)\n // ============================================================================\n\n /**\n * Create a signer session that can be used for multiple sign operations.\n * The host app keeps the key material secure; the editor only receives an opaque handle.\n *\n * @param params.scope - 'session' for multiple operations, 'operation' for one-time use\n * @param params.ttlSeconds - Time-to-live for session scope (default: 300, max: 3600)\n */\n createSignerSession?: (params: {\n did: string;\n didType: 'entity' | 'user';\n entityRoomId?: string;\n pin: string;\n scope: SignerSessionScope;\n ttlSeconds?: number;\n }) => Promise<SignerSessionInfo>;\n\n /**\n * Sign data using an existing session.\n * For 'operation' scope, the session is automatically invalidated after this call.\n */\n signWithSession?: (params: { sessionId: string; data: string; algorithm?: 'Ed25519' }) => Promise<{\n signature: string;\n algorithm: 'Ed25519';\n keyId: string;\n }>;\n\n /**\n * Release a session before it expires.\n * Safe to call on already-released or expired sessions.\n */\n releaseSignerSession?: (params: { sessionId: string }) => Promise<{\n released: boolean;\n reason?: string;\n }>;\n\n // ============================================================================\n // Deprecated high-level session helpers.\n // Prefer BlocknoteHandlers.createDelegation/createInvocation plus the\n // createSignerSession/signWithSession/releaseSignerSession contract.\n // ============================================================================\n\n /**\n * Create a delegation directly in the host app.\n * The host handles all signing internally using session-based signing.\n * @deprecated Use createDelegation on BlocknoteHandlers instead.\n */\n createDelegationWithSession?: (params: {\n sessionId: string;\n audience: string;\n capabilities: Array<{\n can: string;\n with: string;\n nb?: Record<string, unknown>;\n }>;\n proofs?: string[];\n expiration?: number;\n }) => Promise<{\n cid: string;\n delegation: string;\n }>;\n\n /**\n * Create an invocation directly in the host app.\n * The host handles all signing internally using session-based signing.\n * @deprecated Use createInvocation on BlocknoteHandlers instead.\n */\n createInvocationWithSession?: (params: {\n sessionId: string;\n audience: string;\n capability: {\n can: string;\n with: string;\n nb?: Record<string, unknown>;\n };\n proofs: string[];\n }) => Promise<{\n cid: string;\n invocation: string;\n }>;\n}\n\n/**\n * Configuration for UcanService\n */\nexport interface UcanServiceConfig {\n delegationStore: UcanDelegationStore;\n invocationStore: InvocationStore;\n handlers: UcanServiceHandlers;\n flowOwnerDid: string;\n flowUri: string;\n}\n\n/**\n * UCAN Service interface\n */\nexport interface UcanService {\n // Delegation operations\n createRootDelegation: (params: CreateRootDelegationParams) => Promise<StoredDelegation>;\n createDelegation: (params: CreateDelegationParams) => Promise<StoredDelegation>;\n revokeDelegation: (cid: string) => void;\n getDelegation: (cid: string) => StoredDelegation | null;\n getAllDelegations: () => StoredDelegation[];\n getRootDelegation: () => StoredDelegation | null;\n\n // Invocation operations\n createAndValidateInvocation: (params: CreateInvocationParams, flowId: string, blockId?: string) => Promise<InvocationResult>;\n executeWithInvocation: <T>(\n params: CreateInvocationParams,\n action: () => Promise<T>,\n flowId: string,\n blockId?: string\n ) => Promise<ExecutionWithInvocationResult & { actionResult?: T }>;\n\n // Validation\n validateDelegationChain: (audienceDid: string, capability: UcanCapability) => Promise<DelegationChainValidationResult>;\n findValidProofs: (audienceDid: string, capability: UcanCapability) => Promise<FindProofsResult>;\n\n // Parsing\n parseDelegationFromStore: (cid: string) => Promise<Delegation | null>;\n\n // Utility\n isConfigured: () => boolean;\n}\n\n/**\n * Convert a DID string to SupportedDID type (did:ixo:* or did:key:*)\n */\nfunction toSupportedDID(did: string): SupportedDID | undefined {\n if (did.startsWith('did:ixo:') || did.startsWith('did:key:')) {\n return did as SupportedDID;\n }\n return undefined;\n}\n\nfunction normalizeDid(did: string): string {\n if (did.startsWith('did:')) return did;\n if (did.startsWith('ixo1')) return `did:ixo:${did}`;\n if (!did.startsWith('@did-')) return did;\n\n const [localpart] = did.split(':');\n const parts = localpart.split('-');\n if (parts.length < 3 || parts[0] !== '@did') return did;\n return `did:${parts[1]}:${parts.slice(2).join('-')}`;\n}\n\nfunction toInvocationAudienceDID(did: string): SupportedDID {\n const normalized = normalizeDid(did);\n const supported = toSupportedDID(normalized);\n if (!supported) {\n throw new Error(`Invalid DID \"${did}\", must start with 'did:'`);\n }\n return supported;\n}\n\n/**\n * Ability type for UCAN capabilities (format: \"namespace/action\" or \"*\")\n */\ntype Ability = `${string}/${string}` | '*';\n\n/**\n * Resource type for UCAN capabilities (format: \"scheme:path\")\n */\ntype Resource = `${string}:${string}`;\n\n/**\n * Convert UcanCapability to UcantoCapability with proper type format\n * Ucanto requires `can` to be Ability and `with` to be Resource\n */\nfunction toUcantoCapabilities(capabilities: UcanCapability[]): UcantoCapability[] {\n return capabilities.map((cap) => ({\n can: cap.can as Ability,\n with: cap.with as Resource,\n ...(cap.nb && { nb: cap.nb }),\n }));\n}\n\n/**\n * Get a signer from the handlers.\n */\nasync function getSigner(handlers: UcanServiceHandlers, did: string, didType: 'entity' | 'user', entityRoomId: string | undefined, pin: string): Promise<Signer> {\n const normalizedDid = normalizeDid(did);\n const supportedDid = toSupportedDID(normalizedDid);\n\n if (handlers.getPrivateKey) {\n const privateKey = await handlers.getPrivateKey({ did: normalizedDid, didType, entityRoomId, pin });\n return parseSigner(privateKey, supportedDid);\n }\n\n if (handlers.getMnemonic) {\n const mnemonic = await handlers.getMnemonic({ did: normalizedDid, didType, entityRoomId, pin });\n const result = await signerFromMnemonic(mnemonic, supportedDid);\n return result.signer;\n }\n\n throw new Error('No signer handler configured (need getPrivateKey or getMnemonic)');\n}\n\n/**\n * Generate a CID-like identifier from delegation\n */\nfunction getCidFromDelegation(delegation: Delegation): string {\n return delegation.cid.toString();\n}\n\n/**\n * Create a UCAN service instance\n */\nexport const createUcanService = (config: UcanServiceConfig): UcanService => {\n const { delegationStore, invocationStore, handlers, flowOwnerDid } = config;\n\n // Cache for parsed delegations\n const delegationCache = new Map<string, Delegation>();\n\n const isConfigured = (): boolean => {\n const hasSessionHandlers = !!(handlers.createSignerSession && handlers.signWithSession);\n const hasLegacyHandlers = !!(handlers.getPrivateKey || handlers.getMnemonic);\n return hasSessionHandlers || hasLegacyHandlers;\n };\n\n const parseDelegationFromStore = async (cid: string): Promise<Delegation | null> => {\n if (delegationCache.has(cid)) {\n return delegationCache.get(cid)!;\n }\n\n const stored = delegationStore.get(cid);\n if (!stored || !stored.delegation) {\n return null;\n }\n\n try {\n const delegation = await parseDelegation(stored.delegation);\n delegationCache.set(cid, delegation);\n return delegation;\n } catch {\n return null;\n }\n };\n\n const getProofDelegations = async (proofCids: string[]): Promise<Delegation[]> => {\n const proofs: Delegation[] = [];\n for (const cid of proofCids) {\n const delegation = await parseDelegationFromStore(cid);\n if (delegation) {\n proofs.push(delegation);\n }\n }\n return proofs;\n };\n\n /**\n * Resolve proof CIDs to their serialized CAR strings (base64) by reading\n * the local delegation store. Used when the host's session-based UCAN\n * handlers want CARs (so they don't need access to the editor's store).\n */\n const getProofCars = async (proofCids: string[]): Promise<string[]> => {\n const cars: string[] = [];\n for (const cid of proofCids) {\n const stored = delegationStore.get(cid);\n if (stored && stored.delegation) {\n cars.push(stored.delegation);\n }\n }\n return cars;\n };\n\n const createRootDelegation = async (params: CreateRootDelegationParams): Promise<StoredDelegation> => {\n const { flowOwnerDid: ownerDid, issuerType, entityRoomId, flowUri: uri, pin } = params;\n const normalizedOwnerDid = normalizeDid(ownerDid);\n\n const capabilities: UcantoCapability[] = [{ can: 'flow/*', with: uri as `${string}:${string}` }];\n\n // Prefer the host's session-based UCAN handler when available — same\n // fallback pattern as createDelegation / createAndValidateInvocation.\n if (handlers.createSignerSession && handlers.createDelegationWithSession) {\n const session = await handlers.createSignerSession({\n did: normalizedOwnerDid,\n didType: issuerType,\n entityRoomId,\n pin,\n scope: 'operation',\n });\n\n const result = await handlers.createDelegationWithSession({\n sessionId: session.sessionId,\n audience: normalizedOwnerDid,\n capabilities: capabilities as Array<{ can: string; with: string; nb?: Record<string, unknown> }>,\n proofs: [],\n });\n\n const storedDelegation: StoredDelegation = {\n cid: result.cid,\n delegation: result.delegation,\n issuerDid: normalizedOwnerDid,\n audienceDid: normalizedOwnerDid,\n capabilities: capabilities as UcanCapability[],\n createdAt: Date.now(),\n format: 'car',\n proofCids: [],\n };\n\n delegationStore.set(storedDelegation);\n delegationStore.setRootCid(result.cid);\n return storedDelegation;\n }\n\n // Legacy path — editor builds the signer locally from a mnemonic/key.\n const signer = await getSigner(handlers, ownerDid, issuerType, entityRoomId, pin);\n\n const delegation = await ucanCreateDelegation({\n issuer: signer,\n audience: toInvocationAudienceDID(normalizedOwnerDid),\n capabilities,\n proofs: [],\n });\n\n const serialized = await serializeDelegation(delegation);\n const cid = getCidFromDelegation(delegation);\n\n const storedDelegation: StoredDelegation = {\n cid,\n delegation: serialized,\n issuerDid: normalizedOwnerDid,\n audienceDid: normalizedOwnerDid,\n capabilities: capabilities as UcanCapability[],\n createdAt: Date.now(),\n format: 'car',\n proofCids: [],\n };\n\n delegationStore.set(storedDelegation);\n delegationStore.setRootCid(cid);\n\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n const createDelegation = async (params: CreateDelegationParams): Promise<StoredDelegation> => {\n const { issuerDid, issuerType, entityRoomId, audience, capabilities, proofs = [], expiration, pin } = params;\n const normalizedIssuerDid = normalizeDid(issuerDid);\n const normalizedAudienceDid = normalizeDid(audience);\n\n // Use proofs exactly as the caller provided them. Empty array = the\n // delegation is self-issued (no parent in the chain) — this is correct\n // for capabilities targeting external services where the issuer's DID\n // is itself the trust root. Flow-rooted delegations must be assembled\n // by the caller (e.g. AuthorizationTab passes [rootCid, ...]).\n const proofCids = proofs;\n\n // Prefer the host's session-based UCAN handler when available — it\n // signs without ever exposing the mnemonic to the editor. Falls back\n // to the legacy mnemonic-based path for older host implementations.\n if (handlers.createSignerSession && handlers.createDelegationWithSession) {\n const session = await handlers.createSignerSession({\n did: normalizedIssuerDid,\n didType: issuerType,\n entityRoomId,\n pin,\n scope: 'operation',\n });\n\n const proofCars = await getProofCars(proofCids);\n\n const result = await handlers.createDelegationWithSession({\n sessionId: session.sessionId,\n audience: normalizedAudienceDid,\n capabilities: capabilities as Array<{ can: string; with: string; nb?: Record<string, unknown> }>,\n proofs: proofCars,\n expiration: expiration ? Math.floor(expiration / 1000) : undefined,\n });\n\n const storedDelegation: StoredDelegation = {\n cid: result.cid,\n delegation: result.delegation,\n issuerDid: normalizedIssuerDid,\n audienceDid: normalizedAudienceDid,\n capabilities,\n expiration,\n createdAt: Date.now(),\n format: 'car',\n proofCids,\n };\n\n delegationStore.set(storedDelegation);\n return storedDelegation;\n }\n\n // Legacy path: editor signs locally using getMnemonic/getPrivateKey.\n const signer = await getSigner(handlers, issuerDid, issuerType, entityRoomId, pin);\n\n const proofDelegations = await getProofDelegations(proofCids);\n\n const delegation = await ucanCreateDelegation({\n issuer: signer,\n audience: toInvocationAudienceDID(normalizedAudienceDid),\n capabilities: toUcantoCapabilities(capabilities),\n proofs: proofDelegations,\n expiration: expiration ? Math.floor(expiration / 1000) : undefined,\n });\n\n const serialized = await serializeDelegation(delegation);\n const cid = getCidFromDelegation(delegation);\n\n const storedDelegation: StoredDelegation = {\n cid,\n delegation: serialized,\n issuerDid: normalizedIssuerDid,\n audienceDid: normalizedAudienceDid,\n capabilities,\n expiration,\n createdAt: Date.now(),\n format: 'car',\n proofCids,\n };\n\n delegationStore.set(storedDelegation);\n\n delegationCache.set(cid, delegation);\n\n return storedDelegation;\n };\n\n const revokeDelegation = (cid: string): void => {\n delegationStore.remove(cid);\n delegationCache.delete(cid);\n };\n\n const getDelegation = (cid: string): StoredDelegation | null => {\n return delegationStore.get(cid);\n };\n\n const getAllDelegations = (): StoredDelegation[] => {\n return delegationStore.getAll();\n };\n\n const getRootDelegation = (): StoredDelegation | null => {\n return delegationStore.getRoot();\n };\n\n const findValidProofs = async (audienceDid: string, capability: UcanCapability): Promise<FindProofsResult> => {\n const delegations = delegationStore.getByAudience(audienceDid);\n\n if (delegations.length === 0) {\n // Check if actor is the root audience (flow owner)\n const root = delegationStore.getRoot();\n if (root && normalizeDid(root.audienceDid) === normalizeDid(audienceDid)) {\n return { found: true, proofCids: [root.cid] };\n }\n return { found: false, error: 'No delegations found for actor' };\n }\n\n for (const delegation of delegations) {\n const covers = delegation.capabilities.some((c) => {\n if (c.can === capability.can && c.with === capability.with) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (capability.can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (capability.with.startsWith(prefix)) return true;\n }\n return false;\n });\n\n if (covers) {\n if (delegation.expiration && delegation.expiration < Date.now()) {\n continue;\n }\n const proofCids = [delegation.cid, ...delegation.proofCids];\n return { found: true, proofCids };\n }\n }\n\n return { found: false, error: 'No valid delegation found for capability' };\n };\n\n const validateDelegationChain = async (audienceDid: string, capability: UcanCapability): Promise<DelegationChainValidationResult> => {\n const proofsResult = await findValidProofs(audienceDid, capability);\n\n if (!proofsResult.found || !proofsResult.proofCids) {\n return { valid: false, error: proofsResult.error };\n }\n\n const proofChain: StoredDelegation[] = [];\n for (const cid of proofsResult.proofCids) {\n const delegation = delegationStore.get(cid);\n if (!delegation) {\n return { valid: false, error: `Proof delegation ${cid} not found` };\n }\n proofChain.push(delegation);\n }\n\n // Validate chain integrity\n for (let i = 0; i < proofChain.length - 1; i++) {\n const current = proofChain[i];\n const parent = proofChain[i + 1];\n\n if (normalizeDid(parent.audienceDid) !== normalizeDid(current.issuerDid)) {\n return {\n valid: false,\n error: `Chain broken: ${parent.cid} audience (${parent.audienceDid}) != ${current.cid} issuer (${current.issuerDid})`,\n };\n }\n }\n\n // Validate root — but only for flow-scoped capabilities. Non-flow\n // capabilities target external services with their own trust anchors;\n // the editor cannot meaningfully validate them locally and shouldn't\n // assume the flow owner is the relevant root issuer.\n const isFlowScoped = capability.can === 'flow/*' || capability.can.startsWith('flow/');\n if (isFlowScoped) {\n const root = proofChain[proofChain.length - 1];\n if (normalizeDid(root.issuerDid) !== normalizeDid(flowOwnerDid)) {\n return { valid: false, error: `Root issuer ${root.issuerDid} is not flow owner ${flowOwnerDid}` };\n }\n }\n\n return { valid: true, proofChain };\n };\n\n const createAndValidateInvocation = async (params: CreateInvocationParams, _flowId: string, _blockId?: string): Promise<InvocationResult> => {\n const { invokerDid, invokerType, entityRoomId, capability, proofs, pin } = params;\n const normalizedInvokerDid = normalizeDid(invokerDid);\n\n const validation = await validateDelegationChain(normalizedInvokerDid, capability);\n if (!validation.valid) {\n return {\n cid: '',\n invocation: '',\n valid: false,\n error: validation.error,\n };\n }\n\n // Audience defaults to the flow owner (in-flow invocations) but can be\n // overridden when invoking against an external service such as a\n // UCAN-gated worker (where audience must equal the worker's did:web).\n const audience = normalizeDid(params.audience ?? flowOwnerDid);\n\n // Prefer the host's session-based UCAN handler when available.\n if (handlers.createSignerSession && handlers.createInvocationWithSession) {\n try {\n const session = await handlers.createSignerSession({\n did: normalizedInvokerDid,\n didType: invokerType,\n entityRoomId,\n pin,\n scope: 'operation',\n });\n\n const proofCars = await getProofCars(proofs);\n\n const result = await handlers.createInvocationWithSession({\n sessionId: session.sessionId,\n audience,\n capability: {\n can: capability.can,\n with: capability.with,\n ...(capability.nb && { nb: capability.nb }),\n },\n proofs: proofCars,\n });\n\n return {\n cid: result.cid,\n invocation: result.invocation,\n valid: true,\n };\n } catch (err) {\n return {\n cid: '',\n invocation: '',\n valid: false,\n error: err instanceof Error ? err.message : 'Failed to create invocation via session',\n };\n }\n }\n\n // Legacy path — editor builds the signer locally from a mnemonic/key.\n const signer = await getSigner(handlers, invokerDid, invokerType, entityRoomId, pin);\n const proofDelegations = await getProofDelegations(proofs);\n\n const ucantoCapability: UcantoCapability = {\n can: capability.can as Ability,\n with: capability.with as Resource,\n ...(capability.nb && { nb: capability.nb }),\n };\n\n const invocation = await ucanCreateInvocation({\n issuer: signer,\n audience,\n capability: ucantoCapability,\n proofs: proofDelegations,\n });\n\n const serialized = await serializeInvocation(invocation);\n const built = await invocation.buildIPLDView();\n const cid = built.cid.toString();\n\n return {\n cid,\n invocation: serialized,\n valid: true,\n };\n };\n\n const executeWithInvocation = async <T>(\n params: CreateInvocationParams,\n action: () => Promise<T>,\n flowId: string,\n blockId?: string\n ): Promise<ExecutionWithInvocationResult & { actionResult?: T }> => {\n const invocationResult = await createAndValidateInvocation(params, flowId, blockId);\n\n if (!invocationResult.valid) {\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: invocationResult.error,\n };\n }\n\n if (invocationStore.hasBeenInvoked(invocationResult.cid)) {\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: 'Invocation has already been used (replay attack prevented)',\n };\n }\n\n try {\n const actionResult = await action();\n\n const storedInvocation: StoredInvocation = {\n cid: invocationResult.cid,\n invocation: invocationResult.invocation,\n invokerDid: params.invokerDid,\n capability: params.capability,\n executedAt: Date.now(),\n flowId,\n blockId,\n result: 'success',\n proofCids: params.proofs,\n };\n invocationStore.add(storedInvocation);\n\n return {\n success: true,\n invocationCid: invocationResult.cid,\n result: actionResult,\n actionResult,\n };\n } catch (error) {\n const storedInvocation: StoredInvocation = {\n cid: invocationResult.cid,\n invocation: invocationResult.invocation,\n invokerDid: params.invokerDid,\n capability: params.capability,\n executedAt: Date.now(),\n flowId,\n blockId,\n result: 'failure',\n error: error instanceof Error ? error.message : 'Unknown error',\n proofCids: params.proofs,\n };\n invocationStore.add(storedInvocation);\n\n return {\n success: false,\n invocationCid: invocationResult.cid,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n };\n\n return {\n createRootDelegation,\n createDelegation,\n revokeDelegation,\n getDelegation,\n getAllDelegations,\n getRootDelegation,\n createAndValidateInvocation,\n executeWithInvocation,\n validateDelegationChain,\n findValidProofs,\n parseDelegationFromStore,\n isConfigured,\n };\n};\n","import type { MatrixClient } from 'matrix-js-sdk';\n\n/**\n * Extract the homeserver domain from a Matrix user ID.\n * e.g. \"@user:matrix.ixo.world\" → \"matrix.ixo.world\"\n */\nexport function getHomeserver(matrixClient: MatrixClient): string {\n const userId = matrixClient.getUserId();\n if (!userId) throw new Error('Matrix client has no user ID');\n const idx = userId.indexOf(':');\n if (idx === -1) throw new Error(`Invalid Matrix user ID: ${userId}`);\n return userId.substring(idx + 1);\n}\n\n/**\n * Convert a DID to a Matrix user ID.\n * e.g. \"did:ixo:abc\" → \"@did-ixo-abc:matrix.ixo.world\"\n *\n * This mirrors the reverse mapping in AssignmentTab:\n * matrixUserId.split(':')[0].replace('@', '').replace(/-/g, ':')\n */\nexport function didToMatrixUserId(did: string, homeserver: string): string {\n const localpart = did.replace(/:/g, '-');\n return `@${localpart}:${homeserver}`;\n}\n\n/**\n * Find an existing DM room with the target user, or create one.\n * Uses the `m.direct` account data to track DM room associations.\n */\nexport async function findOrCreateDMRoom(matrixClient: MatrixClient, targetUserId: string): Promise<string> {\n // Check existing DM rooms via m.direct account data\n try {\n const directEvent = (matrixClient as any).getAccountData('m.direct');\n const directContent: Record<string, string[]> = directEvent?.getContent() || {};\n const existingRooms = directContent[targetUserId];\n\n if (existingRooms && existingRooms.length > 0) {\n // Return the first existing DM room\n return existingRooms[0];\n }\n } catch {\n // No m.direct data yet, proceed to create\n }\n\n // Create a new DM room\n const response = await matrixClient.createRoom({\n is_direct: true,\n invite: [targetUserId],\n preset: 'trusted_private_chat' as any,\n initial_state: [],\n });\n\n const roomId = response.room_id;\n\n // Update m.direct account data to include the new room\n try {\n const directEvent = (matrixClient as any).getAccountData('m.direct');\n const directContent: Record<string, string[]> = directEvent?.getContent() || {};\n const updatedContent = {\n ...directContent,\n [targetUserId]: [...(directContent[targetUserId] || []), roomId],\n };\n await (matrixClient as any).setAccountData('m.direct', updatedContent);\n } catch (error) {\n console.warn('[MatrixDM] Failed to update m.direct account data:', error);\n }\n\n return roomId;\n}\n\n/**\n * Send a text message to a Matrix room.\n */\nexport async function sendMatrixMessage(matrixClient: MatrixClient, roomId: string, message: string): Promise<void> {\n await matrixClient.sendEvent(roomId, 'm.room.message' as any, {\n msgtype: 'm.text',\n body: message,\n });\n}\n\n/**\n * Send a direct message to a user identified by DID.\n * Finds or creates a DM room and sends the message.\n */\nexport async function sendDirectMessage(matrixClient: MatrixClient, targetDid: string, message: string): Promise<{ roomId: string }> {\n const homeserver = getHomeserver(matrixClient);\n const targetUserId = didToMatrixUserId(targetDid, homeserver);\n const roomId = await findOrCreateDMRoom(matrixClient, targetUserId);\n await sendMatrixMessage(matrixClient, roomId, message);\n return { roomId };\n}\n","const seen = new Set<string>();\n\n/**\n * Log a warning at most once per key for the lifetime of the module.\n * Used to surface configuration problems (malformed inputs/trigger JSON,\n * unresolvable references) without flooding the console on every render\n * or reconcile pass.\n */\nexport function warnOnce(key: string, message: string): void {\n if (seen.has(key)) return;\n seen.add(key);\n console.warn(message);\n}\n\n/** Test hook — clears the dedupe set. */\nexport function __resetWarnOnce(): void {\n seen.clear();\n}\n","import type { ActionDefinition, ActionEventDefinition, OutputSchemaField } from './types';\nimport { warnOnce } from '../warnOnce';\n\nconst actions = new Map<string, ActionDefinition>();\n\n/** Stable name of the universal completion event every step emits. */\nexport const STEP_COMPLETED_EVENT_NAME = 'step.completed';\n\n/**\n * The universal completion event. Every step emits this when it completes, on\n * top of whatever domain events its action declares. It exists so that:\n * - any step can be sequenced off a predecessor (\"run after X\") via a\n * `(X, step.completed)` trigger, regardless of the source action's events;\n * - every completion is auditable (a run record is always written).\n */\nexport const STEP_COMPLETED_EVENT: ActionEventDefinition = {\n name: STEP_COMPLETED_EVENT_NAME,\n displayName: 'Completed',\n description: 'Fires when this step is completed.',\n payloadSchema: [],\n};\n\n/** Maps legacy action type names to their canonical namespaced names. */\nconst ACTION_TYPE_ALIASES: Record<string, string> = {\n bid: 'qi/bid.submit',\n claim: 'qi/claim.submit',\n evaluateBid: 'qi/bid.evaluate',\n evaluateClaim: 'qi/claim.evaluate',\n 'email.send': 'qi/email.send',\n 'http.request': 'qi/http.request',\n 'form.submit': 'qi/form.submit',\n 'human.form.submit': 'qi/human.form.submit',\n 'human.checkbox.set': 'qi/human.checkbox.set',\n 'notification.push': 'qi/notification.push',\n 'proposal.create': 'qi/proposal.create',\n 'proposal.vote': 'qi/proposal.vote',\n 'protocol.select': 'qi/protocol.select',\n 'domain.sign': 'qi/domain.sign',\n 'domain.card-preview': 'qi/domain.card-preview',\n 'credential.store': 'qi/credential.store',\n // POD setup flow — camelCase orchestrator labels → canonical action types\n DomainIndexerLookup: 'qi/pod.domain-indexer-lookup',\n DomainSingleSelection: 'qi/pod.domain-single-selection',\n EntitySingleSelection: 'qi/pod.entity-single-selection',\n MemberMultiSelect: 'qi/pod.member-multi-select',\n governanceConfig: 'qi/pod.governance-config',\n listDomainFlows: 'qi/pod.list-domain-flows',\n 'matrix.dm': 'qi/matrix.dm',\n};\n\nconst aliases = new Map<string, string>(Object.entries(ACTION_TYPE_ALIASES));\n\n/** Resolves a legacy action type name to its canonical namespaced name. */\nexport function resolveActionType(type: string): string {\n return aliases.get(type) ?? type;\n}\n\nexport function registerAction<TInputs extends Record<string, any> = Record<string, any>>(definition: ActionDefinition<TInputs>): void {\n actions.set(definition.type, definition as ActionDefinition);\n}\n\nexport function getAction(type: string): ActionDefinition | undefined {\n return actions.get(resolveActionType(type));\n}\n\nexport function getAllActions(): ActionDefinition[] {\n return Array.from(actions.values());\n}\n\n/**\n * Whether an action type is a repeatable ('many') capability — a standing\n * block that can fire any number of times and never latches to a terminal\n * Done. Unknown types default to `false` (one-shot). See\n * {@link ActionDefinition.cardinality}.\n */\nexport function isRepeatableAction(type: string | undefined | null): boolean {\n if (!type) return false;\n return getAction(type)?.cardinality === 'many';\n}\n\n/** All (alias → canonical type) pairs, for manifest generation and consistency checks. */\nexport function getAliasEntries(): Array<[string, string]> {\n return Array.from(aliases.entries());\n}\n\nexport function hasAction(type: string): boolean {\n return actions.has(resolveActionType(type));\n}\n\n/** Look up an action by its UCAN `can` ability string, e.g., \"bid/submit\". */\nexport function getActionByCan(can: string): ActionDefinition | undefined {\n for (const action of actions.values()) {\n if (action.can === can) return action;\n }\n return undefined;\n}\n\n/**\n * Resolve the event vocabulary for a specific block given its template inputs.\n *\n * Prefers the action's `getDynamicEvents(inputs)` resolver (so actions can\n * derive event schemas from configured state — e.g. claim.submit deriving the\n * event payload from the picked collection's survey). Falls back to the static\n * `events` array when no resolver is defined.\n *\n * `inputs` may be a pre-parsed object, a JSON string, or missing entirely;\n * this helper absorbs parse failures so callers don't need to.\n */\nexport function getEventsForBlock(action: ActionDefinition | undefined, inputs: unknown): ActionEventDefinition[] {\n if (!action) return [];\n\n let events: ActionEventDefinition[];\n if (action.getDynamicEvents) {\n const parsed = normalizeInputs(inputs);\n try {\n const dynamic = action.getDynamicEvents(parsed) || [];\n events = action.dynamicResolutionMode === 'replace' ? dynamic : mergeByKey(action.events || [], dynamic, (event) => event.name);\n } catch (error) {\n // A crashing resolver must not break the picker or compiler.\n warnOnce(\n `dynamic-events:${action.type}`,\n `[flow-config] action ${action.type}: getDynamicEvents threw (${error instanceof Error ? error.message : String(error)}); no events resolved`\n );\n events = [];\n }\n } else {\n events = action.events || [];\n }\n\n // Every step also emits the universal completion event, so any step can be a\n // \"run after X\" trigger source. Skip if the action already declares one with\n // that name (don't double-list).\n if (events.some((event) => event.name === STEP_COMPLETED_EVENT_NAME)) {\n return events;\n }\n return [...events, STEP_COMPLETED_EVENT];\n}\n\n/**\n * Resolve the output schema for a specific block. Symmetric to\n * `getEventsForBlock`: prefers `getDynamicOutputSchema(inputs)` when defined\n * so actions can derive their output shape from configured state (e.g.\n * `qi/claim.submit` exposing `output.surveyAnswers.<question>` once a\n * collection is picked). Falls back to the static `outputSchema`.\n */\nexport function getOutputSchemaForBlock(action: ActionDefinition | undefined, inputs: unknown): OutputSchemaField[] {\n if (!action) return [];\n if (action.getDynamicOutputSchema) {\n const parsed = normalizeInputs(inputs);\n try {\n const dynamic = action.getDynamicOutputSchema(parsed) || [];\n if (action.dynamicResolutionMode === 'replace') return dynamic;\n return mergeByKey(action.outputSchema || [], dynamic, (field) => field.path);\n } catch (error) {\n warnOnce(\n `dynamic-output-schema:${action.type}`,\n `[flow-config] action ${action.type}: getDynamicOutputSchema threw (${error instanceof Error ? error.message : String(error)}); using static schema`\n );\n return action.outputSchema || [];\n }\n }\n return action.outputSchema || [];\n}\n\n/**\n * Merge a static baseline with dynamic entries, deduping by key — the\n * dynamic entry wins on conflict, baseline order is preserved. Actions that\n * genuinely need to hide the baseline set `dynamicResolutionMode: 'replace'`.\n */\nfunction mergeByKey<T>(baseline: T[], dynamic: T[], keyOf: (item: T) => string): T[] {\n const dynamicKeys = new Set(dynamic.map(keyOf));\n return [...baseline.filter((item) => !dynamicKeys.has(keyOf(item))), ...dynamic];\n}\n\nfunction normalizeInputs(inputs: unknown): Record<string, any> {\n if (!inputs) return {};\n if (typeof inputs === 'object') return inputs as Record<string, any>;\n if (typeof inputs === 'string') {\n try {\n const parsed = JSON.parse(inputs || '{}');\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n warnOnce(`inputs-normalize:${inputs}`, `[flow-config] block inputs are not valid JSON; treated as empty`);\n return {};\n }\n }\n return {};\n}\n","import type { ActionDefinition, ActionEventDefinition, OutputSchemaField } from './types';\nimport { getAliasEntries, getAllActions } from './registry';\n\n/**\n * Serializable proof declaration: custom `validate` functions can't cross a\n * JSON boundary, so they are represented as `{ kind: 'custom' }` — consumers\n * know a proof exists and is enforced kernel-side, without its logic.\n */\nexport type ManifestProofDeclaration = { kind: 'none' } | { kind: 'fields'; fields: string[] } | { kind: 'custom' };\n\nexport interface ActionManifestEntry {\n type: string;\n /** Legacy names that resolve to this canonical type. */\n aliases: string[];\n can?: string;\n sideEffect: boolean;\n defaultRequiresConfirmation: boolean;\n requiredCapability?: string;\n proof: ManifestProofDeclaration;\n /** JSON Schema for the action's inputs, when declared. */\n inputSchema?: object;\n /** Static output schema. Actions with dynamic schemas also set hasDynamicOutputSchema. */\n outputSchema?: OutputSchemaField[];\n /** Static event vocabulary. Actions with dynamic events also set hasDynamicEvents. */\n events?: Array<Pick<ActionEventDefinition, 'name' | 'displayName' | 'description' | 'payloadSchema'>>;\n hasDynamicEvents: boolean;\n hasDynamicOutputSchema: boolean;\n eligibleForEventTrigger: boolean;\n /**\n * True when the action defines `getMissingInputs` — conditional requiredness\n * that `inputSchema.required` cannot express (like a custom proof, the\n * function itself can't cross the JSON boundary). Out-of-process consumers\n * should treat the schema's `required` as a lower bound for such actions;\n * in-process consumers get the full logic via `getMissingActionInputs`.\n */\n hasCustomInputValidation: boolean;\n}\n\nexport interface ActionManifest {\n /** Schema version of the manifest format itself. */\n manifestVersion: '1';\n actions: ActionManifestEntry[];\n}\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\n/**\n * Generate the machine-readable action contract from the live registry.\n *\n * This is the single artifact external actors (the flow-manager oracle,\n * third-party agentic Oracle actors) implement against, replacing\n * hand-maintained copies of input contracts. It is emitted to\n * `dist/action-manifest.json` at build time and also callable at runtime\n * from `@ixo/editor/core`.\n */\nexport function generateActionManifest(): ActionManifest {\n const aliasEntries = getAliasEntries();\n const aliasesByType = new Map<string, string[]>();\n for (const [alias, canonical] of aliasEntries) {\n const list = aliasesByType.get(canonical) || [];\n list.push(alias);\n aliasesByType.set(canonical, list);\n }\n\n const actions = getAllActions()\n .map((action): ActionManifestEntry => {\n const entry: ActionManifestEntry = {\n type: action.type,\n aliases: (aliasesByType.get(action.type) || []).sort(),\n sideEffect: action.sideEffect,\n defaultRequiresConfirmation: action.defaultRequiresConfirmation,\n proof: serializeProof(action),\n hasDynamicEvents: !!action.getDynamicEvents,\n hasDynamicOutputSchema: !!action.getDynamicOutputSchema,\n eligibleForEventTrigger: !!action.eligibleForEventTrigger,\n hasCustomInputValidation: !!action.getMissingInputs,\n };\n if (action.can) entry.can = action.can;\n if (action.requiredCapability) entry.requiredCapability = action.requiredCapability;\n if (action.inputSchema) entry.inputSchema = action.inputSchema;\n if (action.outputSchema) entry.outputSchema = action.outputSchema;\n if (action.events) {\n entry.events = action.events.map((event) => ({\n name: event.name,\n displayName: event.displayName,\n description: event.description,\n payloadSchema: event.payloadSchema,\n }));\n }\n return entry;\n })\n .sort((a, b) => a.type.localeCompare(b.type));\n\n return { manifestVersion: '1', actions };\n}\n","import { getAction } from './registry';\nimport { warnOnce } from '../warnOnce';\n\n/**\n * Required-input evaluation for action types — the machine-readable mirror of\n * the throw-preamble in each action's `run()`.\n *\n * External orchestrators (the flow-manager oracle, third-party agentic Oracle\n * actors) call {@link getMissingActionInputs} BEFORE queuing execution so a\n * missing input becomes a prompt to a human instead of a failed run. The\n * editor's registry is the single source of truth for requiredness: actions\n * with unconditional requirements derive from `inputSchema.required`; actions\n * whose requiredness depends on other inputs define\n * {@link ActionDefinition.getMissingInputs} next to their `run()`.\n *\n * Scope: presence only. A field can pass here (present, non-blank) and still\n * fail value validation (ranges, formats, duplicates) inside `run()` — `run()`\n * remains the authority on validity.\n */\n\n/**\n * Whether a value counts as \"missing\" for a required input: `null`/`undefined`,\n * a string that is blank after trimming, or an empty array. Objects and other\n * primitives (including `false` and `0`) count as present.\n */\nexport function isBlankInputValue(value: unknown): boolean {\n if (value == null) return true;\n if (typeof value === 'string') return value.trim().length === 0;\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n/**\n * Coerce an input that `run()` accepts as either an object or a JSON string\n * (e.g. `domainCardData`) into an object, or `undefined` when it is neither.\n */\nexport function parseMaybeJsonObject(value: unknown): Record<string, unknown> | undefined {\n if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record<string, unknown>;\n if (typeof value === 'string' && value.trim()) {\n try {\n const parsed = JSON.parse(value);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as Record<string, unknown>;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\nfunction dedupe(values: string[]): string[] {\n return Array.from(new Set(values.filter((value) => typeof value === 'string' && value.length > 0)));\n}\n\n/**\n * Names of the inputs still missing or blank for `actionType` given a\n * fully-merged inputs object (empty array = ready to execute, as far as\n * presence goes). Resolves legacy aliases through the registry; unknown or\n * alias-less action types report nothing missing.\n *\n * Prefers the action's `getMissingInputs` (conditional requiredness), falling\n * back to `inputSchema.required` with {@link isBlankInputValue} semantics.\n * A crashing `getMissingInputs` must not break an orchestrator tick: it is\n * absorbed (warn-once) and reports nothing missing, so the real error\n * surfaces from `run()` instead.\n */\nexport function getMissingActionInputs(actionType: string | undefined | null, inputs: Record<string, unknown> | undefined): string[] {\n if (!actionType) return [];\n const action = getAction(actionType);\n if (!action) return [];\n\n const merged = inputs ?? {};\n if (action.getMissingInputs) {\n try {\n return dedupe(action.getMissingInputs(merged) || []);\n } catch (error) {\n warnOnce(\n `missing-inputs:${action.type}`,\n `[flow-config] action ${action.type}: getMissingInputs threw (${error instanceof Error ? error.message : String(error)}); reporting no missing inputs`\n );\n return [];\n }\n }\n\n const schema = action.inputSchema as { required?: unknown } | undefined;\n const required = Array.isArray(schema?.required) ? schema.required.filter((name): name is string => typeof name === 'string') : [];\n return dedupe(required.filter((name) => isBlankInputValue(merged[name])));\n}\n","/**\n * Bidirectional mapping between UCAN `can` vocabulary and registry `type` strings.\n * Derived mechanically: strip \"qi/\", replace \".\" with \"/\".\n */\n\nconst CAN_TO_TYPE: Record<string, string> = {\n 'bid/submit': 'qi/bid.submit',\n 'bid/evaluate': 'qi/bid.evaluate',\n 'claim/submit': 'qi/claim.submit',\n 'claim/evaluate': 'qi/claim.evaluate',\n 'collection/lifecycle': 'qi/collection.lifecycle',\n 'collection/users': 'qi/collection.users',\n 'email/send': 'qi/email.send',\n 'notification/push': 'qi/notification.push',\n 'matrix/dm': 'qi/matrix.dm',\n 'proposal/create': 'qi/proposal.create',\n 'proposal/vote': 'qi/proposal.vote',\n 'governance/member-proposal': 'qi/governance.member-proposal',\n 'governance/settings-proposal': 'qi/governance.settings-proposal',\n 'governance.transaction/send-funds': 'qi/governance.transaction.send-funds',\n 'domain/card-preview': 'qi/domain.card-preview',\n 'domain/sign': 'qi/domain.sign',\n 'credential/store': 'qi/credential.store',\n 'http/request': 'qi/http.request',\n 'protocol/select': 'qi/protocol.select',\n 'human/checkbox': 'qi/human.checkbox.set',\n 'human/form': 'qi/human.form.submit',\n 'oracle/query': 'oracle',\n 'pod/domain-indexer-lookup': 'qi/pod.domain-indexer-lookup',\n 'pod/domain-single-selection': 'qi/pod.domain-single-selection',\n 'pod/entity-single-selection': 'qi/pod.entity-single-selection',\n 'pod/governance-config': 'qi/pod.governance-config',\n 'pod/member-multi-select': 'qi/pod.member-multi-select',\n 'pod/list-domain-flows': 'qi/pod.list-domain-flows',\n 'blueprint/workspace-start': 'qi/blueprint.workspace-start',\n 'blueprint/journey-resume': 'qi/blueprint.journey-resume',\n 'blueprint/guided-authoring': 'qi/blueprint.guided-authoring',\n 'blueprint/artifact-preview': 'qi/blueprint.artifact-preview',\n 'blueprint/artifact-save': 'qi/blueprint.artifact-save',\n 'blueprint/checklist-update': 'qi/blueprint.checklist-update',\n 'blueprint/phase-confirm': 'qi/blueprint.phase-confirm',\n 'blueprint/reviewer-assign': 'qi/blueprint.reviewer-assign',\n 'blueprint/review-submit': 'qi/blueprint.review-submit',\n 'blueprint/review-respond': 'qi/blueprint.review-respond',\n 'blueprint/release-compile': 'qi/blueprint.release-compile',\n 'blueprint/publish': 'qi/blueprint.publish',\n // Delegated integrations (author connects once, runners execute on their behalf)\n 'gmail.email/send': 'qi/gmail.email.send',\n 'outlook.email/send': 'qi/outlook.email.send',\n 'slack.message/send': 'qi/slack.message.send',\n 'googlecalendar.event/create': 'qi/googlecalendar.event.create',\n // Calendar integration (self-connected)\n 'calendar.event/create': 'qi/calendar.event.create',\n 'calendar.event/update': 'qi/calendar.event.update',\n 'calendar.event/list': 'qi/calendar.event.list',\n // Xero integration\n 'xero.contact/create': 'qi/xero.contact.create',\n 'xero.invoice/create': 'qi/xero.invoice.create',\n 'xero.invoice/list': 'qi/xero.invoice.list',\n 'xero.payment/create': 'qi/xero.payment.create',\n // Oracle / wallet / matrix lifecycle\n 'wallet/generate': 'qi/wallet.generate',\n 'wallet/fund': 'qi/wallet.fund',\n 'iid/create': 'qi/iid.create',\n 'matrix/register': 'qi/matrix.register',\n 'entity/createOracle': 'qi/entity.createOracle',\n 'sandbox/provision': 'qi/sandbox.provision',\n 'oracle/contract': 'qi/oracle.contract',\n 'oracle/storeSecrets': 'qi/oracle.storeSecrets',\n 'oracle/storeConfig': 'qi/oracle.storeConfig',\n 'oracle/configureOracle': 'qi/oracle.configureOracle',\n};\n\nconst TYPE_TO_CAN: Record<string, string> = Object.fromEntries(Object.entries(CAN_TO_TYPE).map(([can, type]) => [type, can]));\n\n/** Resolve a `can` ability string to the registry `type` string. */\nexport function canToType(can: string): string | undefined {\n return CAN_TO_TYPE[can];\n}\n\n/** Resolve a registry `type` string to the `can` ability string. */\nexport function typeToCan(type: string): string | undefined {\n return TYPE_TO_CAN[type];\n}\n\n/** Get all registered can↔type mappings. */\nexport function getAllCanMappings(): ReadonlyArray<{ can: string; type: string }> {\n return Object.entries(CAN_TO_TYPE).map(([can, type]) => ({ can, type }));\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';\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};\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 blueprint: handlers?.blueprint?.execute\n ? {\n execute: async (params) => handlers.blueprint.execute(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 };\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 };\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 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 };\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 * 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 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 { 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 } 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 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","const DID_PATTERN = /\\bdid:[a-z0-9]+:[A-Za-z0-9._:%-]+/i;\n\nexport function extractDid(value: unknown): string {\n const raw = String(value || '').trim();\n if (!raw) return '';\n const match = raw.match(DID_PATTERN);\n return match?.[0] || '';\n}\n","import { registerAction } 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 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 } 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 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 } 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 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 } 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 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 } 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 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 { registerAction } from '../registry';\nimport type { ActionContext, ActionResult, OutputSchemaField } from '../types';\n\ntype BlueprintActionSpec = {\n type: string;\n can: string;\n sideEffect: boolean;\n confirmation: boolean;\n required: string[];\n properties: Record<string, { type: string; description: string }>;\n};\n\nconst OUTPUT_SCHEMA: OutputSchemaField[] = [\n {\n path: 'receiptRef',\n displayName: 'Runtime receipt',\n type: 'string',\n description: 'Immutable Blueprint Runtime reference proving the governed operation completed.',\n },\n {\n path: 'result',\n displayName: 'Result',\n type: 'object',\n description: 'The governed Blueprint Runtime result.',\n },\n];\n\nconst WORKSPACE_ID = {\n type: 'string',\n description: 'Opaque Blueprint workspace reference supplied by Portal.',\n};\n\nconst ACTIONS: BlueprintActionSpec[] = [\n {\n type: 'qi/blueprint.workspace-start',\n can: 'blueprint/workspace-start',\n sideEffect: true,\n confirmation: true,\n required: ['name'],\n properties: {\n name: {\n type: 'string',\n description: 'Plain-language name for the professional Service POD.',\n },\n },\n },\n {\n type: 'qi/blueprint.journey-resume',\n can: 'blueprint/journey-resume',\n sideEffect: false,\n confirmation: false,\n required: ['workspaceId'],\n properties: { workspaceId: WORKSPACE_ID },\n },\n {\n type: 'qi/blueprint.guided-authoring',\n can: 'blueprint/guided-authoring',\n sideEffect: false,\n confirmation: false,\n required: ['workspaceId', 'phase'],\n properties: {\n workspaceId: WORKSPACE_ID,\n phase: {\n type: 'string',\n description: 'The current product phase: discovery, design, validation, testing, or deployment.',\n },\n },\n },\n {\n type: 'qi/blueprint.artifact-preview',\n can: 'blueprint/artifact-preview',\n sideEffect: false,\n confirmation: false,\n required: ['workspaceId', 'stage', 'content'],\n properties: {\n workspaceId: WORKSPACE_ID,\n stage: {\n type: 'string',\n description: 'Internal Blueprint control receiving the draft.',\n },\n content: {\n type: 'object',\n description: 'Draft artifact content to validate without saving.',\n },\n },\n },\n {\n type: 'qi/blueprint.artifact-save',\n can: 'blueprint/artifact-save',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId', 'stage', 'content'],\n properties: {\n workspaceId: WORKSPACE_ID,\n stage: {\n type: 'string',\n description: 'Internal Blueprint control receiving the approved draft.',\n },\n content: {\n type: 'object',\n description: 'User-confirmed artifact content to save.',\n },\n },\n },\n {\n type: 'qi/blueprint.checklist-update',\n can: 'blueprint/checklist-update',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId', 'operation'],\n properties: {\n workspaceId: WORKSPACE_ID,\n operation: {\n type: 'string',\n description: 'Add, accept for later, or resolve a checklist item.',\n },\n item: {\n type: 'object',\n description: 'Checklist proposal or disposition selected by the user.',\n },\n },\n },\n {\n type: 'qi/blueprint.phase-confirm',\n can: 'blueprint/phase-confirm',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId', 'phase'],\n properties: {\n workspaceId: WORKSPACE_ID,\n phase: {\n type: 'string',\n description: 'Discovery, design, validation, testing, or deployment.',\n },\n },\n },\n {\n type: 'qi/blueprint.reviewer-assign',\n can: 'blueprint/reviewer-assign',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId'],\n properties: {\n workspaceId: WORKSPACE_ID,\n reviewer: {\n type: 'object',\n description: 'Portal-selected independent reviewer or IXO-supported review request.',\n },\n },\n },\n {\n type: 'qi/blueprint.review-submit',\n can: 'blueprint/review-submit',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId'],\n properties: { workspaceId: WORKSPACE_ID },\n },\n {\n type: 'qi/blueprint.review-respond',\n can: 'blueprint/review-respond',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId', 'response'],\n properties: {\n workspaceId: WORKSPACE_ID,\n response: {\n type: 'object',\n description: 'Reviewer decision or provider response bound to the complete revision set.',\n },\n },\n },\n {\n type: 'qi/blueprint.release-compile',\n can: 'blueprint/release-compile',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId'],\n properties: { workspaceId: WORKSPACE_ID },\n },\n {\n type: 'qi/blueprint.publish',\n can: 'blueprint/publish',\n sideEffect: true,\n confirmation: true,\n required: ['workspaceId', 'releaseRef', 'network'],\n properties: {\n workspaceId: WORKSPACE_ID,\n releaseRef: {\n type: 'string',\n description: 'Exact approved release to publish.',\n },\n network: {\n type: 'string',\n description: 'Target IXO network selected by the user.',\n },\n },\n },\n];\n\nfunction requireInputs(inputs: Record<string, unknown>, required: string[]): void {\n for (const field of required) {\n const value = inputs[field];\n if (value === undefined || value === null || (typeof value === 'string' && value.trim().length === 0)) {\n throw new Error(`${field} is required`);\n }\n }\n}\n\nasync function executeBlueprintAction(spec: BlueprintActionSpec, inputs: Record<string, unknown>, ctx: ActionContext): Promise<ActionResult> {\n requireInputs(inputs, spec.required);\n const execute = ctx.services.blueprint?.execute;\n if (!execute) {\n throw new Error(`${spec.type} handler not available`);\n }\n const response = await execute({\n action: spec.type,\n inputs,\n actorDid: ctx.actorDid,\n flowId: ctx.flowId,\n nodeId: ctx.nodeId,\n });\n if (!response.receiptRef) {\n throw new Error(`${spec.type} returned no Blueprint Runtime receipt`);\n }\n return {\n output: {\n receiptRef: response.receiptRef,\n result: response.result ?? {},\n },\n };\n}\n\nfor (const spec of ACTIONS) {\n registerAction({\n type: spec.type,\n can: spec.can,\n sideEffect: spec.sideEffect,\n defaultRequiresConfirmation: spec.confirmation,\n proof: { fields: ['receiptRef'] },\n inputSchema: {\n type: 'object',\n required: spec.required,\n properties: spec.properties,\n },\n outputSchema: OUTPUT_SCHEMA,\n run: async (inputs, ctx) => executeBlueprintAction(spec, inputs, ctx),\n });\n}\n","import { registerAction } from '../../registry';\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\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 } from '../../registry';\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\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 { registerAction } from '../../registry';\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\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\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 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 ...(spec.buildExtraOutput ? spec.buildExtraOutput(inputs) : {}),\n },\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 } from '../../registry';\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\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 { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/http.request',\n can: 'http/request',\n sideEffect: false,\n proof: { fields: ['status'] },\n defaultRequiresConfirmation: false,\n\n // HTTP request can be triggered as a listener — a human assignee is DM'd\n // to invoke it when the upstream event fires. See §3.6 of the\n // events-and-triggers plan.\n eligibleForEventTrigger: true,\n\n inputSchema: {\n type: 'object',\n required: ['endpoint'],\n properties: {\n endpoint: { type: 'string', description: 'The request URL. Either endpoint or its alias url must be provided.' },\n url: { type: 'string', description: 'Alias for endpoint; the request URL. Either url or endpoint satisfies the URL requirement.' },\n method: { type: 'string', description: 'HTTP method (GET, POST, etc.). Defaults to GET.' },\n headers: { type: 'object', description: 'Request headers as a key/value map.' },\n body: { type: 'string', description: 'Request body; sent for non-GET methods. Accepts a string or an object (serialized to JSON).' },\n },\n },\n\n // run() accepts `endpoint` OR `url` — mirror the alias the schema's\n // required array can't express.\n getMissingInputs: (inputs) => (String(inputs.endpoint || inputs.url || '').trim() ? [] : ['endpoint']),\n run: async (inputs, ctx) => {\n const endpoint = inputs.endpoint ?? inputs.url;\n const url = typeof endpoint === 'string' ? endpoint : '';\n if (!url) {\n throw new Error('HTTP request action requires an endpoint or url input');\n }\n\n const method = typeof inputs.method === 'string' ? inputs.method : 'GET';\n const headers = inputs.headers && typeof inputs.headers === 'object' && !Array.isArray(inputs.headers) ? (inputs.headers as Record<string, string>) : {};\n const body = inputs.body;\n\n const requestFn = ctx.services.http?.request;\n if (requestFn) {\n const result = await requestFn({ url, method, headers, body });\n return {\n output: {\n status: result.status,\n data: result.data,\n response: JSON.stringify(result.data, null, 2),\n },\n };\n }\n\n // Fallback to native fetch\n const fetchOptions: RequestInit = {\n method,\n headers: { 'Content-Type': 'application/json', ...headers },\n };\n\n if (method !== 'GET' && body) {\n fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);\n }\n\n const response = await fetch(url, fetchOptions);\n const data = await response.json().catch(() => ({}));\n\n return {\n output: {\n status: response.status,\n data,\n response: JSON.stringify(data, null, 2),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/email.send',\n can: 'email/send',\n sideEffect: true,\n proof: { fields: ['messageId'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/human.checkbox.set',\n can: 'human/checkbox',\n sideEffect: true,\n proof: 'none',\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\n run: async (inputs) => {\n // Default to true — \"executing\" a checkbox means checking it\n const checked = inputs.checked !== undefined ? !!inputs.checked : true;\n return { output: { checked } };\n },\n});\n","import { registerAction } from '../registry';\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: 'none',\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 ],\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) => {\n const answers = normalizeAnswers(inputs.answers ?? inputs.form?.answers);\n const answersJson = JSON.stringify(answers);\n\n return {\n output: {\n form: {\n answers: answersJson,\n },\n answers,\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 } from '../registry';\n\nregisterAction({\n type: 'qi/notification.push',\n can: 'notification/push',\n sideEffect: true,\n proof: { fields: ['messageId'] },\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\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 } 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 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 } 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 sideEffect: true,\n proof: { fields: ['bidId'] },\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 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 { registerAction } from '../../registry';\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 // 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 events: [\n {\n name: 'submitted',\n payload: output,\n },\n ],\n };\n },\n});\n","import { registerAction } from '../../registry';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { ActionEventDefinition, OutputSchemaField } from '../../types';\nimport { buildXeroInvoiceWorkKey, upsertXeroWorkItemForEditor } from '../../../xeroWorkItems';\nimport { prefixSurveyAnswerSchema } from '../claim/surveySchema';\nimport type { EvaluateClaimRunInputs } from './types';\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];\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 // Repeatable: an evaluator processes many claims over the flow's life. Never\n // latches to a terminal Done. See cardinality.\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 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 };\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 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 events: [{ name: eventName, payload: eventPayload }],\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/proposal.create',\n can: 'proposal/create',\n sideEffect: true,\n proof: { fields: ['proposalId'] },\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 };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/proposal.vote',\n can: 'proposal/vote',\n sideEffect: true,\n proof: { fields: ['votedAt'] },\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 return {\n output: {\n vote,\n rationale: rationale || '',\n proposalId: String(proposalId),\n votedAt: new Date().toISOString(),\n },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/protocol.select',\n can: 'protocol/select',\n sideEffect: false,\n proof: 'none',\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","/**\n * Transforms survey data from the Domain Creator survey into a W3C Verifiable Credential\n * credentialSubject structure compatible with ixo:DomainCard schema.\n */\n\nexport interface DomainCardCredentialSubject {\n id: string;\n type: string[];\n additionalType?: string[];\n name: string;\n alternateName?: string[];\n description: string;\n url?: string;\n sameAs?: string[];\n logo?: {\n type: string;\n id: string;\n contentUrl: string;\n };\n image?: Array<{\n type: string;\n id: string;\n contentUrl: string;\n }>;\n keywords?: string[];\n knowsAbout?: string[];\n address?: {\n type: string;\n streetAddress?: string;\n addressLocality?: string;\n addressRegion?: string;\n postalCode?: string;\n addressCountry?: string;\n };\n areaServed?: {\n type: string;\n name: string;\n };\n contactPoint?: Array<{\n type: string;\n contactType: string;\n email?: string;\n telephone?: string;\n availableLanguage?: string[];\n }>;\n composition?: {\n type: string;\n hasPart?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n url?: string;\n creator?: {\n type: string;\n name: string;\n };\n }>;\n subjectOf?: Array<{\n type: string;\n name: string;\n url?: string;\n author?: {\n type: string;\n name: string;\n };\n }>;\n };\n makesOffer?: Array<{\n type: string;\n name?: string;\n description?: string;\n itemOffered?: {\n type: string;\n name?: string;\n url?: string;\n };\n }>;\n relationships?: {\n memberOf?: Array<{\n type: string;\n name: string;\n }>;\n 'prov:wasAssociatedWith'?: Array<{\n type: string;\n name: string;\n url?: string;\n }>;\n funding?: Array<{\n type: string;\n funder?: {\n type: string;\n name: string;\n };\n amount?: {\n type: string;\n currency: string;\n value: string;\n };\n }>;\n };\n agents?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n }>;\n credentials?: Array<{\n type: string;\n id?: string;\n name?: string;\n description?: string;\n }>;\n attributes?: Array<{\n '@type': string;\n '@id': string;\n name: string;\n value: string;\n }>;\n project?: {\n type?: string;\n name?: string;\n description?: string;\n hadObjective?: string[];\n plannedStart?: string;\n plannedEnd?: string;\n wasFundedThrough?: Array<{\n type: string;\n moneyAmount?: string;\n moneyCurrency?: string;\n agent?: {\n type: string;\n id?: string;\n name?: string;\n };\n }>;\n };\n researchProfile?: {\n type: string;\n 'ixo:seedQueries'?: string[];\n citation?: Array<{\n type: string;\n name: string;\n url?: string;\n publisher?: string;\n datePublished?: string;\n }>;\n 'ixo:embedding'?: {\n type: string;\n id: string;\n model: string;\n contentUrl: string;\n };\n dateModified?: string;\n };\n}\n\n/**\n * Helper to extract array items from paneldynamic survey fields\n */\nfunction extractPanelDynamicItems<T>(surveyData: Record<string, any>, panelName: string, itemMapper: (item: Record<string, any>) => T | null): T[] {\n const items = surveyData[panelName];\n if (!Array.isArray(items)) return [];\n return items.map(itemMapper).filter((item): item is T => item !== null);\n}\n\n/**\n * Parse comma-separated string into array of trimmed strings\n */\nfunction parseCommaSeparated(value: string | undefined): string[] {\n if (!value || typeof value !== 'string') return [];\n return value\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n/**\n * Parse language codes from comma-separated string\n */\nfunction parseLanguageCodes(value: string | undefined): string[] {\n return parseCommaSeparated(value);\n}\n\n/**\n * Build image object from URL\n */\nfunction buildImageObject(url: string | undefined): { type: string; id: string; contentUrl: string } | null {\n if (!url) return null;\n return {\n type: 'schema:ImageObject',\n id: url,\n contentUrl: url,\n };\n}\n\n/**\n * Main transformation function\n */\nexport function transformSurveyToCredentialSubject(surveyData: Record<string, any>, entityDid: string): DomainCardCredentialSubject {\n // Build type array from survey selections\n const types: string[] = [];\n if (surveyData['type_1']) types.push(`ixo:${surveyData['type_1']}`);\n if (surveyData['type_2']) types.push(surveyData['type_2']);\n\n // Build additionalType from daoType\n const additionalType: string[] = [];\n if (surveyData['daoType']) additionalType.push(surveyData['daoType']);\n\n // Extract alternate names from paneldynamic\n const alternateNames = extractPanelDynamicItems(surveyData, 'pannel_schema:alternateName', (item) => item['schema:alternateName'] || null);\n\n // Extract sameAs URLs from paneldynamic\n const sameAsUrls = extractPanelDynamicItems(surveyData, 'schema:sameAs', (item) => item['schema:sameAs.url'] || null);\n\n // Build logo from URL or uploaded file\n const logoUrl = surveyData['ixo:imageLogo_url'] || surveyData['ixo:imageLogo']?.[0]?.content;\n const logo = buildImageObject(logoUrl);\n\n // Build profile image from URL or uploaded file\n const profileImageUrl = surveyData['ixo:imageProfile_url'] || surveyData['ixo:imageProfile']?.[0]?.content;\n const profileImage = buildImageObject(profileImageUrl);\n\n // Parse keywords from comma-separated string\n const keywords = parseCommaSeparated(surveyData['schema:keywords']);\n\n // Extract knowsAbout from paneldynamic\n const knowsAbout = extractPanelDynamicItems(surveyData, 'pannel_ixo:knowsAbout', (item) => item['ixo:knowsAbout'] || null);\n\n // Build address object\n const hasAddressData =\n surveyData['schema:streetAddress'] ||\n surveyData['schema:addressLocality'] ||\n surveyData['schema:addressRegion'] ||\n surveyData['schema:postalCode'] ||\n surveyData['schema:addressCountry'];\n\n const address = hasAddressData\n ? {\n type: 'schema:PostalAddress',\n streetAddress: surveyData['schema:streetAddress'] || undefined,\n addressLocality: surveyData['schema:addressLocality'] || undefined,\n addressRegion: surveyData['schema:addressRegion'] || undefined,\n postalCode: surveyData['schema:postalCode'] || undefined,\n addressCountry: surveyData['schema:addressCountry'] || undefined,\n }\n : undefined;\n\n // Build areaServed\n const areaServed = surveyData['schema:AdministrativeArea']\n ? {\n type: 'schema:AdministrativeArea',\n name: surveyData['schema:AdministrativeArea'],\n }\n : undefined;\n\n // Extract contact points from paneldynamic\n const contactPoints = extractPanelDynamicItems(surveyData, 'pannel:schema_contactPoint', (item) => {\n if (!item['schema:contactType'] && !item['schema:email'] && !item['schema:telephone']) return null;\n return {\n type: 'schema:ContactPoint',\n contactType: item['schema:contactType'] || 'general',\n email: item['schema:email'] || undefined,\n telephone: item['schema:telephone'] || undefined,\n availableLanguage: parseLanguageCodes(item['schema:availableLanguage']),\n };\n });\n\n // Build composition object\n const hasParts = extractPanelDynamicItems(surveyData, 'schema:hasPart', (item) => {\n if (!item['schema:hasPart.name'] && !item['schema:hasPart.id']) return null;\n return {\n type: 'schema:CreativeWork',\n id: item['schema:hasPart.id'] || undefined,\n name: item['schema:hasPart.name'] || undefined,\n description: item['schema:hasPart.description'] || undefined,\n url: item['schema:hasPart.url'] || undefined,\n creator: item['schema:hasPart.creator.name']\n ? {\n type: 'schema:Organization',\n name: item['schema:hasPart.creator.name'],\n }\n : undefined,\n };\n });\n\n const subjectOf = extractPanelDynamicItems(surveyData, 'schema:subjectOf', (item) => {\n if (!item['schema:subjectOf.name']) return null;\n return {\n type: 'schema:CreativeWork',\n name: item['schema:subjectOf.name'],\n url: item['schema:subjectOf.url'] || undefined,\n author: item['schema:subjectOf.author.name']\n ? {\n type: 'schema:Organisation',\n name: item['schema:subjectOf.author.name'],\n }\n : undefined,\n };\n });\n\n const composition =\n hasParts.length > 0 || subjectOf.length > 0\n ? {\n type: 'schema:Collection',\n hasPart: hasParts.length > 0 ? hasParts : undefined,\n subjectOf: subjectOf.length > 0 ? subjectOf : undefined,\n }\n : undefined;\n\n // Extract makesOffer from paneldynamic\n const makesOffer = extractPanelDynamicItems(surveyData, 'schema:makesOffer', (item) => {\n if (!item['schema:itemOffered.name']) return null;\n return {\n type: 'schema:Offer',\n itemOffered: {\n type: item['schema:itemOffered.type'] === 'service' ? 'schema:Service' : 'schema:Product',\n name: item['schema:itemOffered.name'] || undefined,\n description: item['schema:itemOffered.description'] || undefined,\n url: item['schema:itemOffered.url'] || undefined,\n },\n };\n });\n\n // Build relationships object\n const memberOf = extractPanelDynamicItems(surveyData, 'schema:memberOf', (item) => {\n if (!item['schema:memberOf.name']) return null;\n return {\n type: 'schema:Organization',\n name: item['schema:memberOf.name'],\n };\n });\n\n const wasAssociatedWith = extractPanelDynamicItems(surveyData, 'schema:wasAssociatedWith', (item) => {\n if (!item['schema:wasAssociatedWith.name']) return null;\n return {\n type: 'schema:Organization',\n name: item['schema:wasAssociatedWith.name'],\n url: item['schema:wasAssociatedWith.url'] || undefined,\n };\n });\n\n const funding = extractPanelDynamicItems(surveyData, 'schema:funding', (item) => {\n if (!item['schema:funder.name']) return null;\n return {\n type: 'schema:MonetaryGrant',\n funder: {\n type: 'schema:Organization',\n name: item['schema:funder.name'],\n },\n amount:\n item['schema:amount.value'] || item['schema:amount.currency']\n ? {\n type: 'schema:MonetaryAmount',\n currency: item['schema:amount.currency'] || 'USD',\n value: item['schema:amount.value'] || '0',\n }\n : undefined,\n };\n });\n\n const relationships =\n memberOf.length > 0 || wasAssociatedWith.length > 0 || funding.length > 0\n ? {\n memberOf: memberOf.length > 0 ? memberOf : undefined,\n 'prov:wasAssociatedWith': wasAssociatedWith.length > 0 ? wasAssociatedWith : undefined,\n funding: funding.length > 0 ? funding : undefined,\n }\n : undefined;\n\n // Extract agents from paneldynamic\n const agents = extractPanelDynamicItems(surveyData, 'ixo:agentCard', (item) => {\n if (!item['ixo:agentCard.name'] && !item['ixo:agentCard.id']) return null;\n return {\n type: 'ixo:AgentCard',\n id: item['ixo:agentCard.id'] || undefined,\n name: item['ixo:agentCard.name'] || undefined,\n description: item['ixo:agentCard.description'] || undefined,\n };\n });\n\n // Extract credentials from paneldynamic\n const credentials = extractPanelDynamicItems(surveyData, 'ixo:verifiableCredential', (item) => {\n if (!item['schema:Name'] && !item['schema:ID']) return null;\n return {\n type: 'VerifiableCredential',\n id: item['schema:ID'] || undefined,\n name: item['schema:Name'] || undefined,\n description: item['schema:description'] || undefined,\n };\n });\n\n // Extract attributes from paneldynamic\n const attributes = extractPanelDynamicItems(surveyData, 'ixo:attribute', (item) => {\n if (!item['schema:name_2']) return null;\n return {\n '@type': 'ixo:Attribute',\n '@id': item['schema:ID_2'] || `attribute:${item['schema:name_2'].replace(/\\s+/g, '_').toLowerCase()}`,\n name: item['schema:name_2'],\n value: item['schema:description_2'] || '',\n };\n });\n\n // Build project object from paneldynamic\n const projects = extractPanelDynamicItems(surveyData, 'pannel_proj:project', (item) => {\n if (!item['proj:project.name']) return null;\n\n // Extract objectives\n const objectives = extractPanelDynamicItems(item, 'proj:project.hadObjective', (objItem) => objItem['proj:hadObjective'] || null);\n\n // Extract funding\n const projectFunding = extractPanelDynamicItems(item, 'proj:wasFundedThrough', (fundItem) => ({\n type: 'proj:FundingAssociation',\n moneyAmount: fundItem['proj:moneyAmount'] || undefined,\n moneyCurrency: fundItem['proj:moneyCurrency'] || undefined,\n agent:\n fundItem['prov.agent.name'] || fundItem['prov:agent.id']\n ? {\n type: 'prov:Agent',\n id: fundItem['prov:agent.id'] || undefined,\n name: fundItem['prov.agent.name'] || undefined,\n }\n : undefined,\n }));\n\n return {\n type: 'proj:Project',\n name: item['proj:project.name'],\n description: item['proj:project.description'] || undefined,\n hadObjective: objectives.length > 0 ? objectives : undefined,\n plannedStart: item['proj:plannedStart'] || undefined,\n plannedEnd: item['proj:plannedEnd'] || undefined,\n wasFundedThrough: projectFunding.length > 0 ? projectFunding : undefined,\n };\n });\n\n // Use first project if multiple (or combine as needed)\n const project = projects.length > 0 ? projects[0] : undefined;\n\n // Build research profile\n const seedQueries = extractPanelDynamicItems(surveyData, 'ixo:ResearchProfile', (item) => item['ixo:seedQueries'] || null);\n\n const citations = extractPanelDynamicItems(surveyData, 'schema:creativeWork', (item) => {\n if (!item['schema:creativeWork.name']) return null;\n return {\n type: 'schema:CreativeWork',\n name: item['schema:creativeWork.name'],\n url: item['schema:creativeWork.url'] || undefined,\n publisher: item['schema:creativeWork.publisher'] || undefined,\n datePublished: item['schema:creativeWork.datePublished'] || undefined,\n };\n });\n\n const researchProfile =\n seedQueries.length > 0 || citations.length > 0\n ? {\n type: 'ixo:ResearchProfile',\n 'ixo:seedQueries': seedQueries.length > 0 ? seedQueries : undefined,\n citation: citations.length > 0 ? citations : undefined,\n dateModified: new Date().toISOString(),\n }\n : undefined;\n\n // Build the final credentialSubject\n const credentialSubject: DomainCardCredentialSubject = {\n id: entityDid,\n type: types.length > 0 ? types : ['ixo:dao'],\n name: surveyData['schema:name'] || '',\n description: surveyData['schema.description'] || '',\n };\n\n // Add optional fields only if they have values\n if (additionalType.length > 0) credentialSubject.additionalType = additionalType;\n if (alternateNames.length > 0) credentialSubject.alternateName = alternateNames;\n if (surveyData['schema:url']) credentialSubject.url = surveyData['schema:url'];\n if (sameAsUrls.length > 0) credentialSubject.sameAs = sameAsUrls;\n if (logo) credentialSubject.logo = logo;\n if (profileImage) credentialSubject.image = [profileImage];\n if (keywords.length > 0) credentialSubject.keywords = keywords;\n if (knowsAbout.length > 0) credentialSubject.knowsAbout = knowsAbout;\n if (address) credentialSubject.address = address;\n if (areaServed) credentialSubject.areaServed = areaServed;\n if (contactPoints.length > 0) credentialSubject.contactPoint = contactPoints;\n if (composition) credentialSubject.composition = composition;\n if (makesOffer.length > 0) credentialSubject.makesOffer = makesOffer;\n if (relationships) credentialSubject.relationships = relationships;\n if (agents.length > 0) credentialSubject.agents = agents;\n if (credentials.length > 0) credentialSubject.credentials = credentials;\n if (attributes.length > 0) credentialSubject.attributes = attributes;\n if (project) credentialSubject.project = project;\n if (researchProfile) credentialSubject.researchProfile = researchProfile;\n\n return credentialSubject;\n}\n","/**\n * Builds an unsigned W3C Verifiable Credential envelope for a Domain Card.\n * The credential follows the ixo:DomainCard schema.\n */\n\nimport type { DomainCardCredentialSubject } from './transformSurveyToCredentialSubject';\n\n/**\n * JSON-LD context for Domain Card credentials\n */\nexport const DOMAIN_CARD_CONTEXT = [\n 'https://w3id.org/ixo/context/v1',\n {\n schema: 'https://schema.org/',\n ixo: 'https://w3id.org/ixo/vocab/v1',\n prov: 'http://www.w3.org/ns/prov#',\n proj: 'http://www.w3.org/ns/project#',\n id: '@id',\n type: '@type',\n '@protected': true,\n },\n] as const;\n\n/**\n * Domain Card credential schema reference\n */\nexport const DOMAIN_CARD_SCHEMA = {\n id: 'https://w3id.org/ixo/protocol/schema/v1#domainCard',\n type: 'JsonSchema',\n} as const;\n\n/**\n * DataIntegrityProof structure for signed credentials\n */\nexport interface DataIntegrityProof {\n type: 'DataIntegrityProof';\n created: string;\n verificationMethod: string;\n cryptosuite: 'eddsa-rdfc-2022';\n proofPurpose: 'assertionMethod';\n proofValue: string;\n}\n\n/**\n * Unsigned Verifiable Credential structure\n */\nexport interface UnsignedVerifiableCredential {\n '@context': typeof DOMAIN_CARD_CONTEXT;\n id: string;\n type: ['VerifiableCredential', 'ixo:DomainCard'];\n issuer: {\n id: string;\n };\n validFrom: string;\n validUntil: string;\n credentialSchema: typeof DOMAIN_CARD_SCHEMA;\n credentialSubject: DomainCardCredentialSubject;\n}\n\n/**\n * Signed Verifiable Credential with proof\n */\nexport interface SignedVerifiableCredential extends UnsignedVerifiableCredential {\n proof: DataIntegrityProof;\n}\n\n/**\n * Base credential subject with required fields.\n * Used for flexible input that may come from different sources (survey, existing credential, etc.)\n */\nexport interface BaseCredentialSubject {\n id: string;\n type: string[];\n name: string;\n description: string;\n [key: string]: unknown; // Allow additional properties\n}\n\n/**\n * Parameters for building an unsigned verifiable credential\n */\nexport interface BuildCredentialParams {\n /** DID of the entity this domain card describes */\n entityDid: string;\n /** DID of the issuer signing this credential */\n issuerDid: string;\n /** The credential subject containing domain card data (flexible input) */\n credentialSubject: BaseCredentialSubject | DomainCardCredentialSubject;\n /** ISO 8601 date string for when credential becomes valid */\n validFrom: string;\n /** ISO 8601 date string for when credential expires */\n validUntil: string;\n}\n\n/**\n * Converts a date input to ISO 8601 string format.\n * Handles various input formats from survey fields.\n */\nfunction toISOString(dateInput: string | Date | undefined, fallback: Date = new Date()): string {\n if (!dateInput) {\n return fallback.toISOString();\n }\n\n if (dateInput instanceof Date) {\n return dateInput.toISOString();\n }\n\n // Handle date-only strings (YYYY-MM-DD) from date inputs\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(dateInput)) {\n return new Date(dateInput + 'T00:00:00.000Z').toISOString();\n }\n\n // Handle datetime-local strings (YYYY-MM-DDTHH:MM)\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$/.test(dateInput)) {\n return new Date(dateInput + ':00.000Z').toISOString();\n }\n\n // Try parsing as-is\n const parsed = new Date(dateInput);\n if (!isNaN(parsed.getTime())) {\n return parsed.toISOString();\n }\n\n return fallback.toISOString();\n}\n\n/**\n * Calculates a default expiration date (5 years from validFrom).\n */\nfunction getDefaultValidUntil(validFrom: string): string {\n const fromDate = new Date(validFrom);\n const untilDate = new Date(fromDate);\n untilDate.setFullYear(untilDate.getFullYear() + 5);\n return untilDate.toISOString();\n}\n\n/**\n * Builds an unsigned verifiable credential for a Domain Card.\n *\n * @param params - Parameters for building the credential\n * @returns An unsigned verifiable credential ready for signing\n *\n * @example\n * ```typescript\n * const credential = buildVerifiableCredential({\n * entityDid: 'did:ixo:entity:abc123',\n * issuerDid: 'did:ixo:ixo1xyz...',\n * credentialSubject: transformedSubject,\n * validFrom: '2025-01-01',\n * validUntil: '2030-01-01',\n * });\n * ```\n */\nexport function buildVerifiableCredential(params: BuildCredentialParams): UnsignedVerifiableCredential {\n const { entityDid, issuerDid, credentialSubject, validFrom, validUntil } = params;\n\n const validFromISO = toISOString(validFrom);\n const validUntilISO = validUntil ? toISOString(validUntil) : getDefaultValidUntil(validFromISO);\n\n return {\n '@context': DOMAIN_CARD_CONTEXT,\n id: `${entityDid}#dmn`,\n type: ['VerifiableCredential', 'ixo:DomainCard'],\n issuer: {\n id: issuerDid,\n },\n validFrom: validFromISO,\n validUntil: validUntilISO,\n credentialSchema: DOMAIN_CARD_SCHEMA,\n credentialSubject: {\n ...credentialSubject,\n // Ensure the subject ID matches the entity DID\n id: entityDid,\n },\n };\n}\n\n/**\n * LinkedResource structure for storing the credential on-chain\n */\nexport interface DomainCardLinkedResource {\n id: string;\n type: 'domainCard';\n proof: string;\n right: string;\n encrypted: string;\n mediaType: 'application/json';\n description: string;\n serviceEndpoint: string;\n}\n\n/**\n * Builds a LinkedResource object for a Domain Card credential.\n *\n * @param params - Parameters for building the linked resource\n * @returns A LinkedResource object ready to be added to an entity\n *\n * @example\n * ```typescript\n * const linkedResource = buildDomainCardLinkedResource({\n * entityDid: 'did:ixo:entity:abc123',\n * cid: 'bafkreid2t3hp7qi6ynyvaz4o3bphyjtqcz2qwlhm4odvuvesnh6dtv3hvu',\n * serviceEndpoint: 'https://mx.ixo.earth/_matrix/media/v3/download/...',\n * });\n * ```\n */\nexport function buildDomainCardLinkedResource(params: { entityDid: string; cid: string; serviceEndpoint: string; description?: string }): DomainCardLinkedResource {\n return {\n id: `${params.entityDid}#dmn`,\n type: 'domainCard',\n proof: params.cid,\n right: '',\n encrypted: 'false',\n mediaType: 'application/json',\n description: params.description || 'Domain Card',\n serviceEndpoint: params.serviceEndpoint,\n };\n}\n","interface SurveyElement {\n type: string;\n name?: string;\n elements?: SurveyElement[];\n templateElements?: SurveyElement[];\n}\n\ninterface SurveyPage {\n name: string;\n elements: SurveyElement[];\n}\n\ninterface SurveyDefinition {\n pages: SurveyPage[];\n}\n\n/**\n * Recursively extracts field names from survey elements.\n * Handles nested panels and paneldynamic template elements.\n */\nfunction extractFieldsFromElements(elements: SurveyElement[], fields: Record<string, unknown>): void {\n for (const element of elements) {\n // Skip panel containers but process their children\n if (element.type === 'panel' && element.elements) {\n extractFieldsFromElements(element.elements, fields);\n continue;\n }\n\n // Handle paneldynamic - these create arrays of objects\n if (element.type === 'paneldynamic' && element.name) {\n // Initialize as empty array for dynamic panels\n fields[element.name] = [];\n\n // Also extract template element names for reference\n if (element.templateElements) {\n extractFieldsFromElements(element.templateElements, fields);\n }\n continue;\n }\n\n // Regular input elements with a name\n if (element.name && element.type !== 'panel') {\n // Set appropriate default based on type\n switch (element.type) {\n case 'boolean':\n fields[element.name] = false;\n break;\n case 'checkbox':\n fields[element.name] = [];\n break;\n case 'file':\n fields[element.name] = [];\n break;\n default:\n fields[element.name] = '';\n }\n }\n\n // Handle nested elements in regular panels\n if (element.elements) {\n extractFieldsFromElements(element.elements, fields);\n }\n }\n}\n\n/**\n * Extracts all field names from a SurveyJS survey definition\n * and creates an empty answers template object.\n *\n * This template can be used to:\n * 1. Initialize the answers prop with all possible fields\n * 2. Provide AI agents with the structure they can fill in\n *\n * @param surveyDef - The SurveyJS survey definition object\n * @returns An object with all field names as keys and empty/default values\n */\nexport function extractSurveyAnswersTemplate(surveyDef: SurveyDefinition): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n\n for (const page of surveyDef.pages) {\n extractFieldsFromElements(page.elements, fields);\n }\n\n return fields;\n}\n\n/**\n * Creates a stringified empty answers template from a survey definition.\n * Useful for initializing the block prop.\n */\nexport function createEmptyAnswersJson(surveyDef: SurveyDefinition): string {\n return JSON.stringify(extractSurveyAnswersTemplate(surveyDef));\n}\n","import type { LinkedEntityData } from '@/mantine/blocks/governanceGroup/types';\n\n/**\n * LinkedEntity structure for createDomain call\n */\nexport interface LinkedEntity {\n id: string;\n type: string;\n relationship: string;\n service: string;\n}\n\n/**\n * Parse linked entities from block props\n */\nexport function parseLinkedEntities(entitiesString: string): LinkedEntityData[] {\n if (!entitiesString || entitiesString === '[]') return [];\n try {\n return JSON.parse(entitiesString) as LinkedEntityData[];\n } catch {\n return [];\n }\n}\n\n/**\n * Build LinkedEntity array for governance groups\n * These will be passed to createDomain as linkedEntity parameter\n */\nexport function buildGovernanceGroupLinkedEntities(linkedEntities: LinkedEntityData[]): LinkedEntity[] {\n return linkedEntities\n .filter((entity) => entity.type === 'governanceGroup' && entity.coreAddress)\n .map((entity) => ({\n id: `{id}#${entity.coreAddress}`,\n type: 'group',\n relationship: 'governs',\n service: '',\n }));\n}\n","export const tempDomainCreatorSurvey = {\n title: 'Domain Card Creation',\n description: 'This survey collects structured information required to create a Domain Card Verifiable Credential in compliance with W3C standards.',\n pages: [\n {\n name: 'domainDetails',\n title: 'Domain Information',\n description: 'Provide identifying and descriptive information about the domain entity represented by this credential.',\n elements: [\n {\n type: 'boolean',\n name: 'ixo:advancedDomainSettings',\n title: 'Show Advanced Options',\n defaultValue: 'false',\n },\n {\n type: 'dropdown',\n name: 'type_1',\n visible: false,\n title: 'Domain Type (Primary)',\n defaultValue: 'dao',\n choices: [\n {\n value: 'dao',\n text: 'DAO',\n },\n {\n value: 'protocol',\n text: 'Protocol',\n },\n ],\n },\n {\n type: 'dropdown',\n name: 'type_2',\n title: 'Domain Type ',\n isRequired: true,\n choicesByUrl: {\n url: 'https://test.studio.ixo.earth/api/survey-choices?url=https://raw.githubusercontent.com/ixofoundation/ns/refs/heads/GraemeLeightonIXO-patch-4/protocol/entities/v1/index.json&path=entities.dao.types',\n valueName: 'Value',\n titleName: 'Text',\n },\n },\n {\n type: 'dropdown',\n name: 'daoType',\n title: 'DAO Type',\n isRequired: true,\n choicesByUrl: {\n url: 'https://test.studio.ixo.earth/api/survey-choices?url=https://raw.githubusercontent.com/ixofoundation/ns/refs/heads/GraemeLeightonIXO-patch-4/protocol/tags/v1/index.json&path=daoType',\n valueName: 'Value',\n titleName: 'Text',\n },\n },\n {\n type: 'text',\n name: 'schema:validFrom',\n title: 'Valid From',\n defaultValueExpression: 'today()',\n isRequired: true,\n inputType: 'date',\n },\n {\n type: 'text',\n name: 'schema:validUntil',\n title: 'Vaid Untill',\n defaultValueExpression: 'today()',\n isRequired: true,\n inputType: 'date',\n },\n {\n type: 'text',\n name: 'schema:name',\n title: 'Domain Name',\n description: 'The official name of the domain.',\n isRequired: true,\n },\n {\n type: 'paneldynamic',\n name: 'pannel_schema:alternateName',\n title: 'Alternate Names',\n templateElements: [\n {\n type: 'text',\n name: 'schema:alternateName',\n title: 'Alternate Name',\n },\n ],\n },\n {\n type: 'text',\n name: 'schema:url',\n title: 'URL',\n description: 'Primary URL for the domain',\n inputType: 'url',\n },\n {\n type: 'paneldynamic',\n name: 'schema:sameAs',\n title: 'Additional URLs',\n description: 'Additional URLs associated with the domain (Twitter, Github, Medium)',\n templateElements: [\n {\n type: 'text',\n name: 'schema:sameAs.url',\n title: 'URL',\n inputType: 'url',\n },\n ],\n },\n {\n type: 'comment',\n name: 'schema.description',\n title: 'Canonical Description',\n description: 'A concise, one-paragraph description of the domain.',\n isRequired: true,\n },\n {\n type: 'panel',\n name: 'pannel_schema:media',\n title: 'Domain Images',\n elements: [\n {\n type: 'text',\n name: 'ixo:imageProfile_url',\n title: 'Profile Image URL',\n inputType: 'url',\n },\n {\n type: 'file',\n name: 'ixo:imageProfile',\n title: 'Profile Image',\n },\n {\n type: 'text',\n name: 'ixo:imageLogo_url',\n title: 'Logo URL',\n inputType: 'url',\n },\n {\n type: 'file',\n name: 'ixo:imageLogo',\n title: 'Logo',\n },\n ],\n },\n {\n type: 'comment',\n name: 'schema:keywords',\n title: 'Keywords',\n description: 'List of comma separated keywords describing the domain’s focus areas.',\n },\n {\n type: 'paneldynamic',\n name: 'pannel_ixo:knowsAbout',\n title: 'Topics /Primary Knowledge Areas',\n description: 'Subjects or fields the domain is knowledgeable in.',\n templateElements: [\n {\n type: 'text',\n name: 'ixo:knowsAbout',\n title: 'Knows About',\n },\n ],\n },\n ],\n },\n {\n name: 'contactAndLocation',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Contact & Location',\n description: 'Provide address and contact information for the domain.',\n elements: [\n {\n type: 'panel',\n name: 'schema:address',\n title: 'Postal Address',\n elements: [\n {\n type: 'text',\n name: 'schema:streetAddress',\n title: 'Street Address',\n },\n {\n type: 'text',\n name: 'schema:addressLocality',\n title: 'City',\n },\n {\n type: 'text',\n name: 'schema:addressRegion',\n title: 'Region/State',\n },\n {\n type: 'text',\n name: 'schema:postalCode',\n title: 'Postal Code',\n },\n {\n type: 'text',\n name: 'schema:addressCountry',\n title: 'Country',\n },\n ],\n },\n {\n type: 'text',\n name: 'schema:AdministrativeArea',\n title: 'Area Served',\n },\n {\n type: 'paneldynamic',\n name: 'pannel:schema_contactPoint',\n title: 'Contact Points',\n description: 'List available contact methods for support, business, or technical inquiries.',\n templateElements: [\n {\n type: 'text',\n name: 'schema:contactType',\n title: 'Contact Type',\n description: 'Example: General, Support, Sales',\n },\n {\n type: 'text',\n name: 'schema:email',\n title: 'Email Address',\n inputType: 'email',\n },\n {\n type: 'text',\n name: 'schema:telephone',\n title: 'Telephone ',\n inputType: 'tel',\n },\n {\n type: 'text',\n name: 'schema:availableLanguage',\n title: 'Languages Supported',\n description: 'Comma separated two letter language code (English = en)',\n },\n ],\n },\n ],\n },\n {\n name: 'composition',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Composition',\n elements: [\n {\n type: 'paneldynamic',\n name: 'schema:hasPart',\n title: 'Domain Components',\n description: 'Describes the specific items, documents, linked domains, or components that belong to this domain.',\n templateElements: [\n {\n type: 'text',\n name: 'schema:hasPart.id',\n title: 'Identifier',\n description: 'URI or URL ',\n },\n {\n type: 'text',\n name: 'schema:hasPart.name',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'schema:hasPart.description',\n title: 'Description',\n },\n {\n type: 'text',\n name: 'schema:hasPart.url',\n title: 'URL',\n description: 'If different to the identifier',\n inputType: 'url',\n },\n {\n type: 'text',\n name: 'schema:hasPart.creator.name',\n title: 'Creator',\n description: 'Component creator (Organisation Name)',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'schema:subjectOf',\n title: 'Publications',\n description: 'Publications produced by the domain or where the domain is the subject.',\n templateElements: [\n {\n type: 'text',\n name: 'schema:subjectOf.name',\n title: 'Publication Title',\n },\n {\n type: 'text',\n name: 'schema:subjectOf.url',\n title: 'URL',\n },\n {\n type: 'text',\n name: 'schema:subjectOf.author.name',\n title: 'Author',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'schema:makesOffer',\n title: 'Offers (Product and/or Services)',\n templateElements: [\n {\n type: 'dropdown',\n name: 'schema:itemOffered.type',\n title: 'Catagory',\n choices: [\n {\n value: 'product',\n text: 'Product',\n },\n {\n value: 'service',\n text: 'Service',\n },\n ],\n },\n {\n type: 'text',\n name: 'schema:itemOffered.name',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'schema:itemOffered.description',\n title: 'Description',\n },\n {\n type: 'text',\n name: 'schema:itemOffered.url',\n title: 'URL',\n inputType: 'url',\n },\n ],\n },\n ],\n },\n {\n name: 'relationshipsAndOffers',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Relationships & Funding',\n description: 'Describe the domain’s relationships with other organizations and its software or service offerings.',\n elements: [\n {\n type: 'paneldynamic',\n name: 'schema:memberOf',\n title: 'Memberships',\n templateElements: [\n {\n type: 'text',\n name: 'schema:memberOf.name',\n title: 'Organization Name',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'schema:wasAssociatedWith',\n title: 'Partner/Associated Organizations',\n templateElements: [\n {\n type: 'text',\n name: 'schema:wasAssociatedWith.name',\n title: 'Organization Name',\n },\n {\n type: 'text',\n name: 'schema:wasAssociatedWith.url',\n title: 'URL',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'schema:funding',\n title: 'Funding Sources',\n templateElements: [\n {\n type: 'text',\n name: 'schema:funder.name',\n title: 'Funder Organization',\n },\n {\n type: 'text',\n name: 'schema:amount.currency',\n title: 'Currency Code',\n },\n {\n type: 'text',\n name: 'schema:amount.value',\n title: 'Funding Amount',\n },\n ],\n },\n ],\n },\n {\n name: 'events',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Events',\n elements: [\n {\n type: 'paneldynamic',\n name: 'schema:event',\n title: 'Event',\n templateElements: [\n {\n type: 'text',\n name: 'schema:event.name',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'schema:startDate',\n title: 'Start Date',\n },\n {\n type: 'text',\n name: 'schema:endDate',\n title: 'End Date',\n },\n {\n type: 'text',\n name: 'schema:event.location',\n title: 'Location Name',\n },\n {\n type: 'panel',\n name: 'schema:event.address',\n title: 'Postal Address',\n elements: [\n {\n type: 'text',\n name: 'schema:event.streetAddress',\n title: 'Street Address',\n },\n {\n type: 'text',\n name: 'schema:event.addressLocality',\n title: 'City',\n },\n {\n type: 'text',\n name: 'schema:event.addressRegion',\n title: 'Region/State',\n },\n {\n type: 'text',\n name: 'schema:event.postalCode',\n title: 'Postal Code',\n },\n {\n type: 'text',\n name: 'schema:event.addressCountry',\n title: 'Country',\n },\n ],\n },\n ],\n },\n ],\n },\n {\n name: 'agentsCredentialsAndAttributes',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Agents, Credentials, and Attributes',\n elements: [\n {\n type: 'paneldynamic',\n name: 'ixo:agentCard',\n title: 'Agents',\n templateElements: [\n {\n type: 'text',\n name: 'ixo:agentCard.id',\n title: 'Agent ID',\n },\n {\n type: 'text',\n name: 'ixo:agentCard.name',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'ixo:agentCard.description',\n title: 'Description',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'ixo:verifiableCredential',\n title: 'Credentials',\n templateElements: [\n {\n type: 'text',\n name: 'schema:ID',\n title: 'Credential ID',\n },\n {\n type: 'text',\n name: 'schema:Name',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'schema:description',\n title: 'Description',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'ixo:attribute',\n title: 'Attributes',\n templateElements: [\n {\n type: 'text',\n name: 'schema:ID_2',\n title: 'Attribute ID',\n },\n {\n type: 'text',\n name: 'schema:name_2',\n title: 'Name',\n },\n {\n type: 'text',\n name: 'schema:description_2',\n title: 'Description',\n },\n ],\n },\n ],\n },\n {\n name: 'project',\n visibleIf: '{ixo:advancedDomainSettings} = true',\n title: 'Project Information',\n description: 'Provide details about the related project(s), including objectives, sponsors, and deliverables.',\n elements: [\n {\n type: 'paneldynamic',\n name: 'pannel_proj:project',\n title: 'Projects',\n templateElements: [\n {\n type: 'text',\n name: 'proj:project.name',\n title: 'Project Title',\n },\n {\n type: 'comment',\n name: 'proj:project.description',\n title: 'Project Mission',\n description: 'High-level purpose or mission statement of the project.',\n },\n {\n type: 'paneldynamic',\n name: 'proj:project.hadObjective',\n title: 'Project Objectives',\n templateElements: [\n {\n type: 'comment',\n name: 'proj:hadObjective',\n title: 'Project Objective',\n },\n ],\n },\n {\n type: 'text',\n name: 'proj:plannedStart',\n title: 'Planned Start Date',\n inputType: 'datetime-local',\n },\n {\n type: 'text',\n name: 'proj:plannedEnd',\n title: 'Planned End Date',\n inputType: 'datetime-local',\n },\n {\n type: 'paneldynamic',\n name: 'proj:wasFundedThrough',\n title: 'Project Funding',\n templateElements: [\n {\n type: 'text',\n name: 'proj:moneyAmount',\n title: 'Funding Amount',\n },\n {\n type: 'text',\n name: 'proj:moneyCurrency',\n title: 'Funding Currency',\n },\n {\n type: 'text',\n name: 'prov.agent.name',\n title: 'Funder Name',\n },\n {\n type: 'text',\n name: 'prov:agent.id',\n title: 'Funder URL',\n inputType: 'url',\n },\n ],\n },\n ],\n },\n ],\n },\n {\n name: 'researchProfile',\n title: 'Research Profile',\n description: 'Provide information about the research profile associated with the domain.',\n elements: [\n {\n type: 'paneldynamic',\n name: 'ixo:ResearchProfile',\n title: 'Seed Queries',\n templateElements: [\n {\n type: 'comment',\n name: 'ixo:seedQueries',\n title: 'Seed Query',\n description: 'Seed keywords or queries that define the research scope.',\n },\n ],\n },\n {\n type: 'paneldynamic',\n name: 'schema:creativeWork',\n title: 'Citations',\n templateElements: [\n {\n type: 'text',\n name: 'schema:creativeWork.name',\n title: 'Citation Title',\n },\n {\n type: 'text',\n name: 'schema:creativeWork.url',\n title: 'Citation URL',\n },\n {\n type: 'text',\n name: 'schema:creativeWork.publisher',\n title: 'Publisher',\n },\n {\n type: 'text',\n name: 'schema:creativeWork.datePublished',\n title: 'Date Published',\n inputType: 'datetime-local',\n },\n ],\n },\n ],\n },\n ],\n showPageTitles: false,\n showQuestionNumbers: 'on',\n showProgressBar: true,\n progressBarLocation: 'top',\n};\n","import { registerAction } from '../registry';\nimport { parseMaybeJsonObject } from '../inputRequirements';\nimport { buildVerifiableCredential, buildDomainCardLinkedResource } from '@/core/lib/domainCard';\n\n/**\n * Map a schema.org-style credential type (e.g. `schema:Organization`) to the\n * on-chain entity type accepted by `createDomain`. Valid on-chain types are\n * `dao/pod`, `protocol`, `oracle`, `investment`, `project`, `asset`. Schema types\n * without a direct match fall back to `dao/pod`.\n */\nexport function resolveEntityTypeFromSchema(schemaType: string): string {\n const normalized = schemaType.replace(/^schema:/i, '').toLowerCase();\n const schemaToEntity: Record<string, string> = {\n organization: 'dao/pod',\n nonprofit: 'dao/pod',\n corporation: 'dao/pod',\n governmentorganization: 'dao/pod',\n };\n if (schemaToEntity[normalized]) return schemaToEntity[normalized];\n const allowed = new Set(['dao/pod', 'protocol', 'oracle', 'investment', 'project', 'asset']);\n return allowed.has(normalized) ? normalized : 'dao/pod';\n}\n\n/** Parse a JSON input that may be a string, object, or empty. */\nfunction parseJsonInput(value: unknown): Record<string, any> | null {\n if (!value) return null;\n if (typeof value === 'object' && !Array.isArray(value)) return value as Record<string, any>;\n if (typeof value === 'string') {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === 'object' ? parsed : null;\n } catch {\n return null;\n }\n }\n return null;\n}\n\nfunction parseContextInput(value: unknown): Array<{ key: string; val: string }> {\n let raw = value;\n if (typeof value === 'string') {\n try {\n raw = JSON.parse(value);\n } catch {\n raw = [];\n }\n }\n if (!Array.isArray(raw)) return [];\n\n return raw\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null;\n const key = String((entry as Record<string, unknown>).key || '').trim();\n const val = String((entry as Record<string, unknown>).val || '').trim();\n return key && val ? { key, val } : null;\n })\n .filter((entry): entry is { key: string; val: string } => entry !== null);\n}\n\ntype SelectedProtocolTemplate = {\n protocolDid: string;\n sourceRoomId: string;\n sourceLabel?: string;\n};\n\nfunction getSelectedProtocolTemplates(flowTemplateConfig: Record<string, any> | null): SelectedProtocolTemplate[] {\n const raw = flowTemplateConfig?.selectedTemplates;\n if (!Array.isArray(raw)) return [];\n\n return raw\n .map((item) => {\n if (!item || typeof item !== 'object') return null;\n const record = item as Record<string, unknown>;\n const protocolDid = String(record.protocolDid || '').trim();\n const sourceRoomId = String(record.sourceRoomId || '').trim();\n if (!protocolDid || !sourceRoomId) return null;\n const sourceLabel = String(record.sourceLabel || record.label || '').trim();\n return {\n protocolDid,\n sourceRoomId,\n ...(sourceLabel ? { sourceLabel } : {}),\n };\n })\n .filter((item): item is SelectedProtocolTemplate => item !== null);\n}\n\nfunction groupTemplatesByProtocol(templates: SelectedProtocolTemplate[]): Map<string, Array<{ sourceRoomId: string; sourceLabel?: string }>> {\n const grouped = new Map<string, Array<{ sourceRoomId: string; sourceLabel?: string }>>();\n for (const template of templates) {\n const existing = grouped.get(template.protocolDid) || [];\n existing.push({\n sourceRoomId: template.sourceRoomId,\n ...(template.sourceLabel ? { sourceLabel: template.sourceLabel } : {}),\n });\n grouped.set(template.protocolDid, existing);\n }\n return grouped;\n}\n\ntype DomainSignCheckpointStep =\n | 'createGovernanceGroup'\n | 'createDomain'\n | 'signAndUploadDomainCard'\n | 'addLinkedResource'\n | 'addParentLinkedEntity'\n | 'sourceDomainSpaces'\n | 'importTemplates';\n\ntype DomainSignCheckpoint = {\n invocationId: string;\n status: 'running' | 'completed' | 'failed';\n updatedAt: string;\n entityDid?: string;\n governanceGroupCoreAddress?: string;\n governanceGroupLinkedEntities?: any[];\n transactionHash?: string;\n linkedResourceTransactionHash?: string;\n parentEntityDid?: string;\n parentLinkedEntity?: { id: string; type: string; relationship: string; service: string };\n parentLinkedEntityTransactionHash?: string;\n domainCardLinkedResource?: ReturnType<typeof buildDomainCardLinkedResource>;\n flowTemplateConfig?: Record<string, any> | null;\n domainSpaces?: any;\n protocolTemplateImports?: Array<{ protocolDid: string; imported: any[] }>;\n output?: Record<string, any>;\n error?: string;\n completedSteps?: Partial<Record<DomainSignCheckpointStep, boolean>>;\n};\n\nconst DOMAIN_SIGN_CACHE_KEY = 'domainSign';\n\nfunction getDomainSignCheckpointKey(inputs: Record<string, unknown>, ctx: any): string {\n return String(ctx.pendingInvocation?.id || inputs.pendingInvocationId || inputs.invocationId || 'manual');\n}\n\nfunction readDomainSignCheckpoint(ctx: any, key: string): DomainSignCheckpoint | undefined {\n const cache = ctx.runtime?.get?.(ctx.nodeId)?.cache;\n const bucket = cache?.[DOMAIN_SIGN_CACHE_KEY];\n if (!bucket || typeof bucket !== 'object') return undefined;\n const checkpoint = (bucket as Record<string, unknown>)[key];\n return checkpoint && typeof checkpoint === 'object' ? (checkpoint as DomainSignCheckpoint) : undefined;\n}\n\nfunction writeDomainSignCheckpoint(ctx: any, key: string, checkpoint: DomainSignCheckpoint): void {\n if (!ctx.runtime?.get || !ctx.runtime?.update || !ctx.nodeId) return;\n const current = ctx.runtime.get(ctx.nodeId) || {};\n const cache = current.cache && typeof current.cache === 'object' ? current.cache : {};\n const bucket = cache[DOMAIN_SIGN_CACHE_KEY] && typeof cache[DOMAIN_SIGN_CACHE_KEY] === 'object' ? (cache[DOMAIN_SIGN_CACHE_KEY] as Record<string, unknown>) : {};\n ctx.runtime.update(ctx.nodeId, {\n cache: {\n ...cache,\n [DOMAIN_SIGN_CACHE_KEY]: {\n ...bucket,\n [key]: checkpoint,\n },\n },\n });\n}\n\nfunction buildCompletedDomainSignResult(output: Record<string, any>) {\n const payload = {\n entityDid: output.entityDid,\n governanceGroupCoreAddress: output.governanceGroupCoreAddress || '',\n transactionHash: output.transactionHash || '',\n linkedResourceTransactionHash: output.linkedResourceTransactionHash || '',\n ...(output.parentLinkedEntityTransactionHash ? { parentLinkedEntityTransactionHash: output.parentLinkedEntityTransactionHash } : {}),\n };\n\n return {\n output,\n events: [\n {\n name: 'created',\n payload,\n },\n ],\n };\n}\n\nfunction readDidInput(value: unknown): string {\n if (typeof value !== 'string') return '';\n const did = value.trim();\n if (!did || did === 'null' || did === 'undefined') return '';\n return did.startsWith('did:') ? did : '';\n}\n\nfunction getSelectedParentEntityDid(inputs: Record<string, unknown>): string {\n if (inputs.skipped === true || inputs.parentSkipped === true) return '';\n return readDidInput(inputs.selectedEntityDid) || readDidInput(inputs.parentDid) || readDidInput(inputs.parentDID);\n}\n\n/** Max times we re-prompt for the PIN before giving up and surfacing the error. */\nconst MAX_PIN_ATTEMPTS = 3;\n\n/**\n * A wrong PIN throws \"Invalid PIN - could not decrypt mnemonic\" (the mnemonic\n * is encrypted with the PIN, so a bad PIN fails decryption). This is a\n * recoverable, user-correctable error — re-prompt rather than failing the run.\n */\nfunction isInvalidPinError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /invalid pin|could not decrypt mnemonic/i.test(msg);\n}\n\n/**\n * Parse a duration string like '604800s' into amount + unit suitable for\n * the daodao group config (proposalDurationAmount / proposalDurationUnit).\n */\nfunction parseDuration(raw: string): { amount: number; unit: string } {\n const seconds = parseInt(raw, 10) || 0;\n if (seconds % (7 * 86400) === 0) return { amount: seconds / (7 * 86400), unit: 'weeks' };\n if (seconds % 86400 === 0) return { amount: seconds / 86400, unit: 'days' };\n if (seconds % 3600 === 0) return { amount: seconds / 3600, unit: 'hours' };\n if (seconds % 60 === 0) return { amount: seconds / 60, unit: 'minutes' };\n return { amount: seconds, unit: 'seconds' };\n}\n\n/**\n * Build the config object for `handlers.createGovernanceGroup` by transforming\n * the PODGovernance + member data from the barrier payload into the shape the\n * daodao message builders expect (CategoricalGroupConfig, MultisigGroupConfig,\n * NftStakingGroupConfig, or TokenStakingGroupConfig).\n *\n * Member identifiers are forwarded as DIDs in the address fields — the\n * consumer's message builders resolve them to bech32 account addresses\n * (`did:ixo:<address>` embeds the address) before anything reaches the chain.\n */\nfunction buildGroupConfig(groupType: string, governance: Record<string, any>, memberConfig: Record<string, any> | null): Record<string, unknown> {\n const duration = parseDuration(governance.votingPeriod || '604800s');\n const thresholdNum = parseFloat(governance.threshold || '0.51');\n const quorumNum = parseFloat(governance.quorum);\n const unstakingDuration = governance.unstakingDuration ? parseDuration(governance.unstakingDuration) : null;\n\n const baseConfig: Record<string, unknown> = {\n proposalDurationAmount: duration.amount,\n proposalDurationUnit: duration.unit,\n proposalSubmissionPolicy: 'members',\n voteSwitching: false,\n };\n\n // Pod governance thresholds are decimals of votes cast (0–1]; the builders\n // take percentages, paired with the quorum via threshold_quorum on-chain.\n const decisionPolicy: Record<string, unknown> = {\n passingThreshold: 'percentage',\n passingThresholdPercentage: Math.round(thresholdNum * 100),\n ...(Number.isFinite(quorumNum) && quorumNum > 0 ? { quorum: 'percentage', quorumPercentage: Math.round(quorumNum * 100) } : {}),\n };\n\n if (groupType === 'multisig') {\n const members = (memberConfig?.members || []) as Array<{ did: string }>;\n return {\n ...baseConfig,\n threshold: memberConfig?.multisigThreshold || 1,\n membershipCategory: [{ members: members.map((m) => m.did) }],\n };\n }\n\n if (groupType === 'nftStaking') {\n return {\n ...baseConfig,\n ...decisionPolicy,\n nftContractAddress: memberConfig?.nftContractAddress || '',\n ...(unstakingDuration ? { unstakingDurationAmount: unstakingDuration.amount, unstakingDurationUnit: unstakingDuration.unit } : {}),\n };\n }\n\n if (groupType === 'tokenStaking') {\n const tokenConfig = memberConfig?.tokenConfig || {};\n return {\n ...baseConfig,\n ...decisionPolicy,\n isExistingToken: Boolean(tokenConfig.isExistingToken),\n tokenAddress: tokenConfig.tokenAddress || '',\n tokenName: tokenConfig.tokenName || '',\n tokenSymbol: tokenConfig.tokenSymbol || '',\n tokenSupply: tokenConfig.tokenSupply || 0,\n distributionCategory: tokenConfig.distributionCategory || [],\n ...(unstakingDuration ? { unstakingDurationAmount: unstakingDuration.amount, unstakingDurationUnit: unstakingDuration.unit } : {}),\n };\n }\n\n // categorical (default)\n const members = (memberConfig?.members || []) as Array<{ did: string; role: string; votingPower: number }>;\n const byRole = new Map<string, { dids: string[]; weight: number }>();\n for (const m of members) {\n const role = m.role || 'member';\n const existing = byRole.get(role);\n if (existing) {\n existing.dids.push(m.did);\n } else {\n byRole.set(role, { dids: [m.did], weight: m.votingPower || 1 });\n }\n }\n\n return {\n ...baseConfig,\n ...decisionPolicy,\n membershipCategory: Array.from(byRole.entries()).map(([role, { dids, weight }]) => ({\n categoryName: role,\n members: dids.map((did) => ({ memberAddress: did })),\n weightPerMember: weight,\n })),\n };\n}\n\nregisterAction({\n type: 'qi/domain.sign',\n can: 'domain/sign',\n sideEffect: true,\n proof: { fields: ['entityDid'] },\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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; signed and used to create the domain.',\n },\n entityType: { type: 'string', description: 'Optional on-chain entity type; defaults from the credential type or dao/pod.' },\n governanceConfig: { type: 'object', description: 'Optional governance group config (object or JSON string) used to create a governance group.' },\n memberConfig: { type: 'object', description: 'Optional member config (object or JSON string) for the governance group.' },\n flowTemplateConfig: { type: 'object', description: 'Optional flow template config (object or JSON string) with selected protocol templates.' },\n context: { type: 'array', description: 'Optional context entries (array of { key, val } or JSON string) attached to the domain.' },\n selectedEntityDid: { type: 'string', description: 'Optional parent entity DID to link the new POD to.' },\n parentDid: { type: 'string', description: 'Optional parent entity DID (alternate field).' },\n parentDID: { type: 'string', description: 'Optional parent entity DID (alternate field).' },\n skipped: { type: 'boolean', description: 'Optional flag that skips parent entity linking.' },\n parentSkipped: { type: 'boolean', description: 'Optional flag that skips parent entity linking.' },\n pendingInvocationId: { type: 'string', description: 'Optional invocation ID used as the checkpoint key for resumable runs.' },\n invocationId: { type: 'string', description: 'Optional invocation ID used as the checkpoint key for resumable runs.' },\n },\n },\n\n outputSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'The DID of the newly created domain entity' },\n {\n path: 'governanceGroupCoreAddress',\n displayName: 'Governance Group Core Address',\n type: 'string',\n description: 'The core address of the created governance group, when one was created',\n },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The on-chain transaction hash for domain creation' },\n {\n path: 'linkedResourceTransactionHash',\n displayName: 'Linked Resource Transaction Hash',\n type: 'string',\n description: 'The on-chain transaction hash for adding the domain card linked resource',\n },\n {\n path: 'parentEntityDid',\n displayName: 'Parent Entity DID',\n type: 'string',\n description: 'The selected parent entity DID that was updated with the new POD linked entity',\n },\n {\n path: 'parentLinkedEntityTransactionHash',\n displayName: 'Parent Linked Entity Transaction Hash',\n type: 'string',\n description: 'The on-chain transaction hash for linking the new POD to the selected parent entity',\n },\n {\n path: 'flowTemplateConfig',\n displayName: 'Flow Template Config',\n type: 'object',\n description: 'Selected protocol templates captured before POD creation',\n },\n {\n path: 'domainSpaces',\n displayName: 'Domain Spaces',\n type: 'object',\n description: 'Matrix space structure sourced for the new domain',\n },\n {\n path: 'protocolTemplateImports',\n displayName: 'Protocol Template Imports',\n type: 'array',\n description: 'Import results for selected protocol templates',\n },\n ],\n\n events: [\n {\n name: 'created',\n displayName: 'Domain Created',\n description: 'Fires after the domain entity is successfully created on-chain.',\n payloadSchema: [\n { path: 'entityDid', displayName: 'Entity DID', type: 'string', description: 'DID of the newly created domain' },\n {\n path: 'governanceGroupCoreAddress',\n displayName: 'Governance Group Core Address',\n type: 'string',\n description: 'Core address of the created governance group, when present',\n },\n { path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'On-chain transaction hash' },\n {\n path: 'linkedResourceTransactionHash',\n displayName: 'Linked Resource Transaction Hash',\n type: 'string',\n description: 'On-chain transaction hash for adding the domain card linked resource',\n },\n {\n path: 'parentLinkedEntityTransactionHash',\n displayName: 'Parent Linked Entity Transaction Hash',\n type: 'string',\n description: 'On-chain transaction hash for linking the new POD to the selected parent entity',\n },\n ],\n pendingDisplayFields: ['entityDid', 'governanceGroupCoreAddress'],\n },\n ],\n\n // Mirrors run(): the card envelope (object or JSON string) must carry\n // credentialSubject.name before signing can start.\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, ctx) => {\n const handlers = ctx.handlers || {};\n\n // Parse domainCardData input\n let domainCardData: any;\n if (typeof inputs.domainCardData === 'string') {\n try {\n domainCardData = JSON.parse(inputs.domainCardData);\n } catch {\n throw new Error('domainCardData must be valid JSON');\n }\n } else if (inputs.domainCardData && typeof inputs.domainCardData === 'object') {\n domainCardData = inputs.domainCardData;\n } else {\n throw new Error('domainCardData is required');\n }\n\n if (!domainCardData?.credentialSubject?.name) {\n throw new Error('domainCardData is missing or invalid (credentialSubject.name required)');\n }\n\n // Determine entity type\n const entityType =\n String(inputs.entityType || '').trim() || (domainCardData.credentialSubject?.type?.[0] ? resolveEntityTypeFromSchema(domainCardData.credentialSubject.type[0]) : 'dao/pod');\n\n const validFrom = domainCardData.validFrom || new Date().toISOString();\n const validUntil =\n domainCardData.validUntil ||\n (() => {\n const d = new Date();\n d.setFullYear(d.getFullYear() + 100);\n return d.toISOString();\n })();\n\n const govConfig = parseJsonInput(inputs.governanceConfig);\n const memberConfig = parseJsonInput(inputs.memberConfig);\n const flowTemplateConfig = parseJsonInput(inputs.flowTemplateConfig);\n const context = parseContextInput(inputs.context);\n const selectedParentEntityDid = getSelectedParentEntityDid(inputs);\n const selectedProtocolTemplates = getSelectedProtocolTemplates(flowTemplateConfig);\n const checkpointKey = getDomainSignCheckpointKey(inputs, ctx);\n let checkpoint: DomainSignCheckpoint = readDomainSignCheckpoint(ctx, checkpointKey) || {\n invocationId: checkpointKey,\n status: 'running',\n updatedAt: new Date().toISOString(),\n completedSteps: {},\n };\n\n if (checkpoint.status === 'completed' && checkpoint.output) {\n return buildCompletedDomainSignResult(checkpoint.output);\n }\n\n if (!ctx.handlers) {\n throw new Error('Handlers not available');\n }\n\n if (typeof handlers.requestPin !== 'function') throw new Error('requestPin handler not available');\n if (typeof handlers.signCredential !== 'function') throw new Error('signCredential handler not implemented');\n if (typeof handlers.publicFileUpload !== 'function') throw new Error('publicFileUpload handler not available');\n if (typeof handlers.createDomain !== 'function') throw new Error('createDomain handler not implemented');\n if (typeof handlers.createAddLinkedResourceMessage !== 'function') throw new Error('createAddLinkedResourceMessage handler not implemented');\n if (typeof handlers.executeTransaction !== 'function') throw new Error('executeTransaction handler not implemented');\n // Captured after the guards above so the narrowed (non-undefined) types\n // survive into the step closures below.\n const { requestPin, signCredential, publicFileUpload } = handlers;\n\n const saveCheckpoint = (updates: Partial<DomainSignCheckpoint>): DomainSignCheckpoint => {\n checkpoint = {\n ...checkpoint,\n ...updates,\n invocationId: checkpointKey,\n updatedAt: new Date().toISOString(),\n completedSteps: {\n ...(checkpoint.completedSteps || {}),\n ...(updates.completedSteps || {}),\n },\n };\n writeDomainSignCheckpoint(ctx, checkpointKey, checkpoint);\n return checkpoint;\n };\n\n saveCheckpoint({\n status: 'running',\n error: undefined,\n flowTemplateConfig,\n });\n\n try {\n // Step 1: Create governance group if config arrived from barrier payload.\n let governanceGroupLinkedEntities: any[] = checkpoint.governanceGroupLinkedEntities || [];\n let governanceGroupCoreAddress = checkpoint.governanceGroupCoreAddress || '';\n\n if (govConfig && handlers.createGovernanceGroup && !checkpoint.completedSteps?.createGovernanceGroup) {\n const groupType = govConfig.groupType as string;\n const governance = (govConfig.governance || {}) as Record<string, any>;\n const config = buildGroupConfig(groupType, governance, memberConfig);\n\n const groupResult = await handlers.createGovernanceGroup({\n groupType: groupType as 'categorical' | 'multisig' | 'nftStaking' | 'tokenStaking',\n name: govConfig.groupName || domainCardData.credentialSubject?.name || 'Governance Group',\n config,\n });\n governanceGroupCoreAddress = groupResult.coreAddress;\n\n governanceGroupLinkedEntities = [\n {\n id: `{id}#${governanceGroupCoreAddress}`,\n type: 'group',\n relationship: 'governs',\n service: '',\n },\n ];\n\n saveCheckpoint({\n governanceGroupCoreAddress,\n governanceGroupLinkedEntities,\n completedSteps: { createGovernanceGroup: true },\n });\n } else if (!govConfig) {\n saveCheckpoint({ completedSteps: { createGovernanceGroup: true } });\n }\n\n // Get issuer DID\n const issuerDid = handlers.getEntityDid?.() || handlers.getCurrentUser?.()?.address;\n if (!issuerDid) throw new Error('Unable to determine issuer DID');\n\n const signAndUploadDomainCard = async (entityDid: string) => {\n const credentialSubject = {\n ...domainCardData.credentialSubject,\n id: entityDid,\n };\n\n const unsignedCredential = buildVerifiableCredential({\n entityDid,\n issuerDid,\n credentialSubject,\n validFrom,\n validUntil,\n });\n\n // Re-prompt for the PIN on an invalid-PIN failure instead of unwinding\n // the run. createDomain has already happened by this point, so failing\n // here would leave the user with a half-created POD and a \"Try Again\"\n // button; an inline re-prompt lets them recover without that.\n let signedCredential: Awaited<ReturnType<NonNullable<typeof handlers.signCredential>>>['signedCredential'] | undefined;\n for (let attempt = 1; attempt <= MAX_PIN_ATTEMPTS; attempt++) {\n const pin = await requestPin({\n title: 'Sign Domain Card',\n description: attempt === 1 ? 'Enter your PIN to sign the Domain Card credential' : 'Incorrect PIN. Re-enter your PIN to sign the Domain Card credential.',\n submitText: 'Sign',\n });\n // A cancelled prompt (falsy PIN) ends the loop cleanly rather than\n // re-prompting forever.\n if (!pin) throw new Error('PIN entry cancelled');\n\n try {\n ({ signedCredential } = await signCredential({\n issuerDid,\n issuerType: 'user',\n credential: unsignedCredential,\n pin,\n }));\n break;\n } catch (signError) {\n // Only an invalid PIN is retryable, and only while attempts remain;\n // anything else (or the final attempt) propagates to fail the run.\n if (isInvalidPinError(signError) && attempt < MAX_PIN_ATTEMPTS) continue;\n throw signError;\n }\n }\n\n // The loop only exits via `break` (success) or `throw`, so this is an\n // invariant — it also narrows the type away from `undefined`.\n if (!signedCredential) throw new Error('Failed to sign credential');\n\n const credentialBlob = new Blob([JSON.stringify(signedCredential, null, 2)], {\n type: 'application/json',\n });\n const credentialFile = new File([credentialBlob], 'domainCard.json', {\n type: 'application/json',\n });\n\n const uploadResult = await publicFileUpload(credentialFile);\n\n return {\n ...buildDomainCardLinkedResource({\n entityDid,\n cid: uploadResult.cid,\n serviceEndpoint: uploadResult.url,\n description: `Domain Card for ${domainCardData.credentialSubject?.name || 'Domain'}`,\n }),\n id: '{id}#dmn',\n };\n };\n\n const endDate = domainCardData.endDate || validUntil;\n let newEntityDid = checkpoint.entityDid || '';\n let transactionHash = checkpoint.transactionHash || '';\n let linkedResourceTransactionHash = checkpoint.linkedResourceTransactionHash || '';\n const parentEntityDid = checkpoint.parentEntityDid || selectedParentEntityDid;\n let parentLinkedEntity = checkpoint.parentLinkedEntity;\n let parentLinkedEntityTransactionHash = checkpoint.parentLinkedEntityTransactionHash || '';\n let domainCardLinkedResource = checkpoint.domainCardLinkedResource;\n\n // Unified path: create the entity first so the signed domain card and\n // linked resource use the real entity DID, then add the domain card as a\n // second transaction.\n if (!checkpoint.completedSteps?.createDomain || !newEntityDid || !transactionHash) {\n const createResult = await handlers.createDomain({\n entityType,\n context: context.length > 0 ? context : undefined,\n linkedResource: [],\n linkedEntity: governanceGroupLinkedEntities.length > 0 ? governanceGroupLinkedEntities : undefined,\n startDate: validFrom,\n endDate,\n });\n newEntityDid = createResult.entityDid;\n transactionHash = createResult.transactionHash;\n saveCheckpoint({\n entityDid: newEntityDid,\n transactionHash,\n completedSteps: { createDomain: true },\n });\n }\n\n if (!checkpoint.completedSteps?.signAndUploadDomainCard || !domainCardLinkedResource) {\n domainCardLinkedResource = await signAndUploadDomainCard(newEntityDid);\n saveCheckpoint({\n domainCardLinkedResource,\n completedSteps: { signAndUploadDomainCard: true },\n });\n }\n\n if (!checkpoint.completedSteps?.addLinkedResource || !linkedResourceTransactionHash) {\n const addLinkedResourceMessage = await handlers.createAddLinkedResourceMessage({\n entityDid: newEntityDid,\n linkedResource: domainCardLinkedResource,\n });\n const addLinkedResourceResult = await handlers.executeTransaction({\n messages: [addLinkedResourceMessage],\n memo: '',\n });\n linkedResourceTransactionHash = String(addLinkedResourceResult?.transactionHash || '');\n if (!linkedResourceTransactionHash) {\n throw new Error('Linked resource transaction completed but no transaction hash received');\n }\n saveCheckpoint({\n linkedResourceTransactionHash,\n completedSteps: { addLinkedResource: true },\n });\n }\n\n if (parentEntityDid && (!checkpoint.completedSteps?.addParentLinkedEntity || !parentLinkedEntityTransactionHash)) {\n if (typeof handlers.createAddLinkedEntityMessage !== 'function') {\n throw new Error('createAddLinkedEntityMessage handler not implemented');\n }\n\n parentLinkedEntity = parentLinkedEntity || {\n id: newEntityDid,\n type: entityType,\n relationship: 'manages',\n service: '',\n };\n\n const addParentLinkedEntityMessage = await handlers.createAddLinkedEntityMessage({\n entityDid: parentEntityDid,\n linkedEntity: parentLinkedEntity,\n });\n const addParentLinkedEntityResult = await handlers.executeTransaction({\n messages: [addParentLinkedEntityMessage],\n memo: '',\n });\n parentLinkedEntityTransactionHash = String(addParentLinkedEntityResult?.transactionHash || '');\n if (!parentLinkedEntityTransactionHash) {\n throw new Error('Parent linked entity transaction completed but no transaction hash received');\n }\n saveCheckpoint({\n parentEntityDid,\n parentLinkedEntity,\n parentLinkedEntityTransactionHash,\n completedSteps: { addParentLinkedEntity: true },\n });\n } else if (!parentEntityDid) {\n saveCheckpoint({ completedSteps: { addParentLinkedEntity: true } });\n }\n\n let domainSpaces: Awaited<ReturnType<NonNullable<typeof handlers.sourceDomainSpaces>>> | undefined = checkpoint.domainSpaces;\n let protocolTemplateImports: Array<{ protocolDid: string; imported: any[] }> = checkpoint.protocolTemplateImports || [];\n\n if (handlers.sourceDomainSpaces && (!checkpoint.completedSteps?.sourceDomainSpaces || !domainSpaces)) {\n domainSpaces = await handlers.sourceDomainSpaces({ entityDid: newEntityDid });\n if (!domainSpaces?.success) {\n throw new Error('Domain spaces could not be sourced for the newly created domain');\n }\n saveCheckpoint({\n domainSpaces,\n completedSteps: { sourceDomainSpaces: true },\n });\n } else if (!handlers.sourceDomainSpaces) {\n saveCheckpoint({ completedSteps: { sourceDomainSpaces: true } });\n }\n\n if (selectedProtocolTemplates.length > 0 && !checkpoint.completedSteps?.importTemplates) {\n if (!handlers.sourceDomainSpaces) {\n throw new Error('sourceDomainSpaces handler is required to import selected protocol templates');\n }\n if (!handlers.importProtocolTemplatesToSpace) {\n throw new Error('importProtocolTemplatesToSpace handler is required to import selected protocol templates');\n }\n\n const targetFlowsSubspaceId = domainSpaces?.subspaces?.['domain flows']?.space_id;\n if (!targetFlowsSubspaceId) {\n throw new Error('Domain flows subspace was not returned by sourceDomainSpaces');\n }\n\n const groupedTemplates = groupTemplatesByProtocol(selectedProtocolTemplates);\n protocolTemplateImports = await Promise.all(\n Array.from(groupedTemplates.entries()).map(async ([protocolDid, templates]) => {\n const result = await handlers.importProtocolTemplatesToSpace!({\n protocolDid,\n entityDid: newEntityDid,\n targetFlowsSubspaceId,\n templates,\n });\n return { protocolDid, imported: result.imported };\n })\n );\n saveCheckpoint({\n protocolTemplateImports,\n completedSteps: { importTemplates: true },\n });\n } else if (selectedProtocolTemplates.length === 0) {\n saveCheckpoint({\n protocolTemplateImports,\n completedSteps: { importTemplates: true },\n });\n }\n\n const output = {\n entityDid: newEntityDid,\n governanceGroupCoreAddress,\n linkedEntities: governanceGroupLinkedEntities,\n linkedResources: [domainCardLinkedResource],\n parentEntityDid,\n parentLinkedEntity,\n flowTemplateConfig,\n domainSpaces,\n protocolTemplateImports,\n transactionHash,\n linkedResourceTransactionHash,\n parentLinkedEntityTransactionHash,\n };\n\n saveCheckpoint({\n status: 'completed',\n output,\n });\n\n return buildCompletedDomainSignResult(output);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Domain sign failed';\n saveCheckpoint({\n status: 'failed',\n error: message,\n });\n throw error;\n }\n },\n});\n","import { registerAction } 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 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 { registerAction } from '../registry';\n\nregisterAction({\n type: 'oracle',\n can: 'oracle/query',\n sideEffect: false,\n proof: 'none',\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 companion.' },\n },\n },\n\n outputSchema: [{ path: 'prompt', displayName: 'Prompt', type: 'string', description: 'The prompt sent to the companion' }],\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 await ctx.handlers.askCompanion(prompt);\n\n return {\n output: { prompt },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/credential.store',\n can: 'credential/store',\n sideEffect: true,\n proof: { fields: ['storedAt'] },\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/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 { registerAction } 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 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\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 } from '../registry';\n\nregisterAction({\n type: 'qi/wallet.generate',\n can: 'wallet/generate',\n sideEffect: false,\n proof: { fields: ['address'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/wallet.fund',\n can: 'wallet/fund',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\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 base units (defaults to 250000).' },\n },\n },\n\n outputSchema: [{ path: 'transactionHash', displayName: 'Transaction Hash', type: 'string', description: 'The funding transaction hash' }],\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 const result = await ctx.services.oracle.fundWallet({\n address: inputs.address,\n amount: inputs.amount || 250000,\n });\n return { output: result };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/wallet.generateAndFund',\n can: 'wallet/generateAndFund',\n sideEffect: true,\n proof: { fields: ['transactionHash'] },\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 },\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 ],\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\n const fundResult = await ctx.services.oracle.fundWallet({\n address: walletResult.address,\n amount: inputs.amount || 250000,\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 },\n };\n },\n});\n","import { registerAction } from '../registry';\n\nregisterAction({\n type: 'qi/iid.create',\n can: 'iid/create',\n sideEffect: true,\n proof: { fields: ['transactionHash', 'alreadyExisted'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/matrix.register',\n can: 'matrix/register',\n sideEffect: true,\n proof: { fields: ['matrixUserId'] },\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 } 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 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 } from '../registry';\n\nregisterAction({\n type: 'qi/entity.createOracle',\n can: 'entity/createOracle',\n sideEffect: true,\n proof: { fields: ['entityDid'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/sandbox.provision',\n can: 'sandbox/provision',\n sideEffect: true,\n proof: { fields: ['status', 'sandboxUrl'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.contract',\n can: 'oracle/contract',\n sideEffect: true,\n proof: { fields: ['userOracleRoomId'] },\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 } 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 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 } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.storeConfig',\n can: 'oracle/storeConfig',\n sideEffect: true,\n proof: { fields: ['configStored'] },\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 } 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 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 } 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 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 } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deploySetup',\n can: 'oracle/deploySetup',\n sideEffect: true,\n proof: { fields: ['setupComplete'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deployStart',\n can: 'oracle/deployStart',\n sideEffect: true,\n proof: { fields: ['processId', 'status'] },\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 } from '../registry';\n\nregisterAction({\n type: 'qi/oracle.deploy',\n can: 'oracle/deploy',\n sideEffect: true,\n proof: { fields: ['processId', 'status'] },\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 type { FlowNode } from '../../types/authorization';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { FlowRuntimeStateManager } from '../flowEngine/runtime';\nimport type { PendingInvocation } from '../flowEngine/triggers';\n\n/**\n * The raw consumer handler bag (mantine `BlocknoteHandlers`), as visible to\n * action `run()` implementations via `ctx.handlers`. The real interface lives\n * in the mantine layer and cannot be imported here without a core→mantine\n * cycle, so this declares only the members actions actually call — loosely\n * typed, since the parameter shapes are owned by the consumer contract.\n *\n * There is deliberately NO index signature: calling an undeclared handler is a\n * compile error, so a renamed consumer handler surfaces here instead of\n * failing at runtime. Add the member when an action starts using a new\n * handler. Prefer `ctx.services.*` (the typed, adapted contract) over\n * `ctx.handlers` for new actions — this escape hatch exists for actions that\n * predate `buildServicesFromHandlers`.\n */\nexport interface ActionHandlers {\n askCompanion?: (prompt: string) => Promise<any>;\n vote?: (...args: any[]) => any;\n getPreProposalContractAddress?: (...args: any[]) => any;\n getGroupContractAddress?: (...args: any[]) => any;\n getProposalContractAddress?: (...args: any[]) => any;\n createProposal?: (...args: any[]) => any;\n getUserRoles?: (...args: any[]) => any;\n getClaimData?: (...args: any[]) => any;\n requestPin?: (...args: any[]) => any;\n signCredential?: (...args: any[]) => any;\n publicFileUpload?: (...args: any[]) => any;\n createDomain?: (...args: any[]) => any;\n createAddLinkedResourceMessage?: (...args: any[]) => any;\n executeTransaction?: (...args: any[]) => any;\n createGovernanceGroup?: (...args: any[]) => any;\n getEntityDid?: (...args: any[]) => any;\n getCurrentUser?: (...args: any[]) => any;\n createAddLinkedEntityMessage?: (...args: any[]) => any;\n sourceDomainSpaces?: (...args: any[]) => any;\n importProtocolTemplatesToSpace?: (...args: any[]) => any;\n integrations?: {\n executeTool?: (...args: any[]) => any;\n fetchCurrentState?: (...args: any[]) => any;\n getEntityDid?: (...args: any[]) => any;\n };\n}\n\nexport interface ActionContext {\n actorDid: string;\n flowId: string;\n nodeId: string;\n services: ActionServices;\n flowNode?: FlowNode;\n runtime?: FlowRuntimeStateManager;\n flowUri?: string;\n handlers?: ActionHandlers;\n editor?: IxoEditorType;\n pendingInvocation?: PendingInvocation;\n}\n\n/**\n * Lifecycle state of an IXO claims-module collection.\n *\n * Mirrors `ixo.claims.v1beta1.CollectionState` (the on-chain enum). Carried as\n * a numeric enum at this boundary so the consumer-side handler can map it\n * directly onto the SDK enum without a string lookup.\n *\n * - `OPEN` (0) — accepting claims/bids.\n * - `PAUSED` (1) — temporarily not accepting submissions.\n * - `CLOSED` (2) — permanently closed.\n */\nexport enum CollectionStateEnum {\n OPEN = 0,\n PAUSED = 1,\n CLOSED = 2,\n}\n\n/**\n * A single coin amount. Mirrors `cosmos.base.v1beta1.Coin`. `amount` is the\n * integer base-denom amount carried as a string (no `Long`/`bigint` at this\n * boundary).\n */\nexport interface CollectionCoin {\n denom: string;\n amount: string;\n}\n\n/**\n * A CW20 token payment leg. Mirrors `ixo.claims.v1beta1.CW20Payment`.\n */\nexport interface CollectionCW20Payment {\n address: string;\n /** Integer amount carried as a string. */\n amount: string;\n}\n\n/**\n * A CW1155 contract payment leg. Mirrors `ixo.claims.v1beta1.Contract1155Payment`.\n */\nexport interface CollectionContract1155Payment {\n address: string;\n tokenId: string;\n /** Integer amount carried as a string. */\n amount: string;\n}\n\n/**\n * One payment leg of a collection (submission / evaluation / approval /\n * rejection). Mirrors `ixo.claims.v1beta1.Payment`.\n *\n * Optional/empty legs are represented by an empty `amount` array. The consumer\n * handler fills `account` with the collection admin address when creating.\n */\nexport interface CollectionPayment {\n /** Destination/charging account address. */\n account: string;\n /** Native-coin amounts. Empty when this leg charges nothing in native coin. */\n amount: CollectionCoin[];\n /** Optional CW20 payment legs. */\n cw20Payment?: CollectionCW20Payment[];\n /** Optional CW1155 contract payment. */\n contract_1155Payment?: CollectionContract1155Payment;\n /** Optional payment timeout in nanoseconds, carried as a string. */\n timeoutNs?: string;\n /** Whether this leg is paid by the oracle rather than the claimant. */\n isOraclePayment?: boolean;\n}\n\n/**\n * The four payment legs of a collection. Mirrors `ixo.claims.v1beta1.Payments`.\n */\nexport interface Payments {\n submission?: CollectionPayment;\n evaluation?: CollectionPayment;\n approval?: CollectionPayment;\n rejection?: CollectionPayment;\n}\n\n/**\n * Per-intent configuration for a collection. Mirrors the\n * `ixo.claims.v1beta1.CollectionIntentOptions` shape — controls whether/how\n * claimants can declare an intent before submitting.\n */\nexport interface CollectionIntentOptions {\n /** Whether intents are enabled on this collection. */\n allowed?: boolean;\n /** Optional intent timeout in nanoseconds, carried as a string. */\n timeoutNs?: string;\n /** Optional per-intent payment override. */\n payment?: CollectionPayment;\n}\n\n/**\n * Parameters for creating a collection (`MsgCreateCollection`).\n *\n * `entity` and `protocol` are template configuration; the consumer resolves the\n * `signer`/admin from its own wallet context, so it is not part of this\n * boundary. `quota` is carried as a string (`0` = unlimited).\n */\nexport interface CollectionCreateParams {\n /** Entity (deed) DID the collection belongs to. */\n entity: string;\n /** Protocol DID/id the collection follows. */\n protocol: string;\n /** Initial lifecycle state. Defaults to OPEN if omitted by the consumer. */\n state?: CollectionStateEnum;\n /** ISO-8601 start date. */\n startDate?: string;\n /** ISO-8601 end date. */\n endDate?: string;\n /** Max number of claims; `0` = unlimited. Carried as a string. */\n quota?: string;\n /** Payment configuration for the four claim legs. */\n payments?: Payments;\n /** Intent configuration. */\n intents?: CollectionIntentOptions;\n}\n\n/**\n * The full, canonical on-chain state of a collection, returned by every\n * `collection.*` operation (read or write) and stored verbatim as\n * `runtime.output`. It is never a delta — see IXO-2573: `output` always holds\n * the latest full on-chain collection state.\n *\n * Field names mirror `ixo.claims.v1beta1.Collection`. Numeric chain types\n * (`Long`/uint64) are carried as strings; `state` is the numeric enum.\n */\nexport interface CollectionState {\n /** Collection identifier (the chain-assigned id). */\n collectionId: string;\n /** Entity (deed) DID the collection belongs to. */\n entity: string;\n /** Protocol DID/id the collection follows. */\n protocol: string;\n /** Admin address authorised to mutate the collection. */\n admin?: string;\n /** Current lifecycle state. */\n state: CollectionStateEnum;\n /** ISO-8601 start date, if set. */\n startDate?: string;\n /** ISO-8601 end date, if set. */\n endDate?: string;\n /** Max number of claims; `0` = unlimited. Carried as a string. */\n quota: string;\n /** Number of claims submitted so far. Carried as a string. */\n count: string;\n /** Number of claims evaluated so far. Carried as a string. */\n evaluated?: string;\n /** Number of approved claims. Carried as a string. */\n approved?: string;\n /** Number of rejected claims. Carried as a string. */\n rejected?: string;\n /** Number of disputed claims. Carried as a string. */\n disputed?: string;\n /** Payment configuration for the four claim legs. */\n payments?: Payments;\n /** Intent configuration. */\n intents?: CollectionIntentOptions;\n}\n\n/**\n * Role a grantee holds on a claim collection. Drives which custom claims-module\n * authorization is granted: `submit` → `SubmitClaimAuthorization`,\n * `evaluate` → `EvaluateClaimAuthorization` (each carries `[]constraints`, one\n * per collection). See IXO-2586.\n */\nexport type CollectionUserRole = 'submit' | 'evaluate';\n\n/**\n * How a grantee address is treated when adding it to a collection:\n * - `user` — a plain account; one grant.\n * - `group-account` — a DAO-core group account; one grant to the group itself.\n * Only offered when the group can exercise the grant (dao-core can MsgExec).\n * - `group-members` — fan out: enumerate the group's members and grant each\n * one individually.\n */\nexport type CollectionGranteeKind = 'user' | 'group-account' | 'group-members';\n\n/**\n * One per-collection authorization constraint held by a grantee for a role.\n * Carries the LIVE (decremented) limits as read back from chain — the revoke\n * read-modify-write must preserve these verbatim (IXO-2590), so re-granting\n * from a template would wrongly reset spent quota.\n */\nexport interface CollectionGrantee {\n /** Grantee bech32 address. */\n address: string;\n /** Optional resolved DID (display / audit). */\n did?: string;\n /** Role this grant confers. */\n role: CollectionUserRole;\n /** Remaining agent quota; `0` = unlimited. Carried as a string. */\n agentQuota?: string;\n /** Per-claim max amount cap (evaluate role). */\n maxAmount?: CollectionCoin[];\n /** Intent duration in nanoseconds, carried as a string. */\n intentDurationNs?: string;\n}\n\n/**\n * A member enumerated from a group account, used for grant fan-out. Mirrors the\n * `PODMember` shape produced by the `pod/memberMultiSelect` enumeration\n * (abstracts cw4 members / token-staking stakers / nft-staking / multisig\n * signers).\n */\nexport interface CollectionMember {\n address: string;\n did?: string;\n role?: string;\n votingPower?: number;\n}\n\n/**\n * DAO DAO classification of an address. On IXO both user accounts and CosmWasm\n * contracts share the `ixo1…` prefix, so classification is layered: bech32\n * byte-length heuristic → Wasm `ContractInfo` query → cw2 `{ \"info\": {} }`\n * smart query (IXO-2592).\n */\nexport interface AddressClassification {\n /** `user` = plain account; `contract` = CosmWasm contract / module account. */\n kind: 'user' | 'contract';\n /** Present when `kind === 'contract'` and cw2 info resolved a DAO DAO group type. */\n daodao?: {\n /** cw2 contract name family, e.g. `dao-dao-core`, `cw4-group`, `dao-voting-cw4`. */\n type: string;\n /** Whether the contract can itself exercise a granted authz (only dao-core can MsgExec). */\n canExerciseGrant: boolean;\n };\n}\n\n/**\n * Provenance/identity of a carbon batch (= a CARBON token group; the batch id\n * is the on-chain token id). `entityDid` + `adminAddress` identify the entity\n * admin account the batch was minted from — both are REQUIRED to construct a\n * harvest (the authz grant + exec transfer target that account). The host\n * `loadBatches` handler performs provenance recovery for transferred batches so\n * these are populated before the editor ever sees them. See the carbon-credit\n * technical doc §4–§5 (IXO-2675).\n */\nexport interface CarbonBatchRef {\n /** Token/batch id. */\n id: string;\n /** Minter entity DID. */\n entityDid: string;\n /** Entity admin account address (the FROM account for a harvest transfer). */\n adminAddress: string;\n /** Human-readable entity name, for display. */\n alsoKnownAs?: string;\n}\n\n/**\n * A harvestable batch: held on an entity admin account the user owns but not\n * yet pulled into their wallet. `claimable` = the admin-held amount that\n * becomes the user's on harvest.\n */\nexport interface CarbonHarvestableBatch extends CarbonBatchRef {\n /** Harvestable amount (admin-held; becomes user `amount` after harvest). */\n claimable: number;\n}\n\n/**\n * A retireable batch: credits the user already holds in their wallet and can\n * burn/offset. `entityDid` is best-effort (display/provenance) and not required\n * to retire — retirement is a single owner-signed message.\n */\nexport interface CarbonRetireableBatch {\n /** Token/batch id. */\n id: string;\n /** Amount available in the user's wallet to retire. */\n amount: number;\n /** Minter entity DID, when known. */\n entityDid?: string;\n /** Human-readable entity name, for display. */\n alsoKnownAs?: string;\n}\n\nexport interface HttpService {\n request: (params: { url: string; method: string; headers?: Record<string, string>; body?: any }) => Promise<{ status: number; headers: Record<string, string>; data: any }>;\n}\n\nexport interface EmailService {\n send: (params: {\n to: string;\n subject: string;\n template: string;\n templateVersion?: string;\n variables?: Record<string, any>;\n cc?: string;\n bcc?: string;\n replyTo?: string;\n }) => Promise<{ messageId: string; sentAt: string }>;\n}\n\nexport interface NotifyService {\n send: (params: {\n channel: string;\n to: string[];\n cc?: string[];\n bcc?: string[];\n subject?: string;\n body?: string;\n bodyType?: 'text' | 'html';\n from?: string;\n replyTo?: string;\n }) => Promise<{ messageId: string; sentAt: string }>;\n}\n\nexport interface BidService {\n submitBid: (params: { collectionId: string; role: string; surveyAnswers: Record<string, any>; entityDid?: string; onBehalfOfAddress?: string }) => Promise<any>;\n approveBid: (params: { bidId: string; collectionId: string; did: string; entityDid?: string }) => Promise<any>;\n rejectBid: (params: { bidId: string; collectionId: string; did: string; reason: string; entityDid?: string }) => Promise<any>;\n approveServiceAgentApplication: (params: { adminAddress: string; collectionId: string; agentQuota: number; deedDid: string; currentUserAddress: string }) => Promise<void>;\n approveEvaluatorApplication: (params: {\n adminAddress: string;\n collectionId: string;\n deedDid: string;\n evaluatorAddress: string;\n agentQuota?: number;\n claimIds?: string[];\n maxAmounts?: Array<{ denom: string; amount: string }>;\n }) => Promise<void>;\n}\n\nexport interface ClaimService {\n requestPin: (config?: { title?: string; description?: string; submitText?: string }) => Promise<string>;\n submitClaim: (params: { surveyData: any; deedDid: string; collectionId: string; adminAddress: string; pin: string; entityDid?: string }) => Promise<{\n transactionHash: string;\n claimId: string;\n }>;\n evaluateClaim: (\n granteeAddress: string,\n did: string,\n payload: {\n claimId: string;\n collectionId: string;\n adminAddress: string;\n status?: number;\n verificationProof: string;\n amount?: { denom: string; amount: string };\n }\n ) => Promise<{\n code: number;\n transactionHash: string;\n rawLog?: string;\n height?: number;\n txIndex?: number;\n gasWanted?: bigint;\n gasUsed?: bigint;\n }>;\n disputeClaim?: (\n granteeAddress: string,\n did: string,\n payload: {\n subjectId: string;\n disputeType: number;\n reason: string;\n }\n ) => Promise<any>;\n getCurrentUser: () => { address: string; did?: string };\n createUdid?: (params: any) => Promise<any>;\n}\n\n/**\n * Claims-module collection lifecycle service. The editor declares the\n * contract only; the consumer app implements each method (broadcast on chain,\n * resolve admin from its wallet context, map string<->Long).\n *\n * Per IXO-2573, each write op should broadcast then the dispatcher re-fetches\n * via `get(...)` so `runtime.output` always holds the latest full\n * `CollectionState`. `get` is the read-only `refresh` primitive.\n */\nexport interface CollectionService {\n /** Read the full current on-chain state of a collection. */\n get: (params: { collectionId: string }) => Promise<CollectionState>;\n /** Broadcast `MsgCreateCollection`. Returns the new collectionId + tx hash. */\n create: (params: CollectionCreateParams) => Promise<{ transactionHash: string; collectionId: string }>;\n /** Broadcast `MsgUpdateCollectionState`. */\n updateState: (params: { collectionId: string; state: CollectionStateEnum; adminAddress: string }) => Promise<{ transactionHash: string }>;\n /** Broadcast `MsgUpdateCollectionDates`. */\n updateDates: (params: { collectionId: string; startDate?: string; endDate?: string; adminAddress: string }) => Promise<{ transactionHash: string }>;\n /** Broadcast `MsgUpdateCollectionQuota`. `quota` carried as a string; `0` = unlimited. */\n updateQuota: (params: { collectionId: string; quota: string; adminAddress: string }) => Promise<{ transactionHash: string }>;\n /** Broadcast `MsgUpdateCollectionPayments`. */\n updatePayments: (params: { collectionId: string; payments: Payments; adminAddress: string }) => Promise<{ transactionHash: string }>;\n /** Broadcast `MsgUpdateCollectionIntents`. */\n updateIntents: (params: { collectionId: string; intents: CollectionIntentOptions; adminAddress: string }) => Promise<{ transactionHash: string }>;\n}\n\n/**\n * Claim-collection user-management service (IXO-2586). The editor declares the\n * contract only; the consumer app implements each method (build/broadcast the\n * claims-module authz messages, query authz grants, classify addresses,\n * enumerate group members). Extends → replaces the reactive `bid` service.\n */\nexport interface CollectionUsersService {\n /**\n * Grant submit/evaluate authz for ONE collection to a grantee. The handler\n * reads the grantee's existing authz for the role's msgTypeUrl and APPENDS a\n * per-collection constraint (preserving other collections' live values),\n * then broadcasts `MsgCreateClaimAuthorization` routed via\n * `MsgGrantEntityAccountAuthz` (entity admin = granter). See IXO-2589.\n */\n grant: (params: {\n granterAdminAddress: string;\n granteeAddress: string;\n collectionId: string;\n role: CollectionUserRole;\n agentQuota?: string;\n maxAmount?: CollectionCoin[];\n intentDurationNs?: string;\n deedDid?: string;\n }) => Promise<{ transactionHash: string }>;\n /**\n * Per-collection read-modify-write revoke (IXO-2590). Reads the grantee's\n * live authz, drops the target collection's constraint, and — when other\n * constraints remain — broadcasts a single atomic tx ordered\n * `[MsgRevokeEntityAccountAuthz, then one MsgCreateClaimAuthorization per\n * remaining constraint]`, preserving each remaining constraint's live\n * (decremented) quota/limits. Short-circuits to a plain revoke when the\n * target was the only constraint.\n */\n revoke: (params: { granterAdminAddress: string; granteeAddress: string; collectionId: string; role: CollectionUserRole }) => Promise<{ transactionHash: string }>;\n /**\n * List the grantees holding a submit/evaluate constraint for a collection.\n * Queries authz grants against the entity admin account, decodes the\n * authorizations, and filters constraints by `collectionId` (IXO-2591).\n */\n list: (params: { granterAdminAddress: string; collectionId: string }) => Promise<{ grantees: CollectionGrantee[] }>;\n /** Classify an address as a plain user vs a DAO DAO contract (IXO-2592). */\n classifyAddress: (params: { address: string }) => Promise<AddressClassification>;\n /** Enumerate the members of a group account for grant fan-out (IXO-2592). */\n enumerateMembers: (params: { groupAddress: string }) => Promise<{ members: CollectionMember[] }>;\n}\n\nexport interface MatrixCredentialService {\n storeCredential: (params: { roomId: string; credentialKey: string; credential: Record<string, any>; cid: string }) => Promise<{ storedAt: string; duplicate: boolean }>;\n}\n\n/** Result of any integration tool execution (direct or via a binding). */\nexport interface IntegrationExecuteOutcome {\n successful: boolean;\n data?: Record<string, unknown>;\n error?: string;\n code?: 'OK' | 'VALIDATION' | 'AUTH_EXPIRED' | 'UPSTREAM_4XX' | 'UPSTREAM_5XX' | 'RATE_LIMIT' | 'UNKNOWN';\n}\n\n/**\n * The author-authorised connection a delegated block stores in its template\n * config. Holds only opaque references — never a credential. Clones verbatim\n * from template to flow; runners execute against it without connecting\n * anything. The binding lives on the worker keyed by `bindingId`; expiry (if\n * the underlying OAuth dies) surfaces at execute time, not as a stored field.\n */\nexport interface BoundConnection {\n /** Opaque, template-scoped reference to the author's stored credential. */\n bindingId: string;\n /** The underlying platform account id (for display / ownership only). */\n connectedAccountId: string;\n /** Toolkit slug, e.g. 'gmail'. Kept as a plain string for core portability. */\n toolkit: string;\n /** Human label captured at bind time, e.g. \"you@ixo.world\". */\n label: string | null;\n}\n\nexport interface IntegrationsService {\n executeTool: (args: { toolSlug: string; connectedAccountId: string; arguments: Record<string, unknown> }) => Promise<IntegrationExecuteOutcome>;\n fetchCurrentState?: (args: { toolSlug: string; connectedAccountId: string; arguments: Record<string, unknown> }) => Promise<Record<string, unknown>>;\n getEntityDid?: () => string | undefined;\n /**\n * Execute a tool on the template author's behalf via an opaque, server-side\n * binding (delegated blocks). The runner never holds the author's\n * credential — `bindingId` selects it on the worker. Returns the same\n * outcome shape as `executeTool`.\n */\n executeBinding?: (args: { bindingId: string; toolSlug: string; arguments: Record<string, unknown> }) => Promise<IntegrationExecuteOutcome>;\n}\n\nexport interface OracleService {\n // Note: oracle handlers are single-network. The consumer-side handler\n // resolves the chain network and matrix homeserver from its own\n // DefaultChainNetwork — the editor never passes them in.\n generateWallet: () => Promise<{\n address: string;\n did: string;\n pubKey: string;\n mnemonic: string;\n }>;\n fundWallet: (params: { address: string; amount: number }) => Promise<{ transactionHash: string }>;\n createIidDocument: (params: { mnemonic: string; did: string; address: string; pubKey: string }) => Promise<{ did: string; transactionHash: string }>;\n registerMatrixAccount: (params: { mnemonic: string; address: string; did: string; pin: string; oracleName: string; avatarUrl?: string }) => Promise<{\n matrixUserId: string;\n matrixAccessToken: string;\n matrixRoomId: string;\n matrixDeviceId: string;\n matrixMnemonic: string;\n matrixPassword: string;\n matrixRecoveryPhrase: string;\n matrixHomeServerUrl: string;\n }>;\n createOracleEntity: (params: {\n mnemonic: string;\n address: string;\n did: string;\n pubKey: string;\n pin: string;\n matrixAccessToken: string;\n matrixRoomId: string;\n oracleName: string;\n orgName: string;\n description: string;\n location: string;\n logoUrl: string;\n coverImageUrl: string;\n apiUrl: string;\n price: number;\n llmModel: string;\n opening?: string;\n communicationStyle?: string;\n capabilities?: string;\n mcpConfig?: any;\n parentProtocol?: string;\n }) => Promise<{\n entityDid: string;\n transactionHash: string;\n /** Multibase-encoded P-256 public key registered as a keyAgreement vm on the oracle entity DID. */\n encryptionPublicKeyMultibase: string;\n /** DID verification method id of the P-256 keyAgreement key. */\n encryptionVerificationMethodId: string;\n }>;\n /**\n * Contract the oracle: ensure the user↔oracle Matrix DM room exists and\n * the user has joined it. Pure Matrix work — no chain calls, no key setup.\n * Returns the user↔oracle room id which downstream steps (storeSecrets,\n * storeConfig) write into.\n */\n contract: (params: { oracleEntityDid: string }) => Promise<{\n userOracleRoomId: string;\n userOracleRoomAlias: string;\n }>;\n provisionSandbox: (params: { entityDid: string; matrixRoomId: string }) => Promise<{ sandboxUrl: string; status: string }>;\n storeSecrets: (params: {\n matrixRoomId: string;\n publicKeyMultibase: string;\n verificationMethodId: string;\n // For fresh mxLogin → fresh MATRIX_ORACLE_ADMIN_ACCESS_TOKEN value\n matrixHomeServerUrl: string;\n matrixUsername: string;\n matrixPassword: string;\n // Plaintext secrets — handler JWE-encrypts to oracle pubkey before sending\n secrets: Record<string, string>;\n // Already JWE-encrypted secrets — handler writes them to the room as-is\n preEncryptedSecrets?: Record<string, string>;\n }) => Promise<{ storedSecrets: string[]; roomId: string; freshAccessToken?: string }>;\n /** JWE-encrypts a single plaintext value to the oracle's P-256 public key (multibase).\n * Used by storeSecrets FlowDetail to encrypt user-typed OpenRouter key at-rest. */\n encryptForOracle: (params: { plaintext: string; publicKeyMultibase: string }) => Promise<{ jwe: string }>;\n /** Reads `ixo.room.secret.index` state events from the matrix room and returns the\n * list of secret names already stored. Used for idempotency checks. */\n readStoredSecrets: (params: { matrixRoomId: string }) => Promise<{ secretNames: string[] }>;\n /** Returns the network-derived .env constants (RPC URL, matrix homeserver, etc.)\n * for the consumer's currently configured network. Used by the storeSecrets\n * FlowDetail's \"Additional Configuration\" display section, and merged into the\n * storeConfig state event by the consumer handler. Must be deterministic per network. */\n getNetworkConstants: (params: { oracleName: string }) => Promise<{\n constants: Record<string, string>;\n }>;\n validateMcpServer: (params: { url: string; authType?: 'bearer' | 'api-key' | 'none'; authToken?: string }) => Promise<{\n success: boolean;\n tools?: Array<{ name: string; description?: string }>;\n error?: string;\n }>;\n storeConfig: (params: {\n matrixRoomId: string;\n config: {\n oracleName: string;\n orgName: string;\n description: string;\n location: string;\n price: number;\n apiUrl: string;\n entityDid: string;\n logoUrl: string;\n llmModel: string;\n opening?: string;\n communicationStyle?: string;\n capabilities?: string;\n skills?: string[];\n mcpServers?: Array<{ name: string; url: string; description?: string; authEnvVar?: string }>;\n matrixUserId?: string;\n matrixAccountRoomId?: string;\n oracleAddress?: string;\n oracleDid?: string;\n };\n }) => Promise<{ configStored: boolean; roomId: string }>;\n deploySetup: (params: {\n name: string;\n config: Record<string, any>;\n roomId: string;\n secrets?: Record<string, string>;\n }) => Promise<{ setupComplete: boolean; stdout?: string; stderr?: string }>;\n deployStart: (params: { name: string; entityDid: string; roomId: string; secrets?: Record<string, string> }) => Promise<{ processId: string; status: string; url?: string }>;\n updateOracleDomain: (params: { entityDid: string; newApiUrl: string }) => Promise<{ transactionHash: string }>;\n}\n\n/**\n * Carbon credit batch service (IXO-2675). The editor declares the contract\n * only; the consumer app implements each method (run the owner/admin\n * reconciliation read, build + broadcast the harvest grant/exec pair and the\n * retire message, sign via its own wallet/SignX). Both writes are USER-signed\n * — the editor never signs on the user's behalf.\n */\nexport interface CarbonService {\n /**\n * Reconcile the user's owner-side and entity-admin-side batches into the\n * unified view. Pure read (no signing). Performs provenance recovery for\n * transferred batches so every `harvestableBatch` carries `entityDid` +\n * `adminAddress`. See technical doc §3–§4.\n */\n loadBatches: (params: { ownerAddress: string }) => Promise<{\n harvestableBatches: CarbonHarvestableBatch[];\n retireableBatches: CarbonRetireableBatch[];\n totalClaimable: number;\n totalAvailable: number;\n totalRetired: number;\n }>;\n /**\n * Harvest (claim) the given batches: per entity, grant the owner authz to\n * transfer out of the entity admin account, then exec that transfer into\n * the owner's wallet (ordered pairs, 30-min grant). User-signed. See §5.2.\n */\n harvest: (params: {\n ownerAddress: string;\n tokens: Array<{ id: string; entityDid: string; adminAddress: string; claimable: number }>;\n }) => Promise<{ transactionHash: string; harvestedBatchIds: string[]; harvestedAmount: number }>;\n /**\n * Retire (burn/offset) the given amounts from the owner's wallet. Single\n * owner-signed `MsgRetireToken`. Irreversible. `jurisdiction` arrives\n * pre-composed as a string (default \"Global\"); `reason` defaults to\n * \"offset\". See §5.1.\n */\n retire: (params: {\n owner: string;\n reason?: string;\n jurisdiction?: string;\n tokens: Array<{ id: string; amount: number }>;\n }) => Promise<{ transactionHash: string; retiredBatchIds: string[]; retiredAmount: number }>;\n}\n\n/**\n * Entity (domain) ownership service (IXO-2696). The editor declares the\n * contract only; the consumer app implements `transfer` — resolve a group\n * recipient to its DAO controller, ensure the recipient has an IID document,\n * build + broadcast `MsgTransferEntity`, and sign via its own wallet/SignX.\n * USER-signed and IRREVERSIBLE — the editor never signs on the user's behalf.\n */\nexport interface EntityService {\n /**\n * Transfer ownership of `entityDid` to `recipientDid`. The consumer resolves\n * a `did:ixo:entity:` group recipient to its `did:ixo:wasm:` controller\n * (reported back as `recipientResolved` when changed) and creates the\n * recipient's IID document first if it is missing (`createdRecipientIid`).\n * `ownerDid`/`ownerAddress` default to the connected user inside the host.\n * Proof of a real transfer is the returned `transactionHash`.\n */\n transfer: (params: {\n entityDid: string;\n recipientDid: string;\n ownerDid?: string;\n ownerAddress?: string;\n }) => Promise<{ transactionHash: string; recipientResolved?: string; createdRecipientIid?: boolean }>;\n}\n\n/**\n * KYC verification service (qi/kyc.verify). The editor declares the contract\n * only; the consumer app implements each method against its KYC server\n * (create/read the ComplyCube evaluation, mint the hosted verification URL,\n * persist the SD-JWT credential to the user's Matrix vault). The server's\n * status is the single source of truth for the lifecycle\n * (`verify → review → clear → issuing → issued → complete`, failure states\n * `rejected|attention|error`, plus `unknown`) — the editor only polls it.\n *\n * PII boundary: survey answers flow INTO `initiate` but never back out —\n * action outputs carry only `credentialCid`, `credentialType`, `protocolId`,\n * and `status`.\n */\nexport interface KycService {\n /**\n * Load the KYC protocol's details form + the user's current server-side\n * state. `credentialType` is the vault index key of the credential this\n * protocol issues (e.g. 'kycamllevel1' | 'kycamllevel2'); hosts default it\n * to level 1 when omitted — `hasExistingCredential` refers to THAT type\n * only, so a level-2 flow is never satisfied by a level-1 credential.\n */\n loadForm(params: { protocolDid: string; credentialType?: string }): Promise<{\n protocolId: string;\n claimCollectionId?: string;\n deedOfferId?: string;\n surveyJson: Record<string, unknown>;\n hasExistingCredential: boolean;\n /** Non-PII metadata of matching Vault credentials, oldest first. */\n existingCredentials?: Array<{ cid: string; credentialType: string; storedAt?: string; issuerDid?: string }>;\n status: string;\n }>;\n /** Submit the details form; the server creates the ComplyCube evaluation. */\n initiate(params: { protocolId: string; claimCollectionId?: string; deedOfferId?: string; data: Record<string, unknown> }): Promise<{ status: string }>;\n /** Mint the hosted-webview verification URL for the user's evaluation. */\n getVerificationUrl(params: { protocolId: string }): Promise<{ url: string }>;\n /** Read the current server-side lifecycle status. */\n getStatus(params: { protocolId: string }): Promise<{ status: string }>;\n /**\n * Save the issued SD-JWT credential to the user's Matrix vault room and\n * move the server status to `complete`. Idempotent — re-saving an\n * already-saved credential of the same `credentialType` returns the\n * existing CID (defaults to level 1 when omitted).\n */\n saveCredential(params: { protocolId: string; credentialType?: string; credentialCid?: string }): Promise<{ credentialCid: string; credentialType: string }>;\n}\n\nexport interface BlueprintService {\n execute(params: { action: string; inputs: Record<string, unknown>; actorDid: string; flowId: string; nodeId: string }): Promise<{\n receiptRef: string;\n result?: Record<string, unknown>;\n }>;\n}\n\n/**\n * The full service contract an action execution context can carry. Composed\n * from the per-domain service interfaces above so consumers can implement and\n * type one domain at a time; the runtime shape is unchanged.\n */\nexport interface ActionServices {\n blueprint?: BlueprintService;\n http?: HttpService;\n email?: EmailService;\n notify?: NotifyService;\n bid?: BidService;\n claim?: ClaimService;\n collection?: CollectionService;\n collectionUsers?: CollectionUsersService;\n matrix?: MatrixCredentialService;\n integrations?: IntegrationsService;\n oracle?: OracleService;\n carbon?: CarbonService;\n entity?: EntityService;\n kyc?: KycService;\n}\n\nexport interface OutputSchemaField {\n path: string;\n displayName: string;\n type: 'string' | 'number' | 'boolean' | 'object' | 'array';\n description?: string;\n /**\n * For `type === 'array'`: the shape of each element. Drives item-scoped\n * reference pickers (e.g. the Xero invoice LineItems iterative mapper,\n * where each cell refs into `{{item.<field>}}`).\n */\n itemSchema?: OutputSchemaField[];\n}\n\n/**\n * A typed event that an action can emit when it runs.\n *\n * Events drive the trigger/listener model: another block can declare a\n * `block.event` trigger on a (sourceBlockId, eventName) pair, and when this\n * action emits a matching event, a pending invocation is queued on the\n * listener block. See `docs/flow-engine/events-and-triggers-plan.md` for the full model.\n */\nexport interface ActionEventDefinition {\n /** Stable identifier — used in trigger declarations and ref strings. */\n name: string;\n /** Human-readable label shown in the trigger picker UI. */\n displayName: string;\n /** Short description shown as inline hint in the trigger picker. */\n description: string;\n /** Schema of the event payload. Same shape as `outputSchema`. */\n payloadSchema: OutputSchemaField[];\n /**\n * Field paths from `payloadSchema` (in order) shown inline in the\n * pending-invocation list so the assignee can distinguish queued\n * invocations at a glance. E.g. `['claimId', 'evaluatedAt']`.\n */\n pendingDisplayFields?: string[];\n}\n\n/**\n * Declares what counts as proof that this action's side effect actually\n * happened. Enforced centrally by `executeActionBlock`: a run that returns\n * success without satisfying its proof declaration is recorded as\n * `state: 'failed'` (code `PROOF_MISSING`), never as `completed`.\n *\n * - `{ fields }` — at least one of the listed output paths (dot notation\n * allowed) must be truthy. Empty arrays and `false` do not count.\n * - `{ validate }` — custom predicate over the raw output.\n * - `'none'` — explicit opt-out for actions with no side effect to prove\n * (pure selection/config actions). Must be stated, not omitted.\n */\nexport type ActionProofDeclaration = { fields: string[] } | { validate: (output: Record<string, unknown>) => boolean } | 'none';\n\nexport interface ActionDefinition<TInputs extends Record<string, any> = Record<string, any>> {\n type: string;\n\n /** UCAN-style ability string used by the flow compiler, e.g., \"bid/submit\". */\n can?: string;\n\n // Policy\n sideEffect: boolean;\n defaultRequiresConfirmation: boolean;\n requiredCapability?: string;\n\n /**\n * Who performs the execution once inputs are complete.\n *\n * - 'agent' (the default) — a headless orchestrator may run `run()` itself\n * or delegate it to a capable oracle.\n * - 'human' — only a human surface (Portal FlowDetail) may execute: the\n * side effect needs an authority the orchestrator does not hold, e.g. a\n * chain transaction signed as the entity admin. Orchestrators still\n * gather inputs and notify the human, but must never run or delegate\n * the action themselves.\n */\n executionOwner?: 'agent' | 'human';\n\n /** Proof-of-execution declaration. See {@link ActionProofDeclaration}. */\n proof: ActionProofDeclaration;\n\n /**\n * How many times this action is meant to run within a single flow.\n *\n * - 'once' (the default) — a one-shot step that reaches a terminal\n * `completed` state and is then Done.\n * - 'many' — a standing, repeatable capability that can fire any number of\n * times on a cadence the flow (not the action) decides — e.g. submitting a\n * claim every month. A repeatable block never latches to a terminal Done:\n * a `completed` runtime entry means \"has fired at least once\", and its real\n * progress is the count of successful runs in the audit trail, not this\n * single summary entry. Such blocks never withhold the flow.\n */\n cardinality?: 'once' | 'many';\n\n /**\n * How dynamic resolver results combine with the static `events` /\n * `outputSchema` baselines. 'merge' (the default) dedupes by event name /\n * field path with the dynamic entry winning; 'replace' hands the resolver\n * full control of the vocabulary (needed e.g. to hide the baseline until\n * configuration is complete).\n */\n dynamicResolutionMode?: 'merge' | 'replace';\n\n // Validation (optional, wire JSON Schema later)\n inputSchema?: object;\n\n /**\n * Machine-readable mirror of the required-input preamble in `run()`: given a\n * fully-merged inputs object, returns the names of inputs still missing or\n * blank (empty array = ready to execute). External orchestrators call this\n * via `getMissingActionInputs` BEFORE queuing execution so a missing input\n * becomes a prompt to a human rather than a failed run.\n *\n * Only define this when requiredness is conditional — it branches on other\n * inputs (skip flags, group types, either-of-two-fields) and therefore\n * cannot be derived from `inputSchema.required`, which is the default\n * derivation. Keep it directly above `run()` and keep the two in lockstep:\n * every presence throw in `run()` must be predicted here. Presence only —\n * value validity (ranges, formats, duplicates) stays in `run()`.\n */\n getMissingInputs?: (inputs: TInputs) => string[];\n\n /** Static output schema for action types with predictable output (e.g. email.send).\n * For action types with dynamic output (e.g. http.request), the schema is user-defined in inputs. */\n outputSchema?: OutputSchemaField[];\n\n /**\n * Typed vocabulary of events this action can emit. Drives the trigger\n * picker UI and compile-time validation of `block.event` triggers.\n */\n events?: ActionEventDefinition[];\n\n /**\n * Optional per-block event resolver. Called with the block's current\n * template inputs; returns the event vocabulary that applies to this\n * specific block.\n *\n * Use this when the event schema depends on configuration the designer\n * picks at template time. For example, `qi/claim.submit` only knows the\n * shape of `surveyAnswers` once a claim collection has been chosen —\n * returning `[]` until then hides the block from the trigger picker.\n *\n * Consumers (trigger picker, flow compiler, event payload picker) prefer\n * `getDynamicEvents(inputs)` when defined and fall back to static `events`\n * otherwise. By default the result is MERGED with the static `events`\n * baseline (deduped by name, dynamic wins). Set\n * `dynamicResolutionMode: 'replace'` when the resolver must control the\n * full vocabulary (e.g. returning [] to hide the baseline).\n */\n getDynamicEvents?: (inputs: TInputs) => ActionEventDefinition[];\n\n /**\n * Optional per-block output-schema resolver. Symmetric to `getDynamicEvents`\n * but for `outputSchema` — drives the reference picker for `${block.field}`\n * refs so survey-derived fields like `output.surveyAnswers.<question>` show\n * up alongside the static baseline.\n *\n * By default the returned array is MERGED with the static `outputSchema`\n * baseline (deduped by path, dynamic wins); `dynamicResolutionMode:\n * 'replace'` gives the resolver full control.\n */\n getDynamicOutputSchema?: (inputs: TInputs) => OutputSchemaField[];\n\n /**\n * Whether this action can be wired to a `block.event` trigger.\n * False (the default) for user-interaction-driven actions like forms,\n * claims, and evaluations — they always run as `manual`. True for actions\n * where it makes sense for an event to nudge a human assignee to invoke\n * them (email, http, notify).\n *\n * The trigger picker UI is hidden for blocks whose action type has this\n * set to false.\n */\n eligibleForEventTrigger?: boolean;\n\n // Execution\n run: (inputs: TInputs, ctx: ActionContext) => Promise<ActionResult>;\n}\n\n/**\n * Result returned by an action's `run()` function.\n *\n * The optional `events` array is the explicit emission surface — actions\n * declare which named events they're emitting on this particular run, with\n * the payload by value. The runtime persists these as part of the run record\n * and the reconciliation loop turns them into pending invocations on\n * subscribed listener blocks.\n */\nexport interface ActionResult {\n output: Record<string, any>;\n events?: Array<{ name: string; payload: Record<string, any> }>;\n completion?: {\n state?: 'completed' | 'awaiting_readback';\n readBack?: Record<string, any>;\n };\n}\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 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 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 * 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: '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 {\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 { registerAction } from '../../registry';\nimport { isGroupExecution, proposeGroupExecution, requireGroupExecutionParams } from '../_shared/groupExecution';\nimport type { ActionResult } from '../../types';\nimport { COLLECTION_USERS_ACTION_TYPE, 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 a grantee.\n * For `granteeKind === 'group-members'` the FlowDetail resolves\n * the group's members up front (via `enumerateMembers`) and the\n * dispatcher fans the grant out, one `grant(...)` per member.\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\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 // 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, or group-members.' },\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 },\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 return { output: { 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 const grantees: string[] = [];\n if (operation === 'add' && inputs.granteeKind === 'group-members') {\n const members = Array.isArray(inputs.members) ? inputs.members.filter((m) => !!String(m?.address || '').trim()) : [];\n if (members.length === 0) throw new Error('add (group-members): no members resolved to grant to.');\n grantees.push(...members.map((m) => String(m.address).trim()));\n } else {\n const granteeAddress = String(inputs.granteeAddress || '').trim();\n if (!granteeAddress) throw new Error(`${operation}: granteeAddress is required`);\n grantees.push(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 transactionHash: '',\n transactionHashes: [],\n grantedCount: operation === 'add' ? grantees.length : 0,\n role,\n collectionId,\n granteeAddress: grantees.length === 1 ? grantees[0] : 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: { transactionHash, role, collectionId, granteeAddress } };\n }\n\n // ---- add: grant one collection's authz; fan out for group-members ---------\n const granteeKind = inputs.granteeKind || 'user';\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\n if (granteeKind === 'group-members') {\n const members = Array.isArray(inputs.members) ? inputs.members.filter((m) => !!String(m?.address || '').trim()) : [];\n if (members.length === 0) {\n throw new Error('add (group-members): no members resolved to grant to. Enumerate the group members before signing.');\n }\n\n const transactionHashes: string[] = [];\n for (const member of members) {\n const granteeAddress = String(member.address).trim();\n const res = await service.grant({ granterAdminAddress: adminAddress, granteeAddress, collectionId, role, agentQuota, maxAmount, intentDurationNs, deedDid });\n const hash = String(res?.transactionHash || '').trim();\n if (!hash) {\n throw new Error(`add (group-members): grant to ${granteeAddress} returned no transactionHash. ${transactionHashes.length} of ${members.length} grants completed.`);\n }\n transactionHashes.push(hash);\n }\n\n return {\n output: {\n transactionHash: transactionHashes[transactionHashes.length - 1],\n transactionHashes,\n grantedCount: transactionHashes.length,\n role,\n collectionId,\n },\n };\n }\n\n // Single grantee ('user' or a 'group-account' that can exercise the grant).\n const granteeAddress = String(inputs.granteeAddress || '').trim();\n if (!granteeAddress) throw new Error('add: granteeAddress is required');\n\n const result = await service.grant({ granterAdminAddress: adminAddress, granteeAddress, collectionId, role, agentQuota, maxAmount, intentDurationNs, deedDid });\n const transactionHash = String(result?.transactionHash || '').trim();\n if (!transactionHash) {\n throw new Error('add: service returned no transactionHash. The grant was not broadcast.');\n }\n\n return {\n output: {\n transactionHash,\n transactionHashes: [transactionHash],\n grantedCount: 1,\n role,\n collectionId,\n granteeAddress,\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 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 } 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 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 } 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 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 } 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 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 { 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 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 } from '../../types';\nimport type { BoundConnection } 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 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<Record<string, unknown>> {\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 (result.data as Record<string, unknown>) ?? {};\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];\n","import { registerAction } from '../../registry';\nimport { delegatedToolMissingInputs, executeDelegatedTool, fieldValues, parseDelegatedToolInputs, type DelegatedToolInputs } 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 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\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 data = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: GMAIL_SEND_SCHEMA,\n toolSlug: GMAIL_SEND_SLUG,\n values,\n toolkitLabel: 'Gmail',\n });\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 },\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];\n","import { registerAction } from '../../registry';\nimport { delegatedToolMissingInputs, executeDelegatedTool, fieldValues, parseDelegatedToolInputs, type DelegatedToolInputs } 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's send tool often returns no message id (see run() below), so there\n // is no reliable output field to prove execution — a successful tool call\n // (run() throws on failure) is the signal. Declared 'none' rather than\n // requiring messageId, which would push every id-less send to needs_verification.\n proof: 'none',\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\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 data = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: OUTLOOK_SEND_SCHEMA,\n toolSlug: OUTLOOK_SEND_SLUG,\n values,\n toolkitLabel: 'Outlook',\n });\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\n return {\n output: {\n messageId,\n sentAt: new Date().toISOString(),\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];\n","import { registerAction } from '../../registry';\nimport { delegatedToolMissingInputs, executeDelegatedTool, fieldValues, parseDelegatedToolInputs, type DelegatedToolInputs } 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 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\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 data = await executeDelegatedTool(ctx, {\n connection: parsed.connection,\n schema: SLACK_SEND_SCHEMA,\n toolSlug: SLACK_SEND_SLUG,\n values,\n toolkitLabel: 'Slack',\n });\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 },\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];\n","import { registerAction } from '../../registry';\nimport { delegatedToolMissingInputs, executeDelegatedTool, fieldValues, parseDelegatedToolInputs, type DelegatedToolInputs } 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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 data = 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\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 },\n events: eventId ? [{ name: GOOGLECALENDAR_CREATED_EVENT, payload: { eventId, htmlLink, summary } }] : undefined,\n };\n },\n});\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 { registerAction } from '../../registry';\nimport { parseAttendeesField, type CalendarEventCreateInputs } from './eventCreate.types';\n\nexport const CALENDAR_EVENT_CREATE_SLUG = 'GOOGLECALENDAR_CREATE_EVENT';\n\nregisterAction<CalendarEventCreateInputs>({\n type: 'qi/calendar.event.create',\n can: 'calendar.event/create',\n sideEffect: true,\n proof: { fields: ['eventId'] },\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 } 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 type: 'qi/calendar.event.update',\n can: 'calendar.event/update',\n sideEffect: true,\n proof: { fields: ['eventId'] },\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 } from '../../registry';\nimport type { CalendarEventListInputs } from './eventList.types';\n\nexport const CALENDAR_EVENT_LIST_SLUG = 'GOOGLECALENDAR_EVENTS_LIST';\n\nregisterAction<CalendarEventListInputs>({\n type: 'qi/calendar.event.list',\n can: 'calendar.event/list',\n sideEffect: false,\n proof: 'none',\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 } 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 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 } 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 // 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 } 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 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 } from '../../registry';\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 */\nexport interface XeroPaymentCreateRunInputs extends Omit<XeroPaymentCreateInputs, 'Amount' | 'CurrencyRate'> {\n Amount: number;\n CurrencyRate?: number;\n}\n\nregisterAction<XeroPaymentCreateRunInputs>({\n type: 'qi/xero.payment.create',\n can: 'xero.payment/create',\n sideEffect: true,\n proof: { fields: ['paymentId'] },\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 inputSchema: {\n type: 'object',\n required: ['connection', 'InvoiceID', 'AccountID', 'Amount'],\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 InvoiceID: { type: 'string', description: 'UUID of the invoice being paid.' },\n AccountID: { type: 'string', description: 'UUID of the Xero bank/treasury account the payment debits.' },\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 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 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 const accountId = String(inputs.AccountID || '').trim();\n if (!accountId) {\n throw new Error('AccountID is required — set the Xero bank/treasury account in template config.');\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 if (inputs.tenant_id) args.tenant_id = inputs.tenant_id;\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: connection.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","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 { 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/calendar.event.create', {\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/calendar.event.update', {\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';\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 network = String(inputs.network || 'devnet').trim();\n\n const ixoAmount = (Number(amount) / 1_000_000).toFixed(6);\n\n return [\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 IXO',\n after: `${ixoAmount} IXO (${amount} uixo)`,\n changeType: 'replace',\n severity: 'info',\n },\n {\n key: 'network',\n label: 'Network',\n before: network,\n after: network,\n changeType: 'unchanged',\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 } 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\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 === 'group-members') {\n const count = Array.isArray(inputs.members) ? inputs.members.filter((m: any) => !!String(m?.address || '').trim()).length : 0;\n results.push({\n key: 'grantees',\n label: 'Grantees (fan-out)',\n before: null,\n after: `${count} group member${count === 1 ? '' : 's'}`,\n changeType: 'add',\n severity: 'warning',\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","// ─── Base UCAN Flow Plan ────────────────────────────────────────────────────\n// A structured, capability-shaped planning document that borrows UCAN semantics.\n// The AI generates this plan; the compiler turns it into blocks + graph + Yjs state.\n\n/** Condition that gates when a capability activates. */\nexport interface ConditionRef {\n /** ID of the upstream capability whose output is checked. */\n sourceId: string;\n /** Output field path to inspect, e.g., \"decision\". */\n field: string;\n /** Comparison operator. */\n operator: 'eq' | 'neq' | 'gt' | 'lt' | 'in' | 'exists';\n /** Value to compare against (omit for 'exists'). */\n value?: unknown;\n /** What happens when the condition is (not) met. */\n effect?: {\n action: 'enable' | 'disable' | 'hide' | 'show';\n message?: string;\n };\n}\n\n/** Authorization constraint for a capability. */\nexport interface ActorConstraint {\n /** Whitelisted actor DIDs. */\n authorisedActors?: string[];\n /** Parent capability URI for delegation chain. */\n parentCapability?: string;\n}\n\n/** Time-to-live constraint for a capability. */\nexport interface TTLConstraint {\n /** Hard deadline (ISO 8601 date string). */\n absoluteDueDate?: string;\n /** Duration from when the block becomes enabled (ISO 8601 duration, e.g., \"P7D\"). */\n fromEnablement?: string;\n /** Duration from when an actor commits (ISO 8601 duration, e.g., \"PT2H\"). */\n fromCommitment?: string;\n}\n\n/**\n * A single capability in a Base UCAN flow plan.\n *\n * UCAN semantics:\n * can = the action\n * with = the resource or scope\n * nb = typed caveats, inputs, parameters\n *\n * Workflow semantics (kept separate from nb):\n * condition, trigger, parallelGroup, phase\n */\nexport interface FlowCapability {\n /** Stable node identifier for this step. */\n id: string;\n /** UCAN-style ability string, e.g., \"bid/submit\", \"email/send\". */\n can: string;\n /** Resource URI, e.g., \"ixo:flow:{flowId}\" or \"ixo:flow:{flowId}:{nodeId}\". */\n with: string;\n /** Typed caveats / input parameters. Shape is dictated by the action registry. */\n nb?: Record<string, unknown>;\n\n // ── Workflow topology ──\n /** Condition that must be met for this capability to activate. */\n condition?: ConditionRef;\n /** Capabilities sharing a parallelGroup run concurrently. */\n parallelGroup?: string;\n /** Semantic grouping for layout lanes. */\n phase?: string;\n\n // ── Authorization ──\n /** Who can execute this step. */\n actor?: ActorConstraint;\n\n // ── TTL ──\n /** Time-to-live constraints. */\n ttl?: TTLConstraint;\n\n // ── Trigger ──\n /**\n * When and how this block fires. Defaults to `{ type: 'manual' }` if absent\n * (i.e. block runs only when a user explicitly invokes it).\n *\n * `block.event` triggers turn this block into a listener: when the source\n * block emits an event matching `eventName`, a pending invocation is\n * queued on this block and the assigned actor is DM'd to invoke it. See\n * `docs/flow-engine/events-and-triggers-plan.md` §3.7 and §18 for the full model.\n *\n * Triggers are a NEW sibling field on FlowCapability (decided in eng review\n * pass 2 phase 0 #1). They are NOT an extension of `condition`. The decompile\n * branch's author needs to add `props.trigger` parsing when their work merges.\n */\n trigger?: TriggerSpec;\n\n // ── Human-facing metadata ──\n /** Display title (falls back to can statement). */\n title?: string;\n /** Description of what this step does. */\n description?: string;\n /** Icon identifier. */\n icon?: string;\n}\n\n/**\n * Trigger declaration for a block. When and how it fires.\n */\n/** A single event source in a barrier trigger. */\nexport interface TriggerSource {\n /** ID of the block that emits the event. */\n sourceBlockId: string;\n /** Name of the event (must match an event declared on the source action's `events` vocabulary). */\n eventName: string;\n /** Namespace alias for payload access: `trigger.payload.<alias>.*` */\n alias: string;\n /**\n * When `true`, this source does NOT block queuing — the barrier fires once all\n * *required* (non-optional) sources have fired. If an optional source fired before\n * the barrier completes, its payload is merged in; if it never fires, it's skipped.\n * Defaults to `false` (required) for backward compatibility.\n */\n optional?: boolean;\n}\n\nexport interface TriggerSpec {\n /**\n * - `manual`: block runs only when a user explicitly invokes it (default).\n * - `flow.start`: block runs when the flow execution begins.\n * - `block.event`: block runs each time another block emits a matching event.\n * - `block.event.all`: block runs once ALL listed sources have emitted (barrier/join).\n */\n type: 'manual' | 'flow.start' | 'block.event' | 'block.event.all';\n /** Required when `type === 'block.event'`. ID of the block that emits the event. */\n sourceBlockId?: string;\n /** Required when `type === 'block.event'`. Name of the event (must match an event declared on the source action's `events` vocabulary). */\n eventName?: string;\n /** Required when `type === 'block.event.all'`. Array of event sources — ALL must fire before the listener is queued. */\n sources?: TriggerSource[];\n}\n\n/**\n * The Base UCAN flow plan — the intermediate representation between\n * user intent and the compiled flow graph.\n *\n * capabilities is an ordered list. Each capability carries its own stable `id`.\n */\nexport interface BaseUcanFlow {\n kind: 'qi.flow.base-ucan';\n version: '1.0';\n flowId: string;\n title: string;\n goal?: string;\n meta?: {\n entityDid?: string;\n flowUri?: string;\n rootIssuer?: string;\n };\n /** Ordered capabilities, each with its own stable node ID. */\n capabilities: FlowCapability[];\n}\n\n// ─── Runtime References ─────────────────────────────────────────────────────\n// Used in nb values to reference outputs from upstream capabilities.\n// Resolved at execution time, serialized as-is at compile time.\n\n/** A reference to an upstream node's output field. Format: \"nodeId.output.fieldPath\" */\nexport interface RuntimeRef {\n $ref: string;\n}\n\nexport function isRuntimeRef(value: unknown): value is RuntimeRef {\n return typeof value === 'object' && value !== null && '$ref' in value && typeof (value as Record<string, unknown>).$ref === 'string';\n}\n\n// ─── Compiled Flow Output ───────────────────────────────────────────────────\n// Produced by the compiler, consumed by hydration.\n\n/** A single block ready for insertion into BlockNote. */\nexport interface CompiledBlock {\n /** Pre-generated stable block ID. */\n id: string;\n /** BlockNote block type (e.g., \"action\"). */\n type: string;\n /** Block props — all values are strings per BlockNote convention. */\n props: Record<string, string>;\n}\n\n/**\n * An edge in the flow graph. Currently only `kind: 'trigger'` edges are\n * synthesized — they come from `block.event` triggers and represent the\n * source → listener relationship visually on the canvas.\n */\nexport interface CompiledEdge {\n id: string;\n source: string;\n target: string;\n kind: 'trigger';\n condition?: ConditionRef;\n}\n\n/** A compiled flow node stored in qi.flow.nodes. */\nexport interface CompiledFlowNode {\n id: string;\n blockId: string;\n can: string;\n with: string;\n registryType: string;\n title: string;\n description: string;\n props: Record<string, string>;\n phase?: string;\n parallelGroup?: string;\n actor?: ActorConstraint;\n}\n\n/** The complete compiled output from the Base UCAN compiler. */\nexport interface CompiledFlow {\n /** Flow metadata for qi.flow.meta and Y.Map('root'). */\n meta: {\n flowId: string;\n title: string;\n goal?: string;\n version: string;\n flowOwnerDid: string;\n flowUri?: string;\n compiledAt: string;\n compiledFrom: 'BaseUcanFlow';\n };\n /** Blocks to insert into BlockNote, in topological order. */\n blocks: CompiledBlock[];\n /** Flow graph nodes, keyed by node ID. */\n nodes: Record<string, CompiledFlowNode>;\n /** Dependency edges. */\n edges: CompiledEdge[];\n /** Topological order of node IDs. */\n order: string[];\n /** nodeId → blockId mapping. */\n blockIndex: Record<string, string>;\n}\n\n/** Strategy for how a compiled flow is applied to an existing document. */\nexport type FlowStrategy = 'full' | 'merge' | 'patch';\n","import * as Y from 'yjs';\nimport type { RuntimeRef } from '../../types/baseUcan';\nimport { isRuntimeRef } from '../../types/baseUcan';\nimport { getNestedValue } from './referenceResolver';\n\n/**\n * Run record stored in the audit trail as `type: 'block.run'`.\n *\n * Per Phase 0 #2 (eng review pass 2), run records are NOT a parallel\n * `_yRunHistory` structure — they ride on the existing `auditTrail` Y.Map\n * via `useAuditTrail.addEvent`. The shape below is what goes into the\n * audit trail event's `details` field.\n *\n * See `docs/flow-engine/events-and-triggers-plan.md` §3.4, §18, §19.\n */\nexport interface RunRecordDetails {\n /** Stable identifier for this run, deterministic from invocation context. */\n runId: string;\n /** Action's output. */\n output: Record<string, unknown>;\n /**\n * Events the action emitted on this run. Persisted as part of the run\n * record so the reconciliation loop can process them idempotently — even\n * across page refreshes and across multiple clients.\n */\n events: Array<{ name: string; payload: Record<string, unknown> }>;\n /** ISO timestamp when the action started. */\n startedAt: string;\n /** ISO timestamp when the action completed (success or failure). */\n completedAt: string;\n /** DID of the actor who signed the invocation that produced this run. */\n actorDid: string;\n /** UCAN invocation CID when execution produced one. */\n invocationCid?: string;\n /** Capability/proof CID used when no invocation CID was produced. */\n capabilityId?: string;\n /** Optional error if the run failed. */\n error?: { message: string; code?: string };\n /** External read-back metadata associated with this run or reconciliation. */\n readBack?: Record<string, unknown>;\n /** True when this audit entry was written by external read-back reconciliation. */\n reconciled?: boolean;\n /**\n * If this run was triggered by a pending invocation (i.e. it's a listener\n * run), the id of that pending invocation. Used to dedup replays and trace\n * causality back through `triggeredBy`.\n */\n fromPendingInvocationId?: string;\n /**\n * If this run is a listener run, the (sourceBlockId, eventName) that\n * caused it. Used by the failure visibility surface to attribute failures\n * back to the source block (CP-1).\n */\n triggeredBy?: { sourceBlockId: string; eventName: string };\n /** Source run id for listener runs, stored explicitly for failure lookups. */\n sourceRunId?: string;\n}\n\nexport const RUN_RECORD_AUDIT_TYPE = 'block.run';\n\n/**\n * Pending invocation queued on a listener block.\n *\n * Stored in `_yPendingInvocations: Y.Map<blockId, Y.Map<id, PendingInvocation>>`.\n *\n * The id is deterministic — derived from\n * `(sourceBlockId, sourceRunId, listenerBlockId, eventName, eventIndex)` —\n * so the reconciliation loop can run idempotently from multiple clients\n * without producing duplicates.\n *\n * See `docs/flow-engine/events-and-triggers-plan.md` §3.4, §3.5.1, §18.\n */\nexport interface PendingInvocation {\n /** Deterministic id, see `computePendingInvocationId`. */\n id: string;\n /** Block that emitted the event. */\n triggeringBlockId: string;\n /** Run id of the triggering source run, used for the deterministic id. */\n sourceRunId: string;\n /** Event name from the source action's vocabulary. */\n eventName: string;\n /** Event index within the source run's `events` array (a single run can emit multiple). */\n eventIndex: number;\n /**\n * The frozen event payload, captured by value at emission time. The\n * assignee invokes the listener against this payload, not against the\n * source block's current state. This is the property that makes the\n * Sally → Mike scenario produce 10 distinct emails even when Mike acts\n * on them all hours later.\n */\n payload: Record<string, unknown>;\n /**\n * Snapshots of `nodeId.output.*` ref values that the listener's inputs\n * reference, captured at queue time. Keyed by the full ref string.\n *\n * §3.5.1: ref snapshots are the load-bearing fix for the lag-time\n * overwrite scenario. If a listener references a non-trigger block's\n * output (e.g. `evaluateBlock.output.claimId`), that value is captured\n * here at queue time. Resolution at invocation time prefers the snapshot\n * over current state, so multiple queued invocations don't drift when\n * the source re-runs.\n */\n refSnapshots: Record<string, unknown>;\n /** DID of the assigned actor who must invoke this listener. Resolved from `props.assignment.assignedActor.did`. */\n assigneeDid: string;\n /** ISO timestamp when the source emission happened. */\n emittedAt: string;\n /** ISO timestamp after which this pending invocation is considered expired. Resolved from `FlowCapability.ttl` at queue time. */\n expiresAt: string;\n}\n\n/**\n * Compute a deterministic id for a pending invocation from its content.\n *\n * The same (sourceBlockId, sourceRunId, listenerBlockId, eventName,\n * eventIndex) tuple always produces the same id. This is the property that\n * makes the reconciliation loop idempotent — re-running it from a different\n * client, or after a page refresh, produces the same `Y.Map.set` operation\n * with the same key, which Yjs converges to a single entry.\n *\n * Implementation: simple deterministic string concatenation, hashed via a\n * 32-bit FNV-1a. The id is short and stable; collision risk within a single\n * flow is negligible because the inputs are scoped (block ids are unique\n * within a flow, run ids are unique within a block).\n */\nexport function computePendingInvocationId(args: { sourceBlockId: string; sourceRunId: string; listenerBlockId: string; eventName: string; eventIndex: number }): string {\n const { sourceBlockId, sourceRunId, listenerBlockId, eventName, eventIndex } = args;\n const input = `${sourceBlockId}:${sourceRunId}:${listenerBlockId}:${eventName}:${eventIndex}`;\n return `pi-${fnv1a32(input)}`;\n}\n\n/**\n * Walk an inputs object and collect every RuntimeRef of the form\n * `nodeId.output.fieldPath`. Returns a map of `{refString: resolvedValue}`\n * suitable for storing as `PendingInvocation.refSnapshots`.\n *\n * The walker mirrors `resolveRuntimeRefs` in `flowCompiler/resolveRefs.ts`\n * but reads instead of resolving — it captures the current value of each\n * ref so the listener can later resolve against the snapshot rather than\n * against current state.\n *\n * See `docs/flow-engine/events-and-triggers-plan.md` §3.5.1.\n */\nexport function snapshotInputRefs(inputs: unknown, getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined): Record<string, unknown> {\n const snapshots: Record<string, unknown> = {};\n walkRefs(inputs, (ref) => {\n // Skip trigger.* refs — those resolve from the pending invocation's payload, not snapshots\n if (ref.$ref.startsWith('trigger.')) return;\n const parsed = parseOutputRef(ref.$ref);\n if (!parsed) return;\n const output = getNodeOutput(parsed.nodeId);\n if (!output) return;\n snapshots[ref.$ref] = getNestedValue(output, parsed.fieldPath);\n });\n return snapshots;\n}\n\n/**\n * Recursively walk a value and invoke the visitor on every RuntimeRef found.\n * Mirrors the recursion shape of `resolveValue` in `resolveRefs.ts`.\n */\nfunction walkRefs(value: unknown, visit: (ref: RuntimeRef) => void): void {\n if (isRuntimeRef(value)) {\n visit(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) walkRefs(item, visit);\n return;\n }\n if (typeof value === 'object' && value !== null) {\n for (const v of Object.values(value)) walkRefs(v, visit);\n }\n}\n\n/** Parse `\"nodeId.output.fieldPath\"` into its parts. Returns null if not a node output ref. */\nfunction parseOutputRef(ref: string): { nodeId: string; fieldPath: string } | null {\n const outputIndex = ref.indexOf('.output.');\n if (outputIndex === -1) return null;\n return {\n nodeId: ref.slice(0, outputIndex),\n fieldPath: ref.slice(outputIndex + '.output.'.length),\n };\n}\n\n/**\n * 32-bit FNV-1a hash. Returns a hex string. Used for deterministic\n * pending-invocation ids — not cryptographic, just stable across clients.\n */\nfunction fnv1a32(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n// ─── Yjs storage helpers ────────────────────────────────────────────────────\n\nconst PENDING_INVOCATIONS_MAP_KEY = 'pendingInvocations';\n\n/**\n * Get the top-level pending invocations Y.Map from the editor's yDoc.\n * Lazily creates it if missing.\n *\n * Shape: `Y.Map<blockId, Y.Map<pendingInvocationId, PendingInvocation>>`.\n * The outer map is keyed by listener block id; the inner map is keyed by\n * deterministic pending invocation id (see `computePendingInvocationId`).\n */\nexport function getPendingInvocationsMap(yDoc: Y.Doc): Y.Map<Y.Map<unknown>> {\n return yDoc.getMap<Y.Map<unknown>>(PENDING_INVOCATIONS_MAP_KEY);\n}\n\n/**\n * Get the inner pending-invocations map for a specific listener block.\n * Lazily creates it if missing. Caller is responsible for being inside a\n * Yjs transaction if atomic creation matters.\n */\nexport function getOrCreateBlockPendingMap(yDoc: Y.Doc, blockId: string): Y.Map<unknown> {\n const outer = getPendingInvocationsMap(yDoc);\n let inner = outer.get(blockId);\n if (!inner) {\n inner = new Y.Map();\n outer.set(blockId, inner);\n }\n return inner;\n}\n\n/**\n * Read all pending invocations for a block as plain JS objects.\n * Returns an array sorted by `emittedAt` ascending (oldest first).\n */\nexport function readPendingInvocations(yDoc: Y.Doc, blockId: string): PendingInvocation[] {\n const outer = getPendingInvocationsMap(yDoc);\n const inner = outer.get(blockId);\n if (!inner) return [];\n const items: PendingInvocation[] = [];\n inner.forEach((value) => {\n if (value && typeof value === 'object') {\n items.push(value as PendingInvocation);\n }\n });\n items.sort((a, b) => a.emittedAt.localeCompare(b.emittedAt));\n return items;\n}\n\n/**\n * Idempotently write a pending invocation under its deterministic id.\n *\n * Returns true if a new entry was created, false if the id already\n * existed (meaning another client or a previous reconciliation pass\n * already queued this invocation). This is the property that makes\n * `reconcilePendingInvocations` safe to run from multiple clients\n * simultaneously and across page refreshes — see plan §18.\n *\n * Wraps the write in a Yjs transaction so the existence check and the\n * subsequent set are atomic from the local client's perspective. Concurrent\n * clients each computing the same id will all converge to a single entry\n * because Y.Map.set with the same key is last-writer-wins on identical\n * content.\n */\nexport function queuePendingInvocation(yDoc: Y.Doc, listenerBlockId: string, invocation: PendingInvocation): boolean {\n let created = false;\n yDoc.transact(() => {\n const inner = getOrCreateBlockPendingMap(yDoc, listenerBlockId);\n if (inner.has(invocation.id)) return;\n inner.set(invocation.id, invocation);\n created = true;\n });\n return created;\n}\n\n/**\n * Remove a pending invocation by id. Used when the assignee completes the\n * invocation (transitioning to a `block.run` audit trail entry) or when\n * the expiration sweep marks it as expired.\n */\nexport function removePendingInvocation(yDoc: Y.Doc, listenerBlockId: string, pendingInvocationId: string): boolean {\n const outer = getPendingInvocationsMap(yDoc);\n const inner = outer.get(listenerBlockId);\n if (!inner) return false;\n if (!inner.has(pendingInvocationId)) return false;\n inner.delete(pendingInvocationId);\n return true;\n}\n\n/**\n * Collect the ids of pending invocations this listener has already consumed:\n * every run record the listener wrote carries `fromPendingInvocationId`.\n * The reconciliation loop skips these ids so a consumed invocation is not\n * resurrected from the (immutable) source run record on the next pass.\n * Joining on run records needs no extra tombstone state and converges\n * across clients like everything else in the audit trail.\n */\nexport function readConsumedPendingInvocationIds(yDoc: Y.Doc, listenerBlockId: string): Set<string> {\n const consumed = new Set<string>();\n for (const record of readRunRecords(yDoc, listenerBlockId)) {\n if (record.fromPendingInvocationId) consumed.add(record.fromPendingInvocationId);\n }\n return consumed;\n}\n\n/**\n * Physically delete expired pending invocations across all listeners.\n * Safe against resurrection because the reconciliation loop refuses to\n * queue an invocation whose computed expiry is already in the past.\n * Returns the number of entries removed.\n */\nexport function sweepExpiredPendingInvocations(yDoc: Y.Doc, now: number = Date.now()): number {\n const outer = getPendingInvocationsMap(yDoc);\n let removed = 0;\n outer.forEach((inner, listenerBlockId) => {\n const innerMap = inner as Y.Map<unknown>;\n if (!innerMap || typeof innerMap.forEach !== 'function') return;\n const expiredIds: string[] = [];\n innerMap.forEach((value, id) => {\n const expiresAt = (value as PendingInvocation | undefined)?.expiresAt;\n if (expiresAt && Date.parse(expiresAt) < now) expiredIds.push(id);\n });\n for (const id of expiredIds) {\n innerMap.delete(id);\n removed += 1;\n }\n void listenerBlockId;\n });\n return removed;\n}\n\n// ─── Barrier state helpers (block.event.all) ──────────────────────────────────\n\nconst BARRIER_STATE_MAP_KEY = 'barrierState';\n\n/**\n * A single source event recorded toward a barrier trigger's completion.\n */\nexport interface BarrierEntry {\n sourceBlockId: string;\n eventName: string;\n alias: string;\n runId: string;\n payload: Record<string, unknown>;\n emittedAt: string;\n}\n\n/** Get the top-level barrier state Y.Map. Shape: `Y.Map<listenerBlockId, Y.Map<sourceKey, BarrierEntry>>`. */\nexport function getBarrierStateMap(yDoc: Y.Doc): Y.Map<Y.Map<unknown>> {\n return yDoc.getMap<Y.Map<unknown>>(BARRIER_STATE_MAP_KEY);\n}\n\nfunction getOrCreateListenerBarrierMap(yDoc: Y.Doc, listenerBlockId: string): Y.Map<unknown> {\n const outer = getBarrierStateMap(yDoc);\n let inner = outer.get(listenerBlockId);\n if (!inner) {\n inner = new Y.Map();\n outer.set(listenerBlockId, inner);\n }\n return inner;\n}\n\n/** Record one source event firing toward a barrier. Idempotent — skips write if same runId already recorded. */\nexport function recordBarrierEvent(yDoc: Y.Doc, listenerBlockId: string, entry: BarrierEntry): boolean {\n let written = false;\n yDoc.transact(() => {\n const inner = getOrCreateListenerBarrierMap(yDoc, listenerBlockId);\n const key = `${entry.sourceBlockId}::${entry.eventName}`;\n const existing = inner.get(key) as BarrierEntry | undefined;\n // Skip if same runId already recorded — prevents Yjs observer re-trigger loop\n if (existing && typeof existing === 'object' && (existing as BarrierEntry).runId === entry.runId) return;\n inner.set(key, entry);\n written = true;\n });\n return written;\n}\n\n/** Read all barrier entries for a listener block. */\nexport function readBarrierState(yDoc: Y.Doc, listenerBlockId: string): BarrierEntry[] {\n const outer = getBarrierStateMap(yDoc);\n const inner = outer.get(listenerBlockId);\n if (!inner) return [];\n const entries: BarrierEntry[] = [];\n inner.forEach((value) => {\n if (value && typeof value === 'object') {\n entries.push(value as BarrierEntry);\n }\n });\n return entries;\n}\n\n/** Clear barrier state after an invocation is queued (resets for next cycle). */\nexport function clearBarrierState(yDoc: Y.Doc, listenerBlockId: string): void {\n const outer = getBarrierStateMap(yDoc);\n yDoc.transact(() => {\n outer.delete(listenerBlockId);\n });\n}\n\n/**\n * Compute a deterministic id for a barrier invocation from all contributing\n * source run IDs. Sorted to ensure order-independence — whichever source\n * completes last, the same ID is produced.\n */\nexport function computeBarrierInvocationId(entries: BarrierEntry[], listenerBlockId: string): string {\n const sorted = [...entries].sort((a, b) => a.sourceBlockId.localeCompare(b.sourceBlockId));\n const input = sorted.map((e) => `${e.sourceBlockId}:${e.runId}:${e.eventName}`).join('|') + `|>${listenerBlockId}`;\n return `bi-${fnv1a32(input)}`;\n}\n\n/**\n * Merge barrier entries into a namespaced payload object keyed by alias.\n * E.g. { governance: { groupName, groupType }, members: { memberCount }, preview: { domainCardData } }\n */\nexport function mergeBarrierPayloads(entries: BarrierEntry[]): Record<string, unknown> {\n const merged: Record<string, unknown> = {};\n for (const entry of entries) {\n if (entry.alias) {\n merged[entry.alias] = entry.payload;\n } else {\n Object.assign(merged, entry.payload);\n }\n }\n return merged;\n}\n\n// ─── Run record helpers (audit trail integration, Phase 0 #2) ───────────────\n\n/**\n * Append a run record to the audit trail for a block. Run records are\n * stored as audit trail events with `type: 'block.run'` and the structured\n * data in `details`. Per Phase 0 #2 of eng review pass 2, this avoids\n * inventing a parallel `_yRunHistory` storage system.\n *\n * Y.Array.push from concurrent clients merges correctly — verified by the\n * existing `useAuditTrail` shipping in production.\n */\nexport function appendRunRecord(yDoc: Y.Doc, blockId: string, details: RunRecordDetails, userId: string): void {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n\n yDoc.transact(() => {\n let arr = auditMap.get(blockId);\n if (!arr) {\n arr = new Y.Array<unknown>();\n auditMap.set(blockId, arr);\n }\n const event = {\n id: `${details.runId}`,\n blockId,\n type: RUN_RECORD_AUDIT_TYPE,\n details,\n message: undefined,\n meta: {\n timestamp: details.completedAt,\n userId,\n editable: false,\n },\n };\n arr.push([event]);\n });\n}\n\n/**\n * Read all run records for a block from the audit trail. Filters audit\n * trail entries to only those with `type: 'block.run'`.\n */\nexport function readRunRecords(yDoc: Y.Doc, blockId: string): RunRecordDetails[] {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n const arr = auditMap.get(blockId);\n if (!arr) return [];\n const records: RunRecordDetails[] = [];\n arr.forEach((entry) => {\n if (!entry || typeof entry !== 'object') return;\n const e = entry as { type?: string; details?: RunRecordDetails };\n if (e.type === RUN_RECORD_AUDIT_TYPE && e.details) {\n records.push(e.details);\n }\n });\n return records;\n}\n\n// ─── Failure visibility (slice L: CP-1 + CP-2) ──────────────────────────────\n\n/**\n * A failed listener run, attributed to the source block emission that\n * triggered it. Used by the failure visibility surface (CP-1) on source\n * blocks: the source block can show \"N listeners failed for your last run\".\n */\nexport interface FailedListenerRun {\n /** Block id of the listener whose run failed. */\n listenerBlockId: string;\n /** The full RunRecordDetails of the failed listener invocation. */\n record: RunRecordDetails;\n}\n\n/**\n * Find all failed listener runs that were triggered by a specific source\n * block run. Walks every block's audit trail, filters to listener runs\n * triggered by (sourceBlockId, sourceRunId), and returns the ones with an\n * error set.\n *\n * Used by the source block UI to show a failure badge linked to a specific\n * run — if Sally evaluates 10 claims and 2 of Mike's emails fail, Sally\n * sees \"2 failed listeners on claim-G\" rather than discovering it days\n * later in the email service logs.\n */\nexport function findFailedListenersForSourceRun(yDoc: Y.Doc, sourceBlockId: string, sourceRunId: string, listenerBlockIds: string[]): FailedListenerRun[] {\n const failures: FailedListenerRun[] = [];\n for (const listenerBlockId of listenerBlockIds) {\n const records = readRunRecords(yDoc, listenerBlockId);\n for (const record of records) {\n if (!record.error) continue;\n if (record.triggeredBy?.sourceBlockId !== sourceBlockId) continue;\n if (record.fromPendingInvocationId == null) continue;\n // The fromPendingInvocationId encodes the source run; we match on\n // triggeredBy + the listener's record actually being a listener run\n // for THIS source block. The plan's deterministic id includes\n // sourceRunId, so failures from a specific source run are findable\n // by joining on the audit trail's stored sourceRunId reference.\n const sourceRunIdField = (record as { sourceRunId?: string }).sourceRunId;\n if (sourceRunIdField && sourceRunIdField !== sourceRunId) continue;\n failures.push({ listenerBlockId, record });\n }\n }\n return failures;\n}\n\n/**\n * Replay a previously failed listener run by re-queueing a pending\n * invocation with the same content. Reuses the original frozen payload\n * and ref snapshots from the failed run record's audit trail entry, so the\n * replay sees exactly the same data the original invocation saw.\n *\n * CP-2 from the plan. Used by the replay button in the failure visibility\n * surface. Returns true if a new pending invocation was queued.\n *\n * Note: replay does NOT re-derive the deterministic id from the original\n * source emission, because the original pending invocation's id is already\n * present (or removed) in the pendingInvocations Y.Map. Instead, replay\n * generates a fresh id by appending a `:replay-N` suffix to the original.\n * This means the replay creates a NEW pending invocation that the assignee\n * can act on, separate from any history of the original.\n */\nexport function replayFailedListenerRun(\n yDoc: Y.Doc,\n failedRecord: RunRecordDetails,\n listenerBlockId: string,\n originalPayload: Record<string, unknown>,\n originalRefSnapshots: Record<string, unknown>,\n assigneeDid: string\n): boolean {\n if (!failedRecord.triggeredBy) return false;\n const replayId = `${failedRecord.runId}:replay-${Date.now().toString(36)}`;\n const now = new Date().toISOString();\n const replay: PendingInvocation = {\n id: replayId,\n triggeringBlockId: failedRecord.triggeredBy.sourceBlockId,\n sourceRunId: (failedRecord as { sourceRunId?: string }).sourceRunId || failedRecord.runId,\n eventName: failedRecord.triggeredBy.eventName,\n eventIndex: 0,\n payload: originalPayload,\n refSnapshots: originalRefSnapshots,\n assigneeDid,\n emittedAt: now,\n expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),\n };\n return queuePendingInvocation(yDoc, listenerBlockId, replay);\n}\n","/**\n * Reference Resolver — the single engine for `{{blockId.propPath}}` string\n * references.\n *\n * Handles resolution of block property references in the format:\n * {{blockId.propKey}} or {{blockId.nestedProp.key}}\n *\n * Example:\n * Input: \"User email: {{user-block-123.email}}\"\n * Output: \"User email: john@example.com\"\n *\n * This lives in core (framework-free) so both the React layer\n * (`src/mantine/utils/referenceResolver.ts` re-exports it) and headless\n * consumers share one implementation. The structured `{ $ref }` resolver\n * (`flowCompiler/resolveRefs.ts`) is a separate data model that shares\n * `getNestedValue` from here.\n *\n * Behavioral contract (things consumers depend on — do not change):\n * - Unresolved references become `fallback` (default `''`); every\n * FlowDetail `inputsReady` gate relies on empty-string-when-unresolved.\n * - Objects stringify by default (`stringifyObjects: true`).\n * - `:` is allowed in property paths (JSON-LD field names).\n * - `output.*` paths fall back to `output.data.*` and legacy\n * `output.http.data.*`.\n */\n\nimport { warnOnce } from '../warnOnce';\n\n/**\n * Represents a parsed reference from a string\n */\nexport interface ParsedReference {\n /** Full reference string including delimiters: {{blockId.propKey}} */\n fullMatch: string;\n /** Block ID portion */\n blockId: string;\n /** Property path (can be nested): propKey or nested.prop.key */\n propPath: string;\n /** Start index in the original string */\n startIndex: number;\n /** End index in the original string */\n endIndex: number;\n}\n\n/**\n * Regular expression to match references in format: {{blockId.propKey}}\n * Captures: blockId and propPath (including nested paths)\n */\n// propPath allows `:` so JSON-LD field names (e.g. `schema:amount`,\n// `umuzi:paymentCurrency`) round-trip through the resolver without\n// truncation. Without it, `{{evaluation.outcomeResponses.schema:amount}}`\n// silently fails to match and resolves to '' — which then casts to 0 in\n// any downstream number field.\nconst REFERENCE_REGEX = /\\{\\{([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.:]+)\\}\\}/g;\n\n/**\n * Parse all references from a string\n */\nexport function parseReferences(input: string): ParsedReference[] {\n const references: ParsedReference[] = [];\n const regex = new RegExp(REFERENCE_REGEX);\n let match;\n\n while ((match = regex.exec(input)) !== null) {\n references.push({\n fullMatch: match[0],\n blockId: match[1],\n propPath: match[2],\n startIndex: match.index,\n endIndex: match.index + match[0].length,\n });\n }\n\n return references;\n}\n\n/**\n * Get a nested property value from an object using dot notation.\n * Shared by the `{{...}}` resolver, the structured `$ref` resolver, and\n * ref snapshotting — keep the loose `current?.[key]` semantics.\n */\nexport function getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => {\n return current?.[key];\n }, obj);\n}\n\nexport type UnresolvedReferenceReason = 'unknown-block' | 'missing-value' | 'response-parse-error';\n\nexport interface UnresolvedReference {\n /** The full `{{...}}` reference text. */\n ref: string;\n blockId: string;\n propPath: string;\n reason: UnresolvedReferenceReason;\n}\n\ninterface SingleResolution {\n value: any;\n reason?: UnresolvedReferenceReason;\n}\n\nfunction resolveSingleReferenceDetailed(blockId: string, propPath: string, editorDocument: any[], yRuntime?: any, scope?: Record<string, any>): SingleResolution {\n // Scope bindings take precedence over any same-named editor block.\n if (scope && Object.prototype.hasOwnProperty.call(scope, blockId)) {\n const root = scope[blockId];\n if (root == null) return { value: undefined, reason: 'missing-value' };\n const value = getNestedValue(root, propPath);\n return { value, reason: value === undefined ? 'missing-value' : undefined };\n }\n\n if (!editorDocument || !Array.isArray(editorDocument)) {\n return { value: undefined, reason: 'unknown-block' };\n }\n\n // Find the block by ID\n const block = editorDocument.find((b) => b.id === blockId);\n\n if (!block) {\n return { value: undefined, reason: 'unknown-block' };\n }\n\n // Runtime output paths (e.g., \"output.customer.email\") — read from _yRuntime\n // Any block type that stores runtime output (action, apiRequest, email, etc.)\n if (propPath.startsWith('output.')) {\n if (!yRuntime) return { value: undefined, reason: 'missing-value' };\n\n const runtimeState = yRuntime.get(blockId);\n if (!runtimeState?.output) return { value: undefined, reason: 'missing-value' };\n\n const innerPath = propPath.substring('output.'.length);\n const direct = getNestedValue(runtimeState.output, innerPath);\n if (direct !== undefined) return { value: direct };\n\n // Fallback: some actions (e.g. http.request) nest the response payload\n // under output.data, but the user-defined schema references paths\n // relative to the payload (e.g. \"customer.email\" not \"data.customer.email\").\n if (runtimeState.output.data !== undefined) {\n const value = getNestedValue(runtimeState.output.data, innerPath);\n return { value, reason: value === undefined ? 'missing-value' : undefined };\n }\n\n // Legacy fallback: older http.request flow executor stored payload\n // under output.http.data.\n if (runtimeState.output.http?.data !== undefined) {\n const value = getNestedValue(runtimeState.output.http.data, innerPath);\n return { value, reason: value === undefined ? 'missing-value' : undefined };\n }\n\n return { value: undefined, reason: 'missing-value' };\n }\n\n // Special handling for API Request response paths (e.g., \"response.data.user.email\")\n if (propPath.startsWith('response.')) {\n const responseData = block.props.response;\n\n if (!responseData) {\n return { value: undefined, reason: 'missing-value' };\n }\n\n // Parse response JSON if it's a string\n try {\n const parsedResponse = typeof responseData === 'string' ? JSON.parse(responseData) : responseData;\n\n // Extract the path after \"response.\" (e.g., \"data.user.email\")\n const innerPath = propPath.substring('response.'.length);\n\n // Navigate into the parsed response using the inner path\n const value = getNestedValue(parsedResponse, innerPath);\n\n return { value, reason: value === undefined ? 'missing-value' : undefined };\n } catch {\n warnOnce(`ref-response-parse:${blockId}`, `[flow-config] block ${blockId}: props.response is not valid JSON; {{${blockId}.${propPath}}} cannot resolve`);\n return { value: undefined, reason: 'response-parse-error' };\n }\n }\n\n // Default behavior for other properties: direct prop access\n const value = getNestedValue(block.props, propPath);\n\n return { value, reason: value === undefined ? 'missing-value' : undefined };\n}\n\n/**\n * Resolve a single reference by finding the block and extracting the property value\n */\nexport function resolveSingleReference(blockId: string, propPath: string, editorDocument: any[], yRuntime?: any, scope?: Record<string, any>): any {\n return resolveSingleReferenceDetailed(blockId, propPath, editorDocument, yRuntime, scope).value;\n}\n\nexport interface ResolveReferencesOptions {\n /** String to use when a reference cannot be resolved */\n fallback?: string;\n /** Whether to return objects as JSON strings */\n stringifyObjects?: boolean;\n /** Yjs runtime map for resolving action block output paths */\n yRuntime?: any;\n /**\n * Local scope bindings for iterative contexts. When provided, a reference\n * like `{{item.foo}}` resolves against `scope.item.foo` before falling\n * back to editor blocks. Use this in iterative mappers (e.g. Xero\n * invoice LineItems iterative mode).\n */\n scope?: Record<string, any>;\n /**\n * Diagnostic context: when set, unresolved references are logged once per\n * (context, ref). Pass the consuming block's id so a typo'd reference is\n * visible in the console instead of silently becoming ''.\n */\n warnContext?: string;\n}\n\nexport interface DetailedResolution {\n value: string;\n /** References that resolved to the fallback, with the reason. */\n unresolved: UnresolvedReference[];\n}\n\n/**\n * Resolve all references in a string, returning the resolved string plus\n * structured diagnostics for every reference that fell back.\n */\nexport function resolveReferencesDetailed(input: string | null | undefined, editorDocument: any[], options: ResolveReferencesOptions = {}): DetailedResolution {\n const { fallback = '', stringifyObjects = true, yRuntime, scope, warnContext } = options;\n const unresolved: UnresolvedReference[] = [];\n\n // Handle null/undefined input\n if (input == null) {\n return { value: '', unresolved };\n }\n\n // Convert to string if not already\n const inputStr = String(input);\n\n // Parse all references\n const references = parseReferences(inputStr);\n\n // If no references found, return original string\n if (references.length === 0) {\n return { value: inputStr, unresolved };\n }\n\n // Resolve each reference and build the result string\n let result = inputStr;\n\n // Process in reverse order to maintain correct string indices\n for (let i = references.length - 1; i >= 0; i--) {\n const ref = references[i];\n const resolution = resolveSingleReferenceDetailed(ref.blockId, ref.propPath, editorDocument, yRuntime, scope);\n const resolvedValue = resolution.value;\n\n // Convert resolved value to string\n let replacementStr: string;\n\n if (resolvedValue === undefined || resolvedValue === null) {\n replacementStr = fallback;\n unresolved.push({ ref: ref.fullMatch, blockId: ref.blockId, propPath: ref.propPath, reason: resolution.reason || 'missing-value' });\n } else if (typeof resolvedValue === 'object') {\n // Handle objects/arrays\n replacementStr = stringifyObjects ? JSON.stringify(resolvedValue) : fallback;\n } else {\n replacementStr = String(resolvedValue);\n }\n\n // Replace the reference with the resolved value\n result = result.substring(0, ref.startIndex) + replacementStr + result.substring(ref.endIndex);\n }\n\n if (warnContext && unresolved.length > 0) {\n for (const entry of unresolved) {\n warnOnce(`ref-unresolved:${warnContext}:${entry.ref}`, `[flow-config] ${warnContext}: reference ${entry.ref} did not resolve (${entry.reason}); using fallback '${fallback}'`);\n }\n }\n\n return { value: result, unresolved };\n}\n\n/**\n * Resolve all references in a string and return the resolved string\n */\nexport function resolveReferences(input: string | null | undefined, editorDocument: any[], options: ResolveReferencesOptions = {}): string {\n return resolveReferencesDetailed(input, editorDocument, options).value;\n}\n\n/**\n * Check if a string contains any references\n */\nexport function hasReferences(input: string | null | undefined): boolean {\n if (input == null) return false;\n return parseReferences(String(input)).length > 0;\n}\n\n/**\n * Create a reference string for a block property\n */\nexport function createReference(blockId: string, propPath: string): string {\n return `{{${blockId}.${propPath}}}`;\n}\n\n/**\n * Resolve references in an object's values recursively\n * Useful for resolving references in API request bodies, headers, etc.\n */\nexport function resolveObjectReferences<T extends Record<string, any>>(obj: T, editorDocument: any[], options?: ResolveReferencesOptions): T {\n const result: any = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string') {\n result[key] = resolveReferences(value, editorDocument, options);\n } else if (typeof value === 'object' && value !== null) {\n result[key] = resolveObjectReferences(value, editorDocument, options);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n","/**\n * Flow Version Manifest\n *\n * Single source of truth for what each schema version requires.\n * Blocks and components read policy hints rather than checking version strings directly.\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type FlowVersionString = '0.3' | '1.0.0';\n\nexport interface VersionPolicyUi {\n /** Show the delegation management panel in block config */\n showDelegationPanel: boolean;\n /** Show the whitelist (specific actors) option in authorization config */\n showWhitelistConfig: boolean;\n /** Show the \"anyone with flow access\" option in authorization config */\n showAnyoneConfig: boolean;\n /** Show a banner when a newer version is available */\n showMigrationBanner: boolean;\n /** Require PIN entry for block execution (invocation signing) */\n requirePinForExecution: boolean;\n}\n\nexport interface VersionPolicy {\n /** Semver-style version identifier */\n version: FlowVersionString;\n /** Human-readable label */\n label: string;\n /** Whether UCAN delegation chains are required for all executions */\n ucanRequired: boolean;\n /** Whether a root delegation must exist before any execution */\n delegationRootRequired: boolean;\n /** Whether whitelist-only authorization (no parentCapability) is acceptable */\n whitelistOnlyAllowed: boolean;\n /** Whether unrestricted access (no authorisedActors, no parentCapability) is acceptable */\n unrestrictedAllowed: boolean;\n /** Which execution path to use */\n executionPath: 'legacy' | 'invocation';\n /** Which authorization function to use */\n authorizationFn: 'v1' | 'v2';\n /** Allowed authorization modes in the UI */\n allowedAuthModes: Array<'anyone' | 'actors' | 'capability'>;\n /** UI rendering hints — blocks query these instead of checking version strings */\n ui: VersionPolicyUi;\n /** Human-readable description of this version */\n description: string;\n}\n\n// ---------------------------------------------------------------------------\n// Manifest\n// ---------------------------------------------------------------------------\n\nexport const VERSION_MANIFEST: Record<FlowVersionString, VersionPolicy> = {\n '0.3': {\n version: '0.3',\n label: 'Legacy',\n ucanRequired: false,\n delegationRootRequired: false,\n whitelistOnlyAllowed: true,\n unrestrictedAllowed: true,\n executionPath: 'legacy',\n authorizationFn: 'v1',\n allowedAuthModes: ['anyone', 'actors', 'capability'],\n ui: {\n showDelegationPanel: false,\n showWhitelistConfig: true,\n showAnyoneConfig: true,\n showMigrationBanner: true,\n requirePinForExecution: false,\n },\n description: 'Legacy version. UCAN optional, whitelist-only authorization accepted.',\n },\n '1.0.0': {\n version: '1.0.0',\n label: 'UCAN Required',\n ucanRequired: true,\n delegationRootRequired: true,\n whitelistOnlyAllowed: false,\n unrestrictedAllowed: false,\n executionPath: 'invocation',\n authorizationFn: 'v2',\n allowedAuthModes: ['capability'],\n ui: {\n showDelegationPanel: true,\n showWhitelistConfig: false,\n showAnyoneConfig: false,\n showMigrationBanner: false,\n requirePinForExecution: true,\n },\n description: 'UCAN-enforced. Every block execution requires a valid delegation chain.',\n },\n};\n\n/** The version stamped on newly created flows */\nexport const LATEST_VERSION: FlowVersionString = '1.0.0';\n\n// ---------------------------------------------------------------------------\n// TEMPORARY: UCAN enforcement kill switch\n// ---------------------------------------------------------------------------\n\n/**\n * TEMPORARY — while `true`, UCAN enforcement is disabled for versions that\n * declare `ucanRequired` (i.e. 1.0.0). `getVersionPolicy` reports those\n * versions with `ucanRequired: false`, `delegationRootRequired: false` and\n * `ui.requirePinForExecution: false`, so blocks execute without a delegation\n * chain, reconciliation trusts run records without invocations, and no PIN\n * is requested. The manifest itself is untouched.\n *\n * To restore enforcement: set the default back to `false` and revert the\n * kill-switch assertions in `ucanEnforcement.test.ts`.\n */\nlet tempUcanEnforcementDisabled = true;\n\n/** Read the current state of the temporary kill switch above. */\nexport function isTempUcanEnforcementDisabled(): boolean {\n return tempUcanEnforcementDisabled;\n}\n\n/** Toggle the temporary kill switch (test hook / consumer escape hatch). */\nexport function setTempUcanEnforcementDisabled(disabled: boolean): void {\n tempUcanEnforcementDisabled = disabled;\n}\n\n/** Ordered migration path — each flow must step through versions sequentially */\nexport const MIGRATION_PATH: FlowVersionString[] = ['0.3', '1.0.0'];\n\n// ---------------------------------------------------------------------------\n// Utility functions\n// ---------------------------------------------------------------------------\n\n/**\n * Get the policy for a given schema version.\n * Unknown versions fall back to the strictest (latest) policy.\n */\nexport function getVersionPolicy(version: string): VersionPolicy {\n const policy = VERSION_MANIFEST[version as FlowVersionString] ?? VERSION_MANIFEST[LATEST_VERSION];\n // TEMPORARY: see the kill switch above — soften UCAN-enforcing policies.\n if (tempUcanEnforcementDisabled && policy.ucanRequired) {\n return {\n ...policy,\n ucanRequired: false,\n delegationRootRequired: false,\n ui: { ...policy.ui, requirePinForExecution: false },\n };\n }\n return policy;\n}\n\n/**\n * Check whether `current` is at least `minimum` in the migration path.\n */\nexport function isVersionAtLeast(current: string, minimum: FlowVersionString): boolean {\n const currentIdx = MIGRATION_PATH.indexOf(current as FlowVersionString);\n const minimumIdx = MIGRATION_PATH.indexOf(minimum);\n // Unknown versions are treated as latest (highest index)\n const effectiveCurrent = currentIdx === -1 ? MIGRATION_PATH.length : currentIdx;\n return effectiveCurrent >= minimumIdx;\n}\n\n/**\n * Get the next version in the migration path, or null if already at latest.\n */\nexport function getNextVersion(current: string): FlowVersionString | null {\n const idx = MIGRATION_PATH.indexOf(current as FlowVersionString);\n if (idx === -1 || idx >= MIGRATION_PATH.length - 1) {\n return null;\n }\n return MIGRATION_PATH[idx + 1];\n}\n\n/**\n * Get the chain of versions needed to migrate from `from` to `to`.\n * Returns the intermediate and target versions (excludes the `from` version).\n * Returns empty array if no migration needed or path is invalid.\n */\nexport function getMigrationChain(from: string, to: string): FlowVersionString[] {\n const fromIdx = MIGRATION_PATH.indexOf(from as FlowVersionString);\n const toIdx = MIGRATION_PATH.indexOf(to as FlowVersionString);\n\n if (fromIdx === -1 || toIdx === -1 || fromIdx >= toIdx) {\n return [];\n }\n\n return MIGRATION_PATH.slice(fromIdx + 1, toIdx + 1);\n}\n","import * as Y from 'yjs';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { TriggerSpec } from '../../types/baseUcan';\nimport { getAction } from '../actionRegistry/registry';\nimport { getVersionPolicy } from './versionManifest';\nimport { warnOnce } from '../warnOnce';\nimport {\n computePendingInvocationId,\n computeBarrierInvocationId,\n mergeBarrierPayloads,\n queuePendingInvocation,\n readConsumedPendingInvocationIds,\n readRunRecords,\n readBarrierState,\n recordBarrierEvent,\n clearBarrierState,\n snapshotInputRefs,\n sweepExpiredPendingInvocations,\n type PendingInvocation,\n type RunRecordDetails,\n} from './triggers';\n\n/**\n * Reconciliation loop — turns persisted run records into pending invocations\n * idempotently, so the trigger system survives page refreshes and works\n * across multiple connected clients.\n *\n * See `docs/flow-engine/events-and-triggers-plan.md` §18 for the full design rationale.\n *\n * Called from:\n * - The editor lifecycle on open (alongside performDMNotificationScan)\n * - The yDoc observer when remote run records arrive\n * - Immediately after a local action completes\n *\n * Idempotency comes from `computePendingInvocationId` producing the same id\n * for the same (sourceBlockId, sourceRunId, listenerBlockId, eventName,\n * eventIndex) tuple. Both ends of a sync compute the same id, both call\n * `Y.Map.set` on the same key, Yjs converges to one entry.\n *\n * The loop is intentionally write-only-on-new — it never deletes pending\n * invocations. Removal happens elsewhere (assignee invokes, expiration sweep).\n */\nlet _reconcileRunning = false;\n\nexport function reconcilePendingInvocations(editor: IxoEditorType): void {\n // Re-entrancy guard: barrier state writes trigger Yjs observers which\n // re-invoke reconciliation synchronously. Without this guard, cascading\n // re-entrant calls process different source blocks, each writing a new\n // barrier entry that triggers yet another observer. The guard ensures the\n // outer call completes all blocks before any observer-triggered call runs.\n if (_reconcileRunning) return;\n _reconcileRunning = true;\n try {\n _reconcilePendingInvocationsInner(editor);\n } finally {\n _reconcileRunning = false;\n }\n}\n\nfunction _reconcilePendingInvocationsInner(editor: IxoEditorType): void {\n const yDoc = (editor as unknown as { _yDoc?: Y.Doc })._yDoc;\n if (!yDoc) return;\n\n const blocks = (editor as unknown as { document?: any[] }).document || [];\n if (blocks.length === 0) return;\n\n // Build a map of (sourceBlockId, eventName) → listenerBlocks[]\n // by walking every block's parsed trigger.\n const listenersBySource = new Map<string, Array<{ block: any; trigger: TriggerSpec }>>();\n const barrierListenersBySource = new Map<string, Array<{ block: any; trigger: TriggerSpec; source: { sourceBlockId: string; eventName: string; alias: string } }>>();\n\n for (const block of blocks) {\n const trigger = parseTrigger(block);\n if (!trigger) continue;\n\n if (trigger.type === 'block.event') {\n if (!trigger.sourceBlockId || !trigger.eventName) continue;\n const key = `${trigger.sourceBlockId}::${trigger.eventName}`;\n if (!listenersBySource.has(key)) listenersBySource.set(key, []);\n listenersBySource.get(key)!.push({ block, trigger });\n } else if (trigger.type === 'block.event.all' && trigger.sources) {\n for (const source of trigger.sources) {\n if (!source.sourceBlockId || !source.eventName) continue;\n const key = `${source.sourceBlockId}::${source.eventName}`;\n if (!barrierListenersBySource.has(key)) barrierListenersBySource.set(key, []);\n barrierListenersBySource.get(key)!.push({ block, trigger, source });\n }\n }\n }\n\n if (listenersBySource.size === 0 && barrierListenersBySource.size === 0) return;\n\n // Compaction: physically drop expired pending invocations. Re-queue is\n // prevented below (queue-time expiry check), so the sweep cannot fight\n // the write-only-on-new loop.\n const now = Date.now();\n sweepExpiredPendingInvocations(yDoc, now);\n\n // Consumed-invocation dedup, computed lazily per listener: a listener's\n // own run records carry fromPendingInvocationId, and those ids must never\n // be re-queued from the immutable source run record.\n const consumedByListener = new Map<string, Set<string>>();\n const isConsumed = (listenerBlockId: string, pendingId: string): boolean => {\n let consumed = consumedByListener.get(listenerBlockId);\n if (!consumed) {\n consumed = readConsumedPendingInvocationIds(yDoc, listenerBlockId);\n consumedByListener.set(listenerBlockId, consumed);\n }\n return consumed.has(pendingId);\n };\n\n // On UCAN-enforced flows, only run records that reference a resolvable\n // invocation may fire triggers — a hand-written run record (or one from a\n // permissive-era client) must not advance the flow.\n const schemaVersionRaw = yDoc.getMap('root').get('schema_version');\n const ucanRequired = typeof schemaVersionRaw === 'string' ? !!getVersionPolicy(schemaVersionRaw)?.ucanRequired : false;\n const invocationsMap = yDoc.getMap('invocations');\n\n // Look up the current lastOutput for each block (for snapshot fallback).\n // We use the runtime map directly since we're outside React.\n const runtimeMap = (editor as unknown as { _yRuntime?: Y.Map<any> })._yRuntime;\n const getNodeOutput = (nodeId: string): Record<string, unknown> | undefined => {\n if (!runtimeMap) return undefined;\n const state = runtimeMap.get(nodeId);\n if (!state || typeof state !== 'object') return undefined;\n const out = (state as { output?: Record<string, unknown> }).output;\n return out && typeof out === 'object' ? out : undefined;\n };\n\n // For each block that has subscribed listeners, walk its run records and\n // queue pending invocations for any (run, event) pairs not yet queued.\n for (const block of blocks) {\n const sourceBlockId = block?.id;\n if (!sourceBlockId) continue;\n\n // Quick check — does any listener subscribe to this block at all?\n let hasAnyListener = false;\n for (const key of listenersBySource.keys()) {\n if (key.startsWith(`${sourceBlockId}::`)) {\n hasAnyListener = true;\n break;\n }\n }\n for (const key of barrierListenersBySource.keys()) {\n if (key.startsWith(`${sourceBlockId}::`)) {\n hasAnyListener = true;\n break;\n }\n }\n if (!hasAnyListener) continue;\n\n const records = readRunRecords(yDoc, sourceBlockId);\n for (const record of records) {\n if (!isTrustedRunRecord(record, ucanRequired, invocationsMap)) continue;\n processRunRecord(yDoc, sourceBlockId, record, listenersBySource, getNodeOutput, runtimeMap, isConsumed, now);\n processBarrierRunRecord(yDoc, sourceBlockId, record, barrierListenersBySource, getNodeOutput, runtimeMap, isConsumed, now);\n }\n }\n}\n\n/**\n * Decide whether a run record may act as a trigger source.\n *\n * Legacy flows trust every record (room-level access control). On\n * UCAN-enforced flows a record must reference an invocation that resolves in\n * the doc's `invocations` map — INCLUDING read-back reconciliation records.\n *\n * H3: read-back records (`reconciled: true`) used to be trusted\n * unconditionally, so any room member could write a record with that flag set\n * and fire downstream triggers on a UCAN-enforced flow. They now chain to the\n * same evidence as every other record: `writeReconciliationRunRecord` carries\n * the original execution's `invocationCid` forward (from the read-back\n * metadata), and that CID must resolve here. A hand-written `reconciled: true`\n * with no resolvable invocation is no longer trusted.\n *\n * TRUST BOUNDARY (still open, tracked as the remaining part of H3): this is a\n * store-level presence check. The invocation's CAR signature was verified when\n * it was minted, but it is NOT re-verified here. A room member with write\n * access can still forge BOTH a run record and a matching invocation entry.\n * Fully closing forgery requires re-verifying the stored CAR signature against\n * the delegation chain at read time — a 1.0.0 trust-model decision, not a\n * presence tweak. Do not describe this check as making completions\n * unforgeable.\n */\nfunction isTrustedRunRecord(record: RunRecordDetails, ucanRequired: boolean, invocationsMap: Y.Map<unknown>): boolean {\n if (!ucanRequired) return true;\n if (!record.invocationCid) return false;\n return invocationsMap.get(record.invocationCid) !== undefined;\n}\n\n/**\n * Process a single run record: for each event it emitted, queue a pending\n * invocation on every subscribed listener if not already queued.\n */\nfunction processRunRecord(\n yDoc: Y.Doc,\n sourceBlockId: string,\n record: RunRecordDetails,\n listenersBySource: Map<string, Array<{ block: any; trigger: TriggerSpec }>>,\n getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined,\n runtimeMap: Y.Map<any> | undefined,\n isConsumed: (listenerBlockId: string, pendingId: string) => boolean,\n now: number\n): void {\n if (!Array.isArray(record.events)) return;\n\n record.events.forEach((event, eventIndex) => {\n if (!event?.name) return;\n const key = `${sourceBlockId}::${event.name}`;\n const listeners = listenersBySource.get(key);\n if (!listeners || listeners.length === 0) return;\n\n for (const { block: listenerBlock } of listeners) {\n const listenerBlockId = listenerBlock.id;\n if (!listenerBlockId) continue;\n\n const id = computePendingInvocationId({\n sourceBlockId,\n sourceRunId: record.runId,\n listenerBlockId,\n eventName: event.name,\n eventIndex,\n });\n\n // A pending invocation the listener already ran must not resurrect\n // from the immutable source run record after its removal-on-invoke.\n if (isConsumed(listenerBlockId, id)) continue;\n\n const assigneeDid = resolveAssignee(listenerBlock) || 'unassigned';\n\n // Snapshot every nodeId.output.* ref the listener references at this\n // moment. This is the §3.5.1 fix that makes the Sally → Mike scenario\n // produce frozen values per pending invocation.\n const inputs = parseInputs(listenerBlock);\n const refSnapshots = snapshotInputRefs(inputs, getNodeOutput);\n\n const expiresAt = computeExpiry(listenerBlock, record.completedAt);\n\n // Never (re-)queue an invocation that is already past its expiry —\n // this is what lets the expiration sweep physically delete entries\n // without the write-only-on-new loop restoring them.\n if (expiresAt && Date.parse(expiresAt) < now) continue;\n\n const invocation: PendingInvocation = {\n id,\n triggeringBlockId: sourceBlockId,\n sourceRunId: record.runId,\n eventName: event.name,\n eventIndex,\n payload: event.payload as Record<string, unknown>,\n refSnapshots,\n assigneeDid,\n emittedAt: record.completedAt,\n expiresAt,\n };\n\n queuePendingInvocation(yDoc, listenerBlockId, invocation);\n\n // Write the payload into the listener's runtime so the FlowDetail\n // can read it without depending on React state.\n if (runtimeMap) {\n const prev = (runtimeMap.get(listenerBlockId) || {}) as Record<string, unknown>;\n runtimeMap.set(listenerBlockId, {\n ...prev,\n pendingPayload: { ...(event.payload as Record<string, unknown>), ...refSnapshots },\n });\n }\n }\n });\n}\n\nfunction processBarrierRunRecord(\n yDoc: Y.Doc,\n sourceBlockId: string,\n record: RunRecordDetails,\n barrierListenersBySource: Map<string, Array<{ block: any; trigger: TriggerSpec; source: { sourceBlockId: string; eventName: string; alias: string } }>>,\n getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined,\n runtimeMap: Y.Map<any> | undefined,\n isConsumed: (listenerBlockId: string, pendingId: string) => boolean,\n now: number\n): void {\n if (!Array.isArray(record.events)) return;\n\n for (const event of record.events) {\n if (!event?.name) continue;\n const key = `${sourceBlockId}::${event.name}`;\n const listeners = barrierListenersBySource.get(key);\n if (!listeners || listeners.length === 0) continue;\n\n for (const { block: listenerBlock, trigger, source } of listeners) {\n const listenerBlockId = listenerBlock.id;\n if (!listenerBlockId) continue;\n\n const entry = {\n sourceBlockId,\n eventName: event.name,\n alias: source.alias,\n runId: record.runId,\n payload: (event.payload as Record<string, unknown>) || {},\n emittedAt: record.completedAt,\n };\n\n recordBarrierEvent(yDoc, listenerBlockId, entry);\n\n // Accumulate this source's payload into the listener's runtime\n // so partial barrier state is visible to the FlowDetail.\n if (runtimeMap) {\n const prev = (runtimeMap.get(listenerBlockId) || {}) as Record<string, unknown>;\n const existing = (prev.pendingPayload || {}) as Record<string, unknown>;\n runtimeMap.set(listenerBlockId, {\n ...prev,\n pendingPayload: { ...existing, ...((event.payload as Record<string, unknown>) || {}) },\n });\n }\n\n const allSources = trigger.sources || [];\n const currentState = readBarrierState(yDoc, listenerBlockId);\n\n // Optional sources don't gate queuing — the barrier fires once every\n // required source has fired. Optional payloads are merged in if they\n // already arrived (mergeBarrierPayloads reads currentState below).\n const requiredSources = allSources.filter((s) => s.optional !== true);\n // Degenerate all-optional config falls back to \"all sources\" so the\n // barrier can still complete instead of never firing.\n const gatingSources = requiredSources.length > 0 ? requiredSources : allSources;\n\n const allFired = gatingSources.length > 0 && gatingSources.every((s) => currentState.some((e) => e.sourceBlockId === s.sourceBlockId && e.eventName === s.eventName));\n\n if (!allFired) continue;\n\n const assigneeDid = resolveAssignee(listenerBlock) || 'unassigned';\n\n const id = computeBarrierInvocationId(currentState, listenerBlockId);\n // A barrier invocation the listener already ran must not resurrect.\n if (isConsumed(listenerBlockId, id)) continue;\n const mergedPayload = mergeBarrierPayloads(currentState);\n\n const inputs = parseInputs(listenerBlock);\n const refSnapshots = snapshotInputRefs(inputs, getNodeOutput);\n const expiresAt = computeExpiry(listenerBlock, record.completedAt);\n\n // Never (re-)queue an invocation that is already past its expiry —\n // this is what lets the expiration sweep physically delete entries\n // without the write-only-on-new loop restoring them.\n if (expiresAt && Date.parse(expiresAt) < now) continue;\n\n const invocation: PendingInvocation = {\n id,\n triggeringBlockId: sourceBlockId,\n sourceRunId: record.runId,\n eventName: `barrier:${allSources.map((s) => s.alias).join('+')}`,\n eventIndex: 0,\n payload: mergedPayload,\n refSnapshots,\n assigneeDid,\n emittedAt: record.completedAt,\n expiresAt,\n };\n\n queuePendingInvocation(yDoc, listenerBlockId, invocation);\n clearBarrierState(yDoc, listenerBlockId);\n\n // Persist the merged payload into the listener block's runtime so the\n // FlowDetail can read it across navigation without relying on React state.\n if (runtimeMap) {\n const prev = (runtimeMap.get(listenerBlockId) || {}) as Record<string, unknown>;\n runtimeMap.set(listenerBlockId, {\n ...prev,\n pendingPayload: { ...mergedPayload, ...refSnapshots },\n });\n }\n }\n }\n}\n\n// ─── Block prop helpers ─────────────────────────────────────────────────────\n\nfunction parseTrigger(block: any): TriggerSpec | null {\n const raw = block?.props?.trigger;\n if (!raw || typeof raw !== 'string') return null;\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === 'object' && typeof parsed.type === 'string') {\n return parsed as TriggerSpec;\n }\n } catch {\n // Invalid trigger JSON — treat as no trigger, but say so once.\n warnOnce(`trigger-parse:${block?.id}`, `[flow-config] block ${block?.id}: props.trigger is not valid JSON; trigger ignored`);\n }\n return null;\n}\n\nfunction parseInputs(block: any): Record<string, unknown> {\n const raw = block?.props?.inputs;\n if (!raw || typeof raw !== 'string') return {};\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === 'object') return parsed as Record<string, unknown>;\n } catch {\n // Invalid inputs JSON — treat as empty, but say so once.\n warnOnce(`inputs-parse:${block?.id}`, `[flow-config] block ${block?.id}: props.inputs is not valid JSON; treated as empty`);\n }\n return {};\n}\n\nfunction resolveAssignee(block: any): string | undefined {\n const raw = block?.props?.assignment;\n if (!raw) return undefined;\n try {\n const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;\n const did = parsed?.assignedActor?.did;\n return typeof did === 'string' && did.length > 0 ? did : undefined;\n } catch {\n warnOnce(`assignment-parse:${block?.id}`, `[flow-config] block ${block?.id}: props.assignment is not valid JSON; assignee unresolved`);\n return undefined;\n }\n}\n\n/**\n * Compute the expiration timestamp for a pending invocation, reusing the\n * existing TTL props on the listener block (slice D persists these via\n * blockMapping). Falls back to 7 days from emission if no TTL is set.\n */\nfunction computeExpiry(block: any, emittedAt: string): string {\n const ttlAbsolute = block?.props?.ttlAbsoluteDueDate;\n if (typeof ttlAbsolute === 'string' && ttlAbsolute) {\n return ttlAbsolute;\n }\n\n const ttlFromEnablement = block?.props?.ttlFromEnablement;\n if (typeof ttlFromEnablement === 'string' && ttlFromEnablement) {\n // Parse ISO 8601 duration like \"P7D\" → milliseconds\n const ms = parseIsoDurationToMs(ttlFromEnablement);\n if (ms != null) {\n return new Date(new Date(emittedAt).getTime() + ms).toISOString();\n }\n }\n\n // Default: 7 days\n return new Date(new Date(emittedAt).getTime() + 7 * 24 * 60 * 60 * 1000).toISOString();\n}\n\n/** Parse a small subset of ISO 8601 durations: P[n]D, PT[n]H, PT[n]M, PT[n]S. */\nfunction parseIsoDurationToMs(duration: string): number | null {\n const match = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$/.exec(duration);\n if (!match) return null;\n const [, d, h, m, s] = match;\n let ms = 0;\n if (d) ms += parseInt(d, 10) * 24 * 60 * 60 * 1000;\n if (h) ms += parseInt(h, 10) * 60 * 60 * 1000;\n if (m) ms += parseInt(m, 10) * 60 * 1000;\n if (s) ms += parseInt(s, 10) * 1000;\n return ms;\n}\n\n// ─── Action registry compatibility ──────────────────────────────────────────\n// The reconciliation loop doesn't strictly need to look up the action — it\n// trusts the compiler to have validated the trigger and event vocabulary at\n// compile time. But for diagnostics, expose a helper that returns the action\n// for a given block. Used by slice F's tests and slice J's UI.\n\nexport function getActionForBlock(block: any): ReturnType<typeof getAction> {\n const actionType = block?.props?.actionType;\n if (typeof actionType !== 'string') return undefined;\n return getAction(actionType);\n}\n","import * as Y from 'yjs';\nimport type { IxoEditorType } from '../../types/editor';\nimport { appendRunRecord, type RunRecordDetails } from './triggers';\nimport { reconcilePendingInvocations } from './reconcile';\n\n/**\n * Write a run record to the audit trail and trigger the reconciliation loop\n * so listener blocks pick up the emitted events as pending invocations.\n *\n * Call this after `updateRuntime({ state: 'completed', output })` in any\n * FlowDetail component whose action defines events.\n */\nexport function writeRunRecordAndReconcile(\n editor: IxoEditorType,\n blockId: string,\n output: Record<string, unknown>,\n events: Array<{ name: string; payload: Record<string, unknown> }>,\n actorDid: string,\n detailsPatch: Partial<RunRecordDetails> & { sourceRunId?: string } = {}\n): void {\n const yDoc = (editor as unknown as { _yDoc?: Y.Doc })._yDoc;\n if (!yDoc) return;\n if (events.length === 0) return;\n\n const runId = `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n const now = new Date().toISOString();\n\n const details: RunRecordDetails = {\n runId,\n output,\n events,\n startedAt: now,\n completedAt: now,\n actorDid,\n ...detailsPatch,\n };\n\n appendRunRecord(yDoc, blockId, details, actorDid);\n reconcilePendingInvocations(editor);\n}\n","import { FlowNode, FlowNodeAuthzExtension } from '../../types/authorization';\n\nexport const buildAuthzFromProps = (props: Record<string, any>): FlowNodeAuthzExtension => {\n const linkedClaimCollectionId = typeof props.linkedClaimCollectionId === 'string' ? props.linkedClaimCollectionId.trim() : '';\n\n const authz: FlowNodeAuthzExtension = {};\n\n if (linkedClaimCollectionId) {\n authz.linkedClaim = { collectionId: linkedClaimCollectionId };\n }\n\n return authz;\n};\n\nexport const buildFlowNodeFromBlock = (block: any): FlowNode => {\n const base: FlowNode = {\n id: block.id,\n type: block.type,\n props: block.props || {},\n } as FlowNode;\n\n const authz = buildAuthzFromProps(block.props || {});\n\n return {\n ...base,\n ...authz,\n };\n};\n","import type { Doc, Map as YMap } from 'yjs';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { IxoEditorType } from '../../types/editor';\n\nconst XERO_WORK_ITEMS_MAP_NAME = 'xeroWorkItems';\nconst XERO_WORK_TERMINAL_MAP_NAME = 'xeroWorkItemsTerminal';\nconst XERO_CONNECTION_MAP_NAME = 'xeroConnection';\n\nexport interface FlowRuntimeStateManager {\n get: (nodeId: string) => FlowNodeRuntimeState;\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => void;\n}\n\nconst ensureStateObject = (value: unknown): FlowNodeRuntimeState => {\n if (!value || typeof value !== 'object') {\n return {};\n }\n return { ...(value as FlowNodeRuntimeState) };\n};\n\nconst createYMapManager = (map: YMap<any>): FlowRuntimeStateManager => {\n return {\n get: (nodeId: string) => {\n const stored = map.get(nodeId);\n return ensureStateObject(stored);\n },\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => {\n const current = ensureStateObject(map.get(nodeId));\n map.set(nodeId, { ...current, ...updates });\n },\n };\n};\n\nconst createMemoryManager = (): FlowRuntimeStateManager => {\n const memory = new Map<string, FlowNodeRuntimeState>();\n return {\n get: (nodeId: string) => ensureStateObject(memory.get(nodeId)),\n update: (nodeId: string, updates: Partial<FlowNodeRuntimeState>) => {\n const current = ensureStateObject(memory.get(nodeId));\n memory.set(nodeId, { ...current, ...updates });\n },\n };\n};\n\nexport const createRuntimeStateManager = (editor?: IxoEditorType | null): FlowRuntimeStateManager => {\n if (editor?._yRuntime) {\n return createYMapManager(editor._yRuntime);\n }\n return createMemoryManager();\n};\n\nexport const createYDocRuntimeManager = (yDoc: Doc): FlowRuntimeStateManager => {\n return createYMapManager(yDoc.getMap('runtime'));\n};\n\n/**\n * Clears runtime, invocations, and pending invocations from a Y.Doc.\n * Used when cloning a flow as a template — the new document should\n * carry only configuration (intent), not execution history.\n *\n * The audit trail (which now also holds run records as `type: 'block.run'`\n * entries) and pending invocations are observation, not configuration —\n * both are cleared on template clone.\n */\nexport function clearRuntimeForTemplateClone(yDoc: Doc): void {\n const runtime = yDoc.getMap('runtime');\n const invocations = yDoc.getMap('invocations');\n const pendingInvocations = yDoc.getMap('pendingInvocations');\n const agentOutbox = yDoc.getMap('agentOutbox');\n const agentLeases = yDoc.getMap('agentLeases');\n const auditTrail = yDoc.getMap('auditTrail');\n const xeroWorkItems = yDoc.getMap(XERO_WORK_ITEMS_MAP_NAME);\n const xeroWorkTerminal = yDoc.getMap(XERO_WORK_TERMINAL_MAP_NAME);\n const xeroConnection = yDoc.getMap(XERO_CONNECTION_MAP_NAME);\n\n yDoc.transact(() => {\n runtime.forEach((_, key) => runtime.delete(key));\n invocations.forEach((_, key) => invocations.delete(key));\n pendingInvocations.forEach((_, key) => pendingInvocations.delete(key));\n agentOutbox.forEach((_, key) => agentOutbox.delete(key));\n agentLeases.forEach((_, key) => agentLeases.delete(key));\n auditTrail.forEach((_, key) => auditTrail.delete(key));\n xeroWorkItems.forEach((_, key) => xeroWorkItems.delete(key));\n xeroWorkTerminal.forEach((_, key) => xeroWorkTerminal.delete(key));\n xeroConnection.forEach((_, key) => xeroConnection.delete(key));\n });\n}\n","import { isRuntimeRef } from '../../types/baseUcan';\nimport { getNestedValue } from '../flowEngine/referenceResolver';\n\n/**\n * Context passed to resolveRuntimeRefs when resolving inputs for a triggered\n * listener block. The runtime constructs this from a PendingInvocation when\n * the assignee invokes the listener.\n *\n * - `payload`: the frozen event payload, used to resolve `trigger.payload.*` refs\n * - `refSnapshots`: frozen `nodeId.output.*` values captured at queue time,\n * used to resolve those refs against the moment of emission rather than\n * current state. See docs/flow-engine/events-and-triggers-plan.md §3.5.1 for the\n * Sally → Mike scenario this fixes.\n */\nexport interface TriggerResolutionContext {\n payload: Record<string, unknown>;\n refSnapshots: Record<string, unknown>;\n}\n\n/**\n * Resolve runtime references in an nb (caveats) object.\n *\n * At compile time, `{ \"$ref\": \"nodeId.output.fieldPath\" }` values are serialized\n * as-is into the block's `inputs` JSON string. At execution time, this function\n * replaces them with actual output values from upstream nodes.\n *\n * Two ref namespaces are supported:\n * - `nodeId.output.fieldPath` — looked up via `getNodeOutput`. When a\n * `triggerContext` is provided AND `refSnapshots[ref]` exists, the\n * snapshot is preferred over the live lookup. This is the load-bearing\n * fix for the lag-time scenario where multiple pending invocations are\n * queued and the source block re-runs before the assignee acts on them.\n * - `trigger.payload.fieldPath` — looked up in `triggerContext.payload`.\n * Only valid when `triggerContext` is provided (i.e. resolving inputs\n * for a triggered listener invocation). Compile-time validation in\n * compiler.ts guarantees these only appear on `block.event`-triggered\n * blocks.\n *\n * @param nb - The caveats object (may contain nested RuntimeRef values)\n * @param getNodeOutput - Lookup function for upstream node outputs\n * @param triggerContext - Optional, present only for triggered listener invocations\n * @returns A new object with all $ref values resolved\n */\nexport function resolveRuntimeRefs(\n nb: Record<string, unknown>,\n getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined,\n triggerContext?: TriggerResolutionContext\n): Record<string, unknown> {\n return resolveValue(nb, getNodeOutput, triggerContext) as Record<string, unknown>;\n}\n\nfunction resolveValue(value: unknown, getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined, triggerContext?: TriggerResolutionContext): unknown {\n if (isRuntimeRef(value)) {\n return resolveRef(value.$ref, getNodeOutput, triggerContext);\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => resolveValue(item, getNodeOutput, triggerContext));\n }\n\n if (typeof value === 'object' && value !== null) {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = resolveValue(val, getNodeOutput, triggerContext);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Resolve a single $ref string.\n *\n * Supported forms:\n * - \"trigger.payload.fieldPath\" — looked up in triggerContext.payload\n * - \"nodeId.output.fieldPath\" — looked up in triggerContext.refSnapshots first\n * (if present), falling back to getNodeOutput. Snapshot preference is\n * what makes the Sally → Mike scenario produce frozen values per pending\n * invocation.\n */\nfunction resolveRef(ref: string, getNodeOutput: (nodeId: string) => Record<string, unknown> | undefined, triggerContext?: TriggerResolutionContext): unknown {\n // trigger.payload.* — only valid when a triggerContext is provided\n if (ref.startsWith('trigger.payload.')) {\n if (!triggerContext) {\n throw new Error(`Trigger ref \"${ref}\" used outside of a listener invocation context. trigger.payload.* refs are only valid on block.event-triggered blocks.`);\n }\n const fieldPath = ref.slice('trigger.payload.'.length);\n return getNestedValue(triggerContext.payload, fieldPath);\n }\n\n // nodeId.output.fieldPath — prefer the snapshot if we're inside a trigger context\n if (triggerContext && Object.prototype.hasOwnProperty.call(triggerContext.refSnapshots, ref)) {\n return triggerContext.refSnapshots[ref];\n }\n\n // Parse \"nodeId.output.fieldPath\"\n const outputIndex = ref.indexOf('.output.');\n if (outputIndex === -1) {\n throw new Error(`Invalid runtime reference \"${ref}\". Expected format: \"nodeId.output.fieldPath\" or \"trigger.payload.fieldPath\"`);\n }\n\n const nodeId = ref.slice(0, outputIndex);\n const fieldPath = ref.slice(outputIndex + '.output.'.length);\n\n const output = getNodeOutput(nodeId);\n if (!output) {\n return undefined;\n }\n\n // Traverse the field path (supports dot notation)\n return getNestedValue(output, fieldPath);\n}\n","import type { UcanCapability } from '../../types/ucan';\nimport type { UcanService } from '../../services/ucanService';\nimport { getVersionPolicy } from './versionManifest';\n\nexport interface AuthorizationResult {\n authorized: boolean;\n reason?: string;\n capabilityId?: string;\n proofCids?: string[];\n}\n\n/**\n * Check if an actor is authorized to execute a block.\n *\n * Behaviour depends on the flow's schema version:\n * - v0.x (or no version): UCAN is optional. If ucanService is unavailable,\n * execution is allowed without a delegation chain.\n * - v1.0.0+: UCAN is required. A valid delegation chain must exist.\n */\nexport const isAuthorized = async (\n blockId: string,\n actorDid: string,\n ucanService: UcanService | undefined,\n flowUri: string,\n schemaVersion?: string\n): Promise<AuthorizationResult> => {\n const policy = schemaVersion ? getVersionPolicy(schemaVersion) : null;\n\n // If UCAN is not required by this version, allow execution without delegation chain\n if (policy && !policy.ucanRequired) {\n return { authorized: true };\n }\n\n // UCAN is required (v1.0.0+ or unknown version) — ucanService must be available\n if (!ucanService) {\n // No ucanService and no version info: allow for backward compatibility\n if (!policy) {\n return { authorized: true };\n }\n return {\n authorized: false,\n reason: 'UCAN service is not configured. This flow version requires UCAN authorization.',\n };\n }\n\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${flowUri}:${blockId}`,\n };\n\n const result = await ucanService.validateDelegationChain(actorDid, capability);\n\n if (!result.valid) {\n return {\n authorized: false,\n reason: result.error || 'No valid capability chain found',\n };\n }\n\n const proofCids = result.proofChain?.map((d) => d.cid) || [];\n\n return {\n authorized: true,\n capabilityId: proofCids[0],\n proofCids,\n };\n};\n","import { isAuthorized } from './authorization';\nimport type { FlowNode, FlowNodeRuntimeState, EvaluationStatus } from '../../types/authorization';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport type { InvocationStore } from '../invocationStore';\nimport type { UcanService } from '../../services/ucanService';\nimport type { StoredInvocation, UcanCapability } from '../../types/ucan';\n\nexport interface NodeActionResult {\n claimId?: string;\n evaluationStatus?: EvaluationStatus;\n submittedByDid?: string;\n payload?: any;\n}\n\nexport interface ExecutionContext {\n runtime: FlowRuntimeStateManager;\n /** UCAN service — optional for v0.x flows, required for v1.0.0+ */\n ucanService?: UcanService;\n /** Invocation store — optional for v0.x flows */\n invocationStore?: InvocationStore;\n flowUri: string;\n flowId: string;\n flowOwnerDid: string;\n /** Flow schema version. When set, controls whether UCAN is enforced. */\n schemaVersion?: string;\n now?: () => number;\n}\n\nexport interface ExecutionOutcome {\n success: boolean;\n stage: 'authorization' | 'claim' | 'action' | 'complete';\n error?: string;\n result?: NodeActionResult;\n capabilityId?: string;\n invocationCid?: string;\n}\n\nexport interface ExecuteNodeParams {\n node: FlowNode;\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n context: ExecutionContext;\n action: () => Promise<NodeActionResult>;\n pin: string;\n}\n\nconst updateRuntimeAfterSuccess = (\n node: FlowNode,\n actorDid: string,\n runtime: FlowRuntimeStateManager,\n actionResult: NodeActionResult,\n invocationCid?: string,\n now?: () => number\n) => {\n const updates: FlowNodeRuntimeState = {\n submittedByDid: actionResult.submittedByDid || actorDid,\n evaluationStatus: actionResult.evaluationStatus || 'pending',\n executionTimestamp: now ? now() : Date.now(),\n lastInvocationCid: invocationCid,\n };\n\n if (actionResult.claimId) {\n updates.claimId = actionResult.claimId;\n }\n\n runtime.update(node.id, updates);\n};\n\n/**\n * Execute a node.\n *\n * The pipeline adapts based on the flow's schema version (via context.schemaVersion):\n *\n * **v0.x (legacy):** activation → action → runtime update.\n * UCAN authorization and invocations are skipped when ucanService is not available.\n *\n * **v1.0.0+:** activation → UCAN authorization → invocation → action → runtime update.\n * Requires a configured ucanService with valid delegation chains.\n */\nexport const executeNode = async ({ node, actorDid, actorType, entityRoomId, context, action, pin }: ExecuteNodeParams): Promise<ExecutionOutcome> => {\n const { runtime, ucanService, invocationStore, flowUri, flowId, schemaVersion, now } = context;\n\n // 1. Check authorization (version-aware: skips UCAN for v0.x when service unavailable)\n const auth = await isAuthorized(node.id, actorDid, ucanService, flowUri, schemaVersion);\n if (!auth.authorized) {\n return { success: false, stage: 'authorization', error: auth.reason };\n }\n\n // 3. Check linked claim requirement\n if (node.linkedClaim && !node.linkedClaim.collectionId) {\n return { success: false, stage: 'claim', error: 'Linked claim collection is required but missing.' };\n }\n\n // 4. Create invocation BEFORE execution (only when UCAN proof chain exists)\n let invocationCid: string | undefined;\n let invocationData: string | undefined;\n\n if (ucanService && auth.proofCids && auth.proofCids.length > 0) {\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${flowUri}:${node.id}`,\n };\n\n try {\n const invocationResult = await ucanService.createAndValidateInvocation(\n {\n invokerDid: actorDid,\n invokerType: actorType,\n entityRoomId,\n capability,\n proofs: auth.proofCids,\n pin,\n },\n flowId,\n node.id\n );\n\n if (!invocationResult.valid) {\n return {\n success: false,\n stage: 'authorization',\n error: `Invocation validation failed: ${invocationResult.error}`,\n };\n }\n\n invocationCid = invocationResult.cid;\n invocationData = invocationResult.invocation;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to create invocation';\n return { success: false, stage: 'authorization', error: message };\n }\n }\n\n // 5. Execute action\n try {\n const result = await action();\n\n // 6. Verify linked claim was provided if required\n if (node.linkedClaim && !result.claimId) {\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'failure',\n error: 'Execution did not return a claimId for linked claim requirement.',\n proofCids: auth.proofCids || [],\n };\n invocationStore.add(storedInvocation);\n }\n\n return {\n success: false,\n stage: 'claim',\n error: 'Execution did not return a claimId for linked claim requirement.',\n invocationCid,\n };\n }\n\n // 7. Store successful invocation\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'success',\n proofCids: auth.proofCids || [],\n claimId: result.claimId,\n };\n invocationStore.add(storedInvocation);\n }\n\n // 8. Update runtime state\n updateRuntimeAfterSuccess(node, actorDid, runtime, result, invocationCid || auth.capabilityId, now);\n\n return {\n success: true,\n stage: 'complete',\n result,\n capabilityId: auth.capabilityId,\n invocationCid,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Execution failed';\n\n // Store failed invocation\n if (invocationStore && invocationCid && invocationData) {\n const storedInvocation: StoredInvocation = {\n cid: invocationCid,\n invocation: invocationData,\n invokerDid: actorDid,\n capability: { can: 'flow/block/execute', with: `${flowUri}:${node.id}` },\n executedAt: now ? now() : Date.now(),\n flowId,\n blockId: node.id,\n result: 'failure',\n error: message,\n proofCids: auth.proofCids || [],\n };\n invocationStore.add(storedInvocation);\n }\n\n return { success: false, stage: 'action', error: message, invocationCid };\n }\n};\n\n// ---------------------------------------------------------------------------\n// Version-aware execution dispatch (convenience wrapper)\n// ---------------------------------------------------------------------------\n\nexport interface ExecuteNodeVersionedParams {\n node: FlowNode;\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n schemaVersion: string;\n context: ExecutionContext;\n action: () => Promise<NodeActionResult>;\n pin: string;\n}\n\n/**\n * Convenience wrapper that ensures schemaVersion is set on the context.\n * Prefer using executeNode directly with context.schemaVersion set.\n */\nexport const executeNodeVersioned = async (params: ExecuteNodeVersionedParams): Promise<ExecutionOutcome> => {\n return executeNode({\n node: params.node,\n actorDid: params.actorDid,\n actorType: params.actorType,\n entityRoomId: params.entityRoomId,\n context: { ...params.context, schemaVersion: params.schemaVersion },\n action: params.action,\n pin: params.pin,\n });\n};\n","import type { ActionDefinition, ActionProofDeclaration } from '../actionRegistry/types';\n\nexport const PROOF_MISSING_CODE = 'PROOF_MISSING';\n\nexport interface ProofValidationResult {\n valid: boolean;\n reason?: string;\n}\n\nfunction getOutputValue(output: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc && typeof acc === 'object') return (acc as Record<string, unknown>)[key];\n return undefined;\n }, output);\n}\n\nfunction isProofValue(value: unknown): boolean {\n if (Array.isArray(value)) return value.length > 0;\n // A numeric proof field is present when it is any real number — including\n // 0, which is a legitimate value for zero-indexed on-chain ids, a `status`\n // of 0, or an epoch timestamp. `!!value` would wrongly reject those. `false`\n // stays non-proof: a boolean success flag (configStored, alreadyExisted) is\n // only proof when true.\n if (typeof value === 'number') return !Number.isNaN(value);\n return !!value;\n}\n\n/**\n * Validate a successful action run's output against the action's proof\n * declaration. Called by `executeActionBlock` before writing\n * `state: 'completed'` — success without proof becomes a failure.\n *\n * A `sideEffect: true` action with no declaration fails closed; a\n * side-effect-free action with no declaration is tolerated (legacy\n * consumer-registered actions) but should declare `'none'` explicitly.\n */\nexport function validateActionProof(\n action: Pick<ActionDefinition, 'type' | 'sideEffect'> & { proof?: ActionProofDeclaration },\n output: Record<string, unknown>\n): ProofValidationResult {\n const proof = action.proof;\n\n if (proof === 'none') return { valid: true };\n\n if (proof === undefined) {\n if (action.sideEffect) {\n return {\n valid: false,\n reason: `Action '${action.type}' has a side effect but declares no proof of execution. Declare proof (or 'none') on its ActionDefinition.`,\n };\n }\n return { valid: true };\n }\n\n if ('validate' in proof) {\n let valid = false;\n try {\n valid = proof.validate(output);\n } catch {\n valid = false;\n }\n return valid ? { valid: true } : { valid: false, reason: `Action '${action.type}' returned success but its proof validator rejected the output.` };\n }\n\n const satisfied = proof.fields.some((field) => isProofValue(getOutputValue(output, field)));\n if (satisfied) return { valid: true };\n return {\n valid: false,\n reason: `Action '${action.type}' returned success without proof. Expected at least one of [${proof.fields.join(', ')}] in the output. Check the handler logs.`,\n };\n}\n","import type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { StoredInvocation } from '../../types/ucan';\nimport { getAction } from '../actionRegistry';\nimport { validateActionProof } from './proof';\nimport { getVersionPolicy } from './versionManifest';\n\nexport type CompletionVerificationStatus = 'verified' | 'unverified' | 'not_completed';\n\nexport interface CompletionVerification {\n status: CompletionVerificationStatus;\n /** Populated when status is 'unverified'. */\n reason?: string;\n}\n\nexport interface VerifyCompletionParams {\n runtime: FlowNodeRuntimeState | undefined | null;\n blockId: string;\n /** Action type of the block, used to re-check the proof declaration. */\n actionType?: string;\n /** Invocation lookup, typically backed by the doc's `invocations` Y.Map. */\n getInvocation?: (cid: string) => StoredInvocation | undefined | null;\n /** Flow schema version; UCAN binding is only required when the version policy demands it. */\n schemaVersion?: string;\n}\n\n/**\n * Decide whether a block's `state: 'completed'` can be trusted.\n *\n * Anyone with room write access can set `completed` directly in the runtime\n * Y.Map — a completion is only *verified* when it carries the evidence the\n * execution kernel writes:\n *\n * 1. Proof of execution per the action's `proof` declaration (all versions).\n * 2. On UCAN-enforced flows (policy.ucanRequired), a `lastInvocationCid`\n * that resolves in the invocation store to a successful invocation for\n * this block.\n *\n * The invocation check is store-level PRESENCE, not a cryptographic\n * re-verification of the CAR bytes: signatures are validated when the\n * invocation is minted, but the `invocations` Y.Map is room-writable, so a\n * member with write access can forge a matching `{ result: 'success', blockId }`\n * entry and pass this check. This raises the bar (a completion must at least\n * reference a resolvable, successful, block-matching invocation) but does NOT\n * make completions unforgeable — that needs read-time CAR-signature\n * re-verification against the delegation chain (open trust-model decision, H3).\n * Do not describe a completion that passes here as \"impossible to forge\".\n *\n * Consumers gate on this instead of raw `state === 'completed'`:\n * trigger reconciliation (event sources), flow-agent planning (Done\n * classification), and the FlowView completion badge.\n */\nexport function verifyCompletion(params: VerifyCompletionParams): CompletionVerification {\n const { runtime, blockId, actionType, getInvocation, schemaVersion } = params;\n\n if (!runtime || runtime.state !== 'completed') {\n return { status: 'not_completed' };\n }\n\n // A human resolved a `needs_verification` block by confirming the side effect\n // really happened (see NodeState 'needs_verification'). This is a deliberate\n // human-in-the-loop override of the missing declared proof — trust it, but it\n // is recorded (manuallyVerifiedByDid/At) for the audit trail. Preferable to\n // leaving a genuinely-completed on-chain action stuck Blocked forever.\n if (runtime.manuallyVerified === true) {\n return { status: 'verified' };\n }\n\n // Proof re-check applies to every version: a completed entry whose output\n // lacks the declared proof is stale or forged.\n if (actionType) {\n const action = getAction(actionType);\n if (action) {\n const proofCheck = validateActionProof(action, (runtime.output as Record<string, unknown>) || {});\n if (!proofCheck.valid) {\n return { status: 'unverified', reason: proofCheck.reason || 'Completed without proof of execution.' };\n }\n }\n }\n\n const policy = schemaVersion ? getVersionPolicy(schemaVersion) : null;\n if (!policy?.ucanRequired) {\n // Legacy flows: room-level access control is the trust boundary.\n return { status: 'verified' };\n }\n\n const invocationCid = runtime.lastInvocationCid;\n if (!invocationCid) {\n return { status: 'unverified', reason: 'Completed without an invocation record on a UCAN-enforced flow.' };\n }\n if (!getInvocation) {\n return { status: 'unverified', reason: 'No invocation store available to verify the completion.' };\n }\n const invocation = getInvocation(invocationCid);\n if (!invocation) {\n return { status: 'unverified', reason: `Invocation ${invocationCid} not found in the invocation store.` };\n }\n if (invocation.result !== 'success') {\n return { status: 'unverified', reason: 'Completion references a failed invocation.' };\n }\n if (invocation.blockId && invocation.blockId !== blockId) {\n return { status: 'unverified', reason: 'Completion references an invocation for a different block.' };\n }\n\n return { status: 'verified' };\n}\n\nexport function isVerifiedCompletion(params: VerifyCompletionParams): boolean {\n return verifyCompletion(params).status === 'verified';\n}\n","import type { Map as YMap } from 'yjs';\nimport type { StoredDelegation } from '../types/ucan';\n\nconst ROOT_DELEGATION_KEY = '__root__';\nconst STORE_VERSION_KEY = '__version__';\nconst CURRENT_VERSION = 2;\n\n/**\n * Stored entry in Y.Map\n */\ninterface StoredEntry {\n v: number;\n data: StoredDelegation;\n}\n\n/**\n * UCAN Delegation Store — stores CAR-serialized delegations\n */\nexport interface UcanDelegationStore {\n // Core operations\n get: (cid: string) => StoredDelegation | null;\n set: (delegation: StoredDelegation) => void;\n remove: (cid: string) => void;\n has: (cid: string) => boolean;\n\n // Root management\n getRoot: () => StoredDelegation | null;\n setRootCid: (cid: string) => void;\n getRootCid: () => string | null;\n\n // Query operations\n getAll: () => StoredDelegation[];\n getByAudience: (audienceDid: string) => StoredDelegation[];\n getByIssuer: (issuerDid: string) => StoredDelegation[];\n findByCapability: (can: string, withUri: string) => StoredDelegation[];\n}\n\nconst isValidEntry = (value: unknown): value is StoredEntry => {\n if (!value || typeof value !== 'object') return false;\n const entry = value as StoredEntry;\n return entry.v === CURRENT_VERSION && entry.data !== undefined;\n};\n\nconst isReservedKey = (key: string): boolean => key === ROOT_DELEGATION_KEY || key === STORE_VERSION_KEY;\n\n/**\n * Create a UCAN delegation store backed by Y.Map\n */\nexport const createUcanDelegationStore = (yMap: YMap<unknown>): UcanDelegationStore => {\n const get = (cid: string): StoredDelegation | null => {\n if (isReservedKey(cid)) return null;\n const raw = yMap.get(cid);\n if (!raw) return null;\n if (isValidEntry(raw)) return raw.data;\n return null;\n };\n\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = { v: CURRENT_VERSION, data: delegation };\n yMap.set(delegation.cid, entry);\n };\n\n const remove = (cid: string): void => {\n yMap.delete(cid);\n };\n\n const has = (cid: string): boolean => {\n return yMap.has(cid) && !isReservedKey(cid);\n };\n\n const getRoot = (): StoredDelegation | null => {\n const rootCid = yMap.get(ROOT_DELEGATION_KEY) as string | undefined;\n if (!rootCid) return null;\n return get(rootCid);\n };\n\n const setRootCid = (cid: string): void => {\n yMap.set(ROOT_DELEGATION_KEY, cid);\n };\n\n const getRootCid = (): string | null => {\n return (yMap.get(ROOT_DELEGATION_KEY) as string) || null;\n };\n\n const getAll = (): StoredDelegation[] => {\n const delegations: StoredDelegation[] = [];\n yMap.forEach((value, key) => {\n if (isReservedKey(key)) return;\n if (isValidEntry(value)) {\n delegations.push(value.data);\n }\n });\n return delegations;\n };\n\n const getByAudience = (audienceDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.audienceDid === audienceDid);\n };\n\n const getByIssuer = (issuerDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.issuerDid === issuerDid);\n };\n\n const findByCapability = (can: string, withUri: string): StoredDelegation[] => {\n return getAll().filter((d) =>\n d.capabilities.some((c) => {\n if (c.can === can && c.with === withUri) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (withUri.startsWith(prefix)) return true;\n }\n return false;\n })\n );\n };\n\n return {\n get,\n set,\n remove,\n has,\n getRoot,\n setRootCid,\n getRootCid,\n getAll,\n getByAudience,\n getByIssuer,\n findByCapability,\n };\n};\n\n/**\n * Create an in-memory UCAN delegation store (for testing)\n */\nexport const createMemoryUcanDelegationStore = (): UcanDelegationStore => {\n const store = new Map<string, unknown>();\n\n const get = (cid: string): StoredDelegation | null => {\n if (isReservedKey(cid)) return null;\n const raw = store.get(cid);\n if (!raw) return null;\n if (isValidEntry(raw)) return raw.data;\n return null;\n };\n\n const set = (delegation: StoredDelegation): void => {\n const entry: StoredEntry = { v: CURRENT_VERSION, data: delegation };\n store.set(delegation.cid, entry);\n };\n\n const remove = (cid: string): void => {\n store.delete(cid);\n };\n\n const has = (cid: string): boolean => {\n return store.has(cid) && !isReservedKey(cid);\n };\n\n const getRoot = (): StoredDelegation | null => {\n const rootCid = store.get(ROOT_DELEGATION_KEY) as string | undefined;\n if (!rootCid) return null;\n return get(rootCid);\n };\n\n const setRootCid = (cid: string): void => {\n store.set(ROOT_DELEGATION_KEY, cid);\n };\n\n const getRootCid = (): string | null => {\n return (store.get(ROOT_DELEGATION_KEY) as string) || null;\n };\n\n const getAll = (): StoredDelegation[] => {\n const delegations: StoredDelegation[] = [];\n store.forEach((value, key) => {\n if (isReservedKey(key)) return;\n if (isValidEntry(value)) {\n delegations.push(value.data);\n }\n });\n return delegations;\n };\n\n const getByAudience = (audienceDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.audienceDid === audienceDid);\n };\n\n const getByIssuer = (issuerDid: string): StoredDelegation[] => {\n return getAll().filter((d) => d.issuerDid === issuerDid);\n };\n\n const findByCapability = (can: string, withUri: string): StoredDelegation[] => {\n return getAll().filter((d) =>\n d.capabilities.some((c) => {\n if (c.can === can && c.with === withUri) return true;\n if (c.can === '*' || c.can === 'flow/*') return true;\n if (c.can.endsWith('/*')) {\n const prefix = c.can.slice(0, -1);\n if (can.startsWith(prefix)) return true;\n }\n if (c.with === '*') return true;\n if (c.with.endsWith('*')) {\n const prefix = c.with.slice(0, -1);\n if (withUri.startsWith(prefix)) return true;\n }\n return false;\n })\n );\n };\n\n return {\n get,\n set,\n remove,\n has,\n getRoot,\n setRootCid,\n getRootCid,\n getAll,\n getByAudience,\n getByIssuer,\n findByCapability,\n };\n};\n","import type { Map as YMap } from 'yjs';\nimport type { StoredInvocation } from '../types/ucan';\n\n/**\n * Invocation Store for storing and querying invocations\n *\n * Invocations are stored for:\n * - Audit trail: Cryptographic proof of who did what, when, with what authority\n * - Replay protection: Prevent same invocation being used twice\n * - Dispute resolution: Evidence if actions are contested\n * - Blockchain submission: Submit proofs to chain for immutable record\n * - Analytics: Understand flow execution patterns\n */\nexport interface InvocationStore {\n // Core operations\n add: (invocation: StoredInvocation) => void;\n get: (cid: string) => StoredInvocation | null;\n remove: (cid: string) => void;\n\n // Query operations\n getAll: () => StoredInvocation[];\n getByInvoker: (invokerDid: string) => StoredInvocation[];\n getByFlow: (flowId: string) => StoredInvocation[];\n getByBlock: (flowId: string, blockId: string) => StoredInvocation[];\n getByCapability: (can: string, withUri: string) => StoredInvocation[];\n\n // Replay protection\n hasBeenInvoked: (cid: string) => boolean;\n\n // Audit queries\n getInDateRange: (startMs: number, endMs: number) => StoredInvocation[];\n getSuccessful: () => StoredInvocation[];\n getFailures: () => StoredInvocation[];\n\n // Blockchain submission tracking\n getPendingSubmission: () => StoredInvocation[];\n markSubmitted: (cid: string, transactionHash: string) => void;\n\n // Statistics\n getCount: () => number;\n getCountByResult: () => { success: number; failure: number };\n}\n\n/**\n * Create an invocation store backed by Y.Map\n */\nexport const createInvocationStore = (yMap: YMap<unknown>): InvocationStore => {\n /**\n * Add an invocation to the store\n */\n const add = (invocation: StoredInvocation): void => {\n yMap.set(invocation.cid, invocation);\n };\n\n /**\n * Get an invocation by CID\n */\n const get = (cid: string): StoredInvocation | null => {\n const raw = yMap.get(cid);\n if (!raw || typeof raw !== 'object') return null;\n return raw as StoredInvocation;\n };\n\n /**\n * Remove an invocation (use with caution - typically invocations should be immutable)\n */\n const remove = (cid: string): void => {\n yMap.delete(cid);\n };\n\n /**\n * Get all invocations\n */\n const getAll = (): StoredInvocation[] => {\n const invocations: StoredInvocation[] = [];\n yMap.forEach((value) => {\n if (value && typeof value === 'object' && 'cid' in value) {\n invocations.push(value as StoredInvocation);\n }\n });\n // Sort by executedAt descending (most recent first)\n return invocations.sort((a, b) => b.executedAt - a.executedAt);\n };\n\n /**\n * Get invocations by invoker DID\n */\n const getByInvoker = (invokerDid: string): StoredInvocation[] => {\n return getAll().filter((i) => i.invokerDid === invokerDid);\n };\n\n /**\n * Get invocations for a specific flow\n */\n const getByFlow = (flowId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId);\n };\n\n /**\n * Get invocations for a specific block in a flow\n */\n const getByBlock = (flowId: string, blockId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);\n };\n\n /**\n * Get invocations that used a specific capability\n */\n const getByCapability = (can: string, withUri: string): StoredInvocation[] => {\n return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);\n };\n\n /**\n * Check if an invocation has already been used (replay protection)\n */\n const hasBeenInvoked = (cid: string): boolean => {\n return yMap.has(cid);\n };\n\n /**\n * Get invocations in a date range\n */\n const getInDateRange = (startMs: number, endMs: number): StoredInvocation[] => {\n return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);\n };\n\n /**\n * Get successful invocations\n */\n const getSuccessful = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success');\n };\n\n /**\n * Get failed invocations\n */\n const getFailures = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'failure');\n };\n\n /**\n * Get invocations pending blockchain submission\n */\n const getPendingSubmission = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success' && !i.transactionHash);\n };\n\n /**\n * Mark an invocation as submitted to blockchain\n */\n const markSubmitted = (cid: string, transactionHash: string): void => {\n const invocation = get(cid);\n if (invocation) {\n const updated: StoredInvocation = {\n ...invocation,\n transactionHash,\n };\n yMap.set(cid, updated);\n }\n };\n\n /**\n * Get total count of invocations\n */\n const getCount = (): number => {\n return getAll().length;\n };\n\n /**\n * Get count by result type\n */\n const getCountByResult = (): { success: number; failure: number } => {\n const all = getAll();\n return {\n success: all.filter((i) => i.result === 'success').length,\n failure: all.filter((i) => i.result === 'failure').length,\n };\n };\n\n return {\n add,\n get,\n remove,\n getAll,\n getByInvoker,\n getByFlow,\n getByBlock,\n getByCapability,\n hasBeenInvoked,\n getInDateRange,\n getSuccessful,\n getFailures,\n getPendingSubmission,\n markSubmitted,\n getCount,\n getCountByResult,\n };\n};\n\n/**\n * Create an in-memory invocation store (for testing)\n */\nexport const createMemoryInvocationStore = (): InvocationStore => {\n const store = new Map<string, StoredInvocation>();\n\n const add = (invocation: StoredInvocation): void => {\n store.set(invocation.cid, invocation);\n };\n\n const get = (cid: string): StoredInvocation | null => {\n return store.get(cid) || null;\n };\n\n const remove = (cid: string): void => {\n store.delete(cid);\n };\n\n const getAll = (): StoredInvocation[] => {\n const invocations = Array.from(store.values());\n return invocations.sort((a, b) => b.executedAt - a.executedAt);\n };\n\n const getByInvoker = (invokerDid: string): StoredInvocation[] => {\n return getAll().filter((i) => i.invokerDid === invokerDid);\n };\n\n const getByFlow = (flowId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId);\n };\n\n const getByBlock = (flowId: string, blockId: string): StoredInvocation[] => {\n return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);\n };\n\n const getByCapability = (can: string, withUri: string): StoredInvocation[] => {\n return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);\n };\n\n const hasBeenInvoked = (cid: string): boolean => {\n return store.has(cid);\n };\n\n const getInDateRange = (startMs: number, endMs: number): StoredInvocation[] => {\n return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);\n };\n\n const getSuccessful = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success');\n };\n\n const getFailures = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'failure');\n };\n\n const getPendingSubmission = (): StoredInvocation[] => {\n return getAll().filter((i) => i.result === 'success' && !i.transactionHash);\n };\n\n const markSubmitted = (cid: string, transactionHash: string): void => {\n const invocation = get(cid);\n if (invocation) {\n store.set(cid, { ...invocation, transactionHash });\n }\n };\n\n const getCount = (): number => {\n return store.size;\n };\n\n const getCountByResult = (): { success: number; failure: number } => {\n const all = getAll();\n return {\n success: all.filter((i) => i.result === 'success').length,\n failure: all.filter((i) => i.result === 'failure').length,\n };\n };\n\n return {\n add,\n get,\n remove,\n getAll,\n getByInvoker,\n getByFlow,\n getByBlock,\n getByCapability,\n hasBeenInvoked,\n getInDateRange,\n getSuccessful,\n getFailures,\n getPendingSubmission,\n markSubmitted,\n getCount,\n getCountByResult,\n };\n};\n","import * as Y from 'yjs';\nimport { getAction, type ActionHandlers, type ActionResult, type ActionServices } from '../actionRegistry';\nimport type { InvocationStore } from '../invocationStore';\nimport { resolveRuntimeRefs, type TriggerResolutionContext } from '../flowCompiler/resolveRefs';\nimport type { UcanService } from '../../services/ucanService';\nimport type { FlowNodeRuntimeState, NodeState } from '../../types/authorization';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport { createRuntimeStateManager, createYDocRuntimeManager } from './runtime';\nimport { executeNode, type ExecutionOutcome, type NodeActionResult } from './executor';\nimport { reconcilePendingInvocations } from './reconcile';\nimport { appendRunRecord, readPendingInvocations, removePendingInvocation, type PendingInvocation, type RunRecordDetails } from './triggers';\nimport { buildFlowNodeFromBlock } from './utils';\nimport { normalizeActionReadBackMetadata } from './readBackReconciler';\nimport { PROOF_MISSING_CODE, validateActionProof } from './proof';\nimport { warnOnce } from '../warnOnce';\nimport type { IxoEditorType } from '../../types/editor';\n\nexport type ActionBlockLike = {\n id?: string;\n props?: Record<string, unknown>;\n};\n\ntype EditorOrYDoc = IxoEditorType | Y.Doc;\n\nexport interface BuildActionRunInputsParams {\n editorOrYDoc?: EditorOrYDoc | null;\n block?: ActionBlockLike | null;\n blockId?: string;\n document?: ActionBlockLike[];\n runtime?: FlowRuntimeStateManager;\n savedInputs?: unknown;\n runtimeInputs?: Record<string, unknown>;\n pendingInvocationId?: string;\n}\n\nexport interface BuildActionRunInputsResult {\n inputs: Record<string, unknown>;\n savedInputs: Record<string, unknown>;\n mergedInputs: Record<string, unknown>;\n pendingInvocation?: PendingInvocation;\n triggerContext?: TriggerResolutionContext;\n}\n\nexport type ActionExecutionCompletionState = 'completed' | 'failed' | 'awaiting_readback' | 'needs_verification';\n\nexport interface ExecuteActionBlockParams extends BuildActionRunInputsParams {\n actorDid: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n ucanService?: UcanService;\n invocationStore?: InvocationStore;\n services?: ActionServices;\n handlers?: ActionHandlers;\n pin?: string;\n now?: () => number;\n flowUri?: string;\n flowId?: string;\n flowOwnerDid?: string;\n schemaVersion?: string;\n}\n\nexport interface ExecuteActionBlockResult {\n success: boolean;\n stage: ExecutionOutcome['stage'] | 'input' | 'action_lookup';\n blockId: string;\n actionType?: string;\n output?: Record<string, unknown>;\n events: NonNullable<ActionResult['events']>;\n error?: string;\n invocationCid?: string;\n capabilityId?: string;\n runId?: string;\n pendingInvocationRemoved?: boolean;\n completionState: ActionExecutionCompletionState;\n pendingInvocation?: PendingInvocation;\n}\n\nfunction isYDoc(value: unknown): value is Y.Doc {\n return value instanceof Y.Doc;\n}\n\nfunction getYDoc(editorOrYDoc?: EditorOrYDoc | null): Y.Doc | undefined {\n if (!editorOrYDoc) return undefined;\n if (isYDoc(editorOrYDoc)) return editorOrYDoc;\n return (editorOrYDoc as { _yDoc?: Y.Doc })._yDoc;\n}\n\nfunction parseInputs(value: unknown): Record<string, unknown> {\n if (value == null || value === '') return {};\n if (typeof value === 'object' && !Array.isArray(value)) return { ...(value as Record<string, unknown>) };\n if (typeof value !== 'string') return {};\n\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n } catch {\n warnOnce(`executor-inputs-parse:${value}`, `[flow-config] saved block inputs are not valid JSON; treated as empty`);\n return {};\n }\n}\n\nfunction getRuntime(editorOrYDoc?: EditorOrYDoc | null, runtime?: FlowRuntimeStateManager): FlowRuntimeStateManager {\n if (runtime) return runtime;\n const yDoc = getYDoc(editorOrYDoc);\n if (yDoc) return createYDocRuntimeManager(yDoc);\n return createRuntimeStateManager(!isYDoc(editorOrYDoc) ? editorOrYDoc : undefined);\n}\n\nfunction getEditor(editorOrYDoc?: EditorOrYDoc | null): IxoEditorType | undefined {\n return editorOrYDoc && !isYDoc(editorOrYDoc) ? editorOrYDoc : undefined;\n}\n\nfunction findBlock(params: Pick<ExecuteActionBlockParams, 'block' | 'blockId' | 'editorOrYDoc' | 'document'>): ActionBlockLike | undefined {\n if (params.block) return params.block;\n const blockId = params.blockId;\n if (!blockId) return undefined;\n const editor = getEditor(params.editorOrYDoc);\n return (params.document || editor?.document || []).find((block: ActionBlockLike) => block?.id === blockId) as ActionBlockLike | undefined;\n}\n\nfunction getFlowMetadata(editor?: IxoEditorType): { flowId: string; flowUri: string; flowOwnerDid: string; schemaVersion: string } {\n const metadata = editor?.getFlowMetadata?.();\n const flowId = metadata?.doc_id || '';\n return {\n flowId,\n flowUri: flowId ? `ixo:flow:${flowId}` : '',\n flowOwnerDid: editor?.getFlowOwnerDid?.() || metadata?.flowOwnerDid || '',\n schemaVersion: metadata?.schema_version || '0.3',\n };\n}\n\nfunction getPendingInvocation(yDoc: Y.Doc | undefined, blockId: string | undefined, pendingInvocationId: string | undefined): PendingInvocation | undefined {\n if (!pendingInvocationId) return undefined;\n if (!yDoc) {\n throw new Error(`Cannot load pending invocation \"${pendingInvocationId}\" without a Y.Doc`);\n }\n if (!blockId) {\n throw new Error(`Cannot load pending invocation \"${pendingInvocationId}\" without a block id`);\n }\n\n const pending = readPendingInvocations(yDoc, blockId).find((invocation) => invocation.id === pendingInvocationId);\n if (!pending) {\n throw new Error(`Pending invocation \"${pendingInvocationId}\" was not found for block \"${blockId}\"`);\n }\n return pending;\n}\n\nfunction getNodeOutput(runtime: FlowRuntimeStateManager, nodeId: string): Record<string, unknown> | undefined {\n const state = runtime.get(nodeId);\n const output = state.output;\n return output && typeof output === 'object' && !Array.isArray(output) ? output : undefined;\n}\n\nexport function buildActionRunInputs(params: BuildActionRunInputsParams): BuildActionRunInputsResult {\n const blockId = params.blockId || params.block?.id;\n const yDoc = getYDoc(params.editorOrYDoc);\n const runtime = getRuntime(params.editorOrYDoc, params.runtime);\n const savedInputs = parseInputs(params.savedInputs ?? params.block?.props?.inputs);\n const pendingInvocation = getPendingInvocation(yDoc, blockId, params.pendingInvocationId);\n\n const triggerContext = pendingInvocation\n ? {\n payload: pendingInvocation.payload || {},\n refSnapshots: pendingInvocation.refSnapshots || {},\n }\n : undefined;\n\n const mergedInputs = {\n ...savedInputs,\n ...(pendingInvocation?.payload || {}),\n ...(pendingInvocation?.refSnapshots || {}),\n ...(params.runtimeInputs || {}),\n };\n\n return {\n inputs: resolveRuntimeRefs(mergedInputs, (nodeId) => getNodeOutput(runtime, nodeId), triggerContext),\n savedInputs,\n mergedInputs,\n pendingInvocation,\n triggerContext,\n };\n}\n\nfunction buildFailureResult(params: {\n blockId: string;\n actionType?: string;\n stage: ExecuteActionBlockResult['stage'];\n error: string;\n pendingInvocation?: PendingInvocation;\n}): ExecuteActionBlockResult {\n return {\n success: false,\n stage: params.stage,\n blockId: params.blockId,\n actionType: params.actionType,\n events: [],\n error: params.error,\n completionState: 'failed',\n pendingInvocation: params.pendingInvocation,\n };\n}\n\nfunction updateRuntimeFailure(runtime: FlowRuntimeStateManager, blockId: string, message: string, now: () => number): void {\n runtime.update(blockId, {\n state: 'failed',\n error: { message, at: now() },\n } as Partial<FlowNodeRuntimeState>);\n}\n\nfunction makeRunId(now: () => number): string {\n return `run-${now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction getReconcileEditor(params: ExecuteActionBlockParams, yDoc: Y.Doc | undefined, editor: IxoEditorType | undefined): IxoEditorType | undefined {\n if (editor) return editor;\n if (!yDoc || !params.document) return undefined;\n return {\n _yDoc: yDoc,\n _yRuntime: yDoc.getMap('runtime'),\n document: params.document,\n } as IxoEditorType;\n}\n\nfunction persistEvents(params: {\n yDoc?: Y.Doc;\n editor?: IxoEditorType;\n blockId: string;\n actorDid: string;\n output: Record<string, unknown>;\n events: NonNullable<ActionResult['events']>;\n invocationCid?: string;\n capabilityId?: string;\n pendingInvocation?: PendingInvocation;\n startedAt: number;\n completedAt: number;\n now: () => number;\n}): string | undefined {\n if (!params.yDoc || params.events.length === 0) return undefined;\n\n const runId = makeRunId(params.now);\n const details: RunRecordDetails = {\n runId,\n output: params.output,\n events: params.events,\n startedAt: new Date(params.startedAt).toISOString(),\n completedAt: new Date(params.completedAt).toISOString(),\n actorDid: params.actorDid,\n invocationCid: params.invocationCid,\n capabilityId: params.capabilityId,\n };\n\n if (params.pendingInvocation) {\n details.fromPendingInvocationId = params.pendingInvocation.id;\n details.triggeredBy = {\n sourceBlockId: params.pendingInvocation.triggeringBlockId,\n eventName: params.pendingInvocation.eventName,\n };\n details.sourceRunId = params.pendingInvocation.sourceRunId;\n }\n\n appendRunRecord(params.yDoc, params.blockId, details, params.actorDid);\n if (params.editor) {\n reconcilePendingInvocations(params.editor);\n }\n return runId;\n}\n\nfunction cleanupCompletedPendingInvocation(yDoc: Y.Doc | undefined, blockId: string, pendingInvocation: PendingInvocation | undefined): boolean {\n if (!yDoc || !pendingInvocation) return false;\n return removePendingInvocation(yDoc, blockId, pendingInvocation.id);\n}\n\nexport async function executeActionBlock(params: ExecuteActionBlockParams): Promise<ExecuteActionBlockResult> {\n const block = findBlock(params);\n const blockId = params.blockId || block?.id;\n const editor = getEditor(params.editorOrYDoc);\n const yDoc = getYDoc(params.editorOrYDoc);\n const runtime = getRuntime(params.editorOrYDoc, params.runtime);\n const now = params.now || Date.now;\n\n if (!block || !blockId) {\n return buildFailureResult({\n blockId: blockId || '',\n stage: 'input',\n error: blockId ? `Block \"${blockId}\" was not found` : 'executeActionBlock requires a blockId or block',\n });\n }\n\n const actionType = typeof block.props?.actionType === 'string' ? block.props.actionType : undefined;\n if (!actionType) {\n updateRuntimeFailure(runtime, blockId, 'Action block is missing props.actionType', now);\n return buildFailureResult({\n blockId,\n stage: 'input',\n error: 'Action block is missing props.actionType',\n });\n }\n\n const action = getAction(actionType);\n if (!action) {\n const message = `No registered action found for ${actionType}`;\n updateRuntimeFailure(runtime, blockId, message, now);\n return buildFailureResult({ blockId, actionType, stage: 'action_lookup', error: message });\n }\n\n let inputBuild: BuildActionRunInputsResult;\n try {\n inputBuild = buildActionRunInputs({ ...params, block, blockId, runtime });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to build action inputs';\n updateRuntimeFailure(runtime, blockId, message, now);\n return buildFailureResult({ blockId, actionType, stage: 'input', error: message });\n }\n\n const flowNode = buildFlowNodeFromBlock(block);\n const metadata = getFlowMetadata(editor);\n const flowId = params.flowId || metadata.flowId || blockId;\n const flowUri = params.flowUri || metadata.flowUri || `ixo:flow:${flowId}`;\n const flowOwnerDid = params.flowOwnerDid || metadata.flowOwnerDid;\n const schemaVersion = params.schemaVersion || metadata.schemaVersion;\n const events: NonNullable<ActionResult['events']> = [];\n let completionState: ActionExecutionCompletionState = 'completed';\n let readBack: Record<string, unknown> | undefined;\n let rawReadBack: Record<string, unknown> | undefined;\n let requestedAwaitingReadBack = false;\n let proofFailureReason: string | null = null;\n let proofFailureOutput: Record<string, unknown> | undefined;\n const startedAt = now();\n\n runtime.update(blockId, {\n state: 'running',\n output: undefined,\n error: undefined,\n executedByDid: params.actorDid,\n } as Partial<FlowNodeRuntimeState>);\n\n const outcome = await executeNode({\n node: flowNode,\n actorDid: params.actorDid,\n actorType: params.actorType,\n entityRoomId: params.entityRoomId,\n context: {\n runtime,\n ucanService: params.ucanService || editor?.getUcanService?.() || undefined,\n invocationStore: params.invocationStore || editor?._invocationStore,\n flowUri,\n flowId,\n flowOwnerDid,\n schemaVersion,\n now,\n },\n action: async (): Promise<NodeActionResult> => {\n const result = await action.run(inputBuild.inputs, {\n actorDid: params.actorDid,\n flowId,\n flowUri,\n nodeId: blockId,\n flowNode,\n runtime,\n services: params.services || {},\n handlers: params.handlers,\n editor,\n pendingInvocation: inputBuild.pendingInvocation,\n });\n if (result.events?.length) events.push(...result.events);\n if (result.completion?.state === 'awaiting_readback') {\n requestedAwaitingReadBack = true;\n rawReadBack = result.completion.readBack;\n } else {\n // Proof guard runs inside the action callback so that a proofless\n // success is recorded as a FAILED invocation by executeNode's catch\n // path — never as a success invocation followed by a failed runtime.\n const proofCheck = validateActionProof(action, (result.output as Record<string, unknown>) || {});\n if (!proofCheck.valid) {\n proofFailureReason = proofCheck.reason || 'Action returned success without proof of execution.';\n // Keep the handler payload: for a side-effecting action this is the\n // only evidence the effect may have happened (H1). It is retained on\n // runtime.output below instead of being discarded.\n proofFailureOutput = (result.output as Record<string, unknown>) || {};\n throw new Error(proofFailureReason);\n }\n }\n return {\n payload: result.output,\n submittedByDid: params.actorDid || undefined,\n };\n },\n pin: params.pin || '',\n });\n\n if (!outcome.success) {\n const message = outcome.error || 'Action execution failed';\n if (proofFailureReason) {\n // A side-effecting action that ran but couldn't prove it did is NOT a\n // clean failure: the effect may have happened (e.g. an on-chain tx that\n // landed under a differently-named field), so it must never be silently\n // auto-retried — that would double-execute. Route it to the\n // `needs_verification` dead-end and RETAIN the handler payload as\n // evidence for the human/automated verifier. A non-side-effecting proof\n // failure stays `failed` — re-running it is harmless. See H1.\n const proofFailureState: NodeState = action.sideEffect ? 'needs_verification' : 'failed';\n runtime.update(blockId, {\n state: proofFailureState,\n output: proofFailureOutput,\n error: { message, code: PROOF_MISSING_CODE, at: now() },\n } as Partial<FlowNodeRuntimeState>);\n return {\n ...buildFailureResult({\n blockId,\n actionType,\n stage: outcome.stage,\n error: message,\n pendingInvocation: inputBuild.pendingInvocation,\n }),\n completionState: proofFailureState === 'needs_verification' ? 'needs_verification' : 'failed',\n output: proofFailureOutput,\n invocationCid: outcome.invocationCid,\n capabilityId: outcome.capabilityId,\n };\n }\n updateRuntimeFailure(runtime, blockId, message, now);\n return {\n ...buildFailureResult({\n blockId,\n actionType,\n stage: outcome.stage,\n error: message,\n pendingInvocation: inputBuild.pendingInvocation,\n }),\n invocationCid: outcome.invocationCid,\n capabilityId: outcome.capabilityId,\n };\n }\n\n const output = (outcome.result?.payload || {}) as Record<string, unknown>;\n const completedAt = now();\n if (requestedAwaitingReadBack) {\n completionState = 'awaiting_readback';\n readBack = normalizeActionReadBackMetadata({\n readBack: rawReadBack,\n blockId,\n actionType,\n actorDid: params.actorDid,\n invocationCid: outcome.invocationCid,\n capabilityId: outcome.capabilityId,\n requestedAt: startedAt,\n pendingInvocation: inputBuild.pendingInvocation,\n });\n }\n runtime.update(blockId, {\n state: completionState,\n output,\n executedByDid: params.actorDid,\n executedAt: completedAt,\n lastInvocationCid: outcome.invocationCid || outcome.capabilityId,\n readBack,\n } as Partial<FlowNodeRuntimeState>);\n const runId = persistEvents({\n yDoc,\n editor: getReconcileEditor(params, yDoc, editor),\n blockId,\n actorDid: params.actorDid,\n output,\n events,\n invocationCid: outcome.invocationCid,\n capabilityId: outcome.capabilityId,\n pendingInvocation: inputBuild.pendingInvocation,\n startedAt,\n completedAt,\n now,\n });\n const pendingInvocationRemoved = completionState === 'completed' ? cleanupCompletedPendingInvocation(yDoc, blockId, inputBuild.pendingInvocation) : false;\n\n return {\n success: true,\n stage: outcome.stage,\n blockId,\n actionType,\n output,\n events,\n invocationCid: outcome.invocationCid,\n capabilityId: outcome.capabilityId,\n runId,\n pendingInvocationRemoved,\n completionState,\n pendingInvocation: inputBuild.pendingInvocation,\n };\n}\n","import * as Y from 'yjs';\nimport { getAction, type ActionResult } from '../actionRegistry';\nimport { PROOF_MISSING_CODE, validateActionProof } from './proof';\nimport type { ActionReadBackMetadata, FlowNodeRuntimeState, ReadBackTerminalState } from '../../types/authorization';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { FlowRuntimeStateManager } from './runtime';\nimport { createRuntimeStateManager, createYDocRuntimeManager } from './runtime';\nimport { reconcilePendingInvocations } from './reconcile';\nimport { appendRunRecord, removePendingInvocation, type PendingInvocation, type RunRecordDetails } from './triggers';\n\ntype EditorOrYDoc = IxoEditorType | Y.Doc;\n\nexport interface NormalizeReadBackMetadataParams {\n readBack?: Record<string, unknown>;\n blockId: string;\n actionType: string;\n actorDid: string;\n invocationCid?: string;\n capabilityId?: string;\n requestedAt: number;\n pendingInvocation?: PendingInvocation;\n}\n\nexport interface ActionReadBackResolution {\n state: ReadBackTerminalState;\n output?: Record<string, unknown>;\n events?: NonNullable<ActionResult['events']>;\n readBack?: Record<string, unknown>;\n error?: string | { message: string; code?: string };\n}\n\nexport interface ActionReadBackResolverInput {\n blockId: string;\n runtime: FlowNodeRuntimeState;\n output: Record<string, unknown>;\n readBack: ActionReadBackMetadata;\n}\n\nexport type ActionReadBackResolver = (input: ActionReadBackResolverInput) => ActionReadBackResolution | Promise<ActionReadBackResolution>;\n\nexport interface ReconcileActionReadBackParams {\n editorOrYDoc?: EditorOrYDoc | null;\n blockId: string;\n actorDid?: string;\n runtime?: FlowRuntimeStateManager;\n document?: Array<{ id?: string; props?: Record<string, unknown> }>;\n resolver?: ActionReadBackResolver;\n resolvers?: Record<string, ActionReadBackResolver>;\n now?: () => number;\n}\n\nexport interface ReconcileActionReadBackResult {\n success: boolean;\n blockId: string;\n state: ReadBackTerminalState;\n output?: Record<string, unknown>;\n events: NonNullable<ActionResult['events']>;\n error?: string;\n runId?: string;\n pendingInvocationRemoved: boolean;\n readBack?: ActionReadBackMetadata;\n}\n\nfunction isYDoc(value: unknown): value is Y.Doc {\n return value instanceof Y.Doc;\n}\n\nfunction getYDoc(editorOrYDoc?: EditorOrYDoc | null): Y.Doc | undefined {\n if (!editorOrYDoc) return undefined;\n if (isYDoc(editorOrYDoc)) return editorOrYDoc;\n return (editorOrYDoc as { _yDoc?: Y.Doc })._yDoc;\n}\n\nfunction getEditor(editorOrYDoc?: EditorOrYDoc | null): IxoEditorType | undefined {\n return editorOrYDoc && !isYDoc(editorOrYDoc) ? editorOrYDoc : undefined;\n}\n\nfunction getRuntime(editorOrYDoc?: EditorOrYDoc | null, runtime?: FlowRuntimeStateManager): FlowRuntimeStateManager {\n if (runtime) return runtime;\n const yDoc = getYDoc(editorOrYDoc);\n if (yDoc) return createYDocRuntimeManager(yDoc);\n return createRuntimeStateManager(!isYDoc(editorOrYDoc) ? editorOrYDoc : undefined);\n}\n\nfunction getReconcileEditor(params: ReconcileActionReadBackParams, yDoc: Y.Doc | undefined, editor: IxoEditorType | undefined): IxoEditorType | undefined {\n if (editor) return editor;\n if (!yDoc || !params.document) return undefined;\n return {\n _yDoc: yDoc,\n _yRuntime: yDoc.getMap('runtime'),\n document: params.document,\n } as IxoEditorType;\n}\n\nfunction makeRunId(now: () => number): string {\n return `readback-${now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction asOutput(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? { ...(value as Record<string, unknown>) } : {};\n}\n\nfunction errorRecord(error: string | { message: string; code?: string } | undefined): { message: string; code?: string } | undefined {\n if (!error) return undefined;\n return typeof error === 'string' ? { message: error } : { message: error.message, code: error.code };\n}\n\nexport function normalizeActionReadBackMetadata(params: NormalizeReadBackMetadataParams): ActionReadBackMetadata {\n const base = params.readBack && typeof params.readBack === 'object' && !Array.isArray(params.readBack) ? { ...params.readBack } : {};\n const kind = typeof base.kind === 'string' && base.kind.trim() ? base.kind.trim() : params.actionType;\n\n const normalized: ActionReadBackMetadata = {\n ...base,\n kind,\n status: 'pending',\n requestedAt: typeof base.requestedAt === 'string' ? base.requestedAt : new Date(params.requestedAt).toISOString(),\n blockId: params.blockId,\n actionType: params.actionType,\n actorDid: params.actorDid,\n invocationCid: params.invocationCid,\n capabilityId: params.capabilityId,\n };\n\n if (params.pendingInvocation) {\n normalized.pendingInvocation = {\n id: params.pendingInvocation.id,\n triggeringBlockId: params.pendingInvocation.triggeringBlockId,\n eventName: params.pendingInvocation.eventName,\n sourceRunId: params.pendingInvocation.sourceRunId,\n };\n }\n\n return normalized;\n}\n\nfunction writeReconciliationRunRecord(params: {\n yDoc?: Y.Doc;\n editor?: IxoEditorType;\n blockId: string;\n actorDid: string;\n output: Record<string, unknown>;\n events: NonNullable<ActionResult['events']>;\n readBack: ActionReadBackMetadata;\n error?: { message: string; code?: string };\n now: () => number;\n}): string | undefined {\n if (!params.yDoc) return undefined;\n\n const completedAt = params.now();\n const runId = makeRunId(params.now);\n const pendingInvocation = params.readBack.pendingInvocation;\n const details: RunRecordDetails = {\n runId,\n output: params.output,\n events: params.events,\n startedAt: params.readBack.requestedAt || new Date(completedAt).toISOString(),\n completedAt: new Date(completedAt).toISOString(),\n actorDid: params.actorDid,\n invocationCid: params.readBack.invocationCid,\n capabilityId: params.readBack.capabilityId,\n error: params.error,\n readBack: params.readBack,\n reconciled: true,\n };\n\n if (pendingInvocation) {\n details.fromPendingInvocationId = pendingInvocation.id;\n details.triggeredBy = {\n sourceBlockId: pendingInvocation.triggeringBlockId,\n eventName: pendingInvocation.eventName,\n };\n details.sourceRunId = pendingInvocation.sourceRunId;\n }\n\n appendRunRecord(params.yDoc, params.blockId, details, params.actorDid);\n if (params.editor && params.events.length > 0) {\n reconcilePendingInvocations(params.editor);\n }\n return runId;\n}\n\nexport async function reconcileActionReadBack(params: ReconcileActionReadBackParams): Promise<ReconcileActionReadBackResult> {\n const now = params.now || Date.now;\n const yDoc = getYDoc(params.editorOrYDoc);\n const editor = getEditor(params.editorOrYDoc);\n const runtime = getRuntime(params.editorOrYDoc, params.runtime);\n const current = runtime.get(params.blockId);\n const output = asOutput(current.output);\n const readBack = current.readBack;\n\n if (current.state !== 'awaiting_readback' || !readBack?.kind) {\n return {\n success: false,\n blockId: params.blockId,\n state: current.state === 'failed' ? 'failed' : 'pending',\n output,\n events: [],\n error: `Block \"${params.blockId}\" is not awaiting read-back`,\n pendingInvocationRemoved: false,\n readBack,\n };\n }\n\n const resolver = params.resolver || params.resolvers?.[readBack.kind];\n if (!resolver) {\n return {\n success: false,\n blockId: params.blockId,\n state: 'pending',\n output,\n events: [],\n error: `No read-back resolver registered for \"${readBack.kind}\"`,\n pendingInvocationRemoved: false,\n readBack,\n };\n }\n\n const resolution = await resolver({\n blockId: params.blockId,\n runtime: current,\n output,\n readBack,\n });\n const checkedAt = now();\n const checkedIso = new Date(checkedAt).toISOString();\n const nextReadBack: ActionReadBackMetadata = {\n ...readBack,\n ...(resolution.readBack || {}),\n status: resolution.state,\n lastCheckedAt: checkedIso,\n };\n\n if (resolution.state === 'pending') {\n runtime.update(params.blockId, {\n readBack: nextReadBack,\n });\n return {\n success: true,\n blockId: params.blockId,\n state: 'pending',\n output,\n events: resolution.events || [],\n pendingInvocationRemoved: false,\n readBack: nextReadBack,\n };\n }\n\n const events = resolution.events || [];\n const finalOutput = {\n ...output,\n ...(resolution.output || {}),\n };\n const actorDid = params.actorDid || readBack.actorDid || current.executedByDid || 'system:readback';\n\n if (resolution.state === 'failed') {\n const error = errorRecord(resolution.error) || { message: 'External read-back failed' };\n const failedReadBack = {\n ...nextReadBack,\n terminalAt: checkedIso,\n };\n runtime.update(params.blockId, {\n state: 'failed',\n output: finalOutput,\n error: { ...error, at: checkedAt },\n readBack: failedReadBack,\n });\n const runId = writeReconciliationRunRecord({\n yDoc,\n editor: getReconcileEditor(params, yDoc, editor),\n blockId: params.blockId,\n actorDid,\n output: finalOutput,\n events,\n readBack: failedReadBack,\n error,\n now,\n });\n return {\n success: false,\n blockId: params.blockId,\n state: 'failed',\n output: finalOutput,\n events,\n error: error.message,\n runId,\n pendingInvocationRemoved: false,\n readBack: failedReadBack,\n };\n }\n\n // Terminal read-back completion is a `completed` write like any other:\n // the resolver's final output must satisfy the action's proof declaration.\n const readBackActionType = (readBack as { actionType?: string }).actionType || readBack.kind;\n const actionDef = readBackActionType ? getAction(readBackActionType) : undefined;\n if (actionDef) {\n const proofCheck = validateActionProof(actionDef, (finalOutput as Record<string, unknown>) || {});\n if (!proofCheck.valid) {\n const message = proofCheck.reason || 'Read-back resolved completed without proof of execution.';\n const proofFailedReadBack = {\n ...nextReadBack,\n terminalAt: checkedIso,\n };\n // Side-effecting proof failure → `needs_verification`, never a silently\n // retryable `failed` (H1). Payload (finalOutput) is already retained.\n runtime.update(params.blockId, {\n state: actionDef.sideEffect ? 'needs_verification' : 'failed',\n output: finalOutput,\n error: { message, code: PROOF_MISSING_CODE, at: checkedAt },\n readBack: proofFailedReadBack,\n });\n const failedRunId = writeReconciliationRunRecord({\n yDoc,\n editor: getReconcileEditor(params, yDoc, editor),\n blockId: params.blockId,\n actorDid,\n output: finalOutput,\n events,\n readBack: proofFailedReadBack,\n error: { message, code: PROOF_MISSING_CODE },\n now,\n });\n return {\n success: false,\n blockId: params.blockId,\n state: 'failed',\n output: finalOutput,\n events,\n error: message,\n runId: failedRunId,\n pendingInvocationRemoved: false,\n readBack: proofFailedReadBack,\n };\n }\n }\n\n const completedReadBack = {\n ...nextReadBack,\n terminalAt: checkedIso,\n };\n runtime.update(params.blockId, {\n state: 'completed',\n output: finalOutput,\n executedAt: checkedAt,\n error: undefined,\n readBack: completedReadBack,\n });\n const runId = writeReconciliationRunRecord({\n yDoc,\n editor: getReconcileEditor(params, yDoc, editor),\n blockId: params.blockId,\n actorDid,\n output: finalOutput,\n events,\n readBack: completedReadBack,\n now,\n });\n const pendingInvocationRemoved =\n Boolean(yDoc && completedReadBack.pendingInvocation?.id) && removePendingInvocation(yDoc!, params.blockId, completedReadBack.pendingInvocation!.id);\n\n return {\n success: true,\n blockId: params.blockId,\n state: 'completed',\n output: finalOutput,\n events,\n runId,\n pendingInvocationRemoved,\n readBack: completedReadBack,\n };\n}\n","import type * as Y from 'yjs';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport { isRepeatableAction } from '../actionRegistry';\nimport type { CompletionVerification } from './verifiedCompletion';\nimport { readRunRecords } from './triggers';\n\n/**\n * The four top-level phases a block presents to users and planners. This is a\n * DERIVED vocabulary — it is never written to the runtime Y.Map. The stored\n * `NodeState` machine is unchanged; every consumer (badge, flow agent, future\n * dashboards) computes its view through {@link deriveBlockPhase} so the two\n * can never drift, and existing flows need no migration.\n *\n * - `pending` — not actionable yet: nothing has run and no work is queued.\n * - `active` — actionable or in motion: running, awaiting external\n * confirmation, queued invocations to act on, or (for repeatable actions) a\n * standing capability that has fired and remains open.\n * - `complete` — terminal Done. Only one-shot (`cardinality: 'once'`) actions\n * ever reach it; a repeatable action that has fired stays `active`.\n * - `failed` — needs attention. Includes plain failures (safe to retry) and\n * the two states that are deliberately NOT safe to retry:\n * `needs_verification` and unverified completions.\n */\nexport type BlockPhase = 'pending' | 'active' | 'complete' | 'failed';\n\n/**\n * Finer-grained detail preserved from the underlying state machine so UIs can\n * distinguish sub-states without re-deriving them:\n *\n * - `idle` — pending, nothing has run.\n * - `queued` — pending invocations exist for the block.\n * - `running` — executing right now.\n * - `awaiting_readback` — ran; final outcome arrives via read-back\n * reconciliation. Neither pending (it ran) nor complete (not settled).\n * - `standing` — repeatable action with ≥1 completed run; stays\n * active for the flow's life. Progress = `runCount`, not this entry.\n * - `completed` — terminal Done (one-shot actions only).\n * - `cancelled` — deliberately closed; terminal for any cardinality.\n * - `failed` — the run failed; retrying is safe.\n * - `needs_verification` — side effect MAY have happened but proof is\n * missing. Retrying could double-execute; requires human resolution.\n * - `unverified` — a `completed` entry that fails\n * `verifyCompletion` (missing proof / invocation). Treat like\n * `needs_verification`: surface, never silently trust or auto-retry.\n */\nexport type BlockPhaseDetail = 'idle' | 'queued' | 'running' | 'awaiting_readback' | 'standing' | 'completed' | 'cancelled' | 'failed' | 'needs_verification' | 'unverified';\n\nexport interface DerivedBlockState {\n phase: BlockPhase;\n detail: BlockPhaseDetail;\n /** Whether the block's action type is a repeatable ('many') capability. */\n repeatable: boolean;\n /**\n * Successful run count for repeatable blocks, when the caller supplied one\n * (see {@link countSuccessfulRuns}). Undefined when unknown.\n */\n runCount?: number;\n /**\n * Whether re-executing the block is safe. False for `needs_verification`\n * and `unverified` — the side effect may already have happened, so a retry\n * risks double-execution. UIs must not offer a plain retry when false.\n */\n safeToRetry: boolean;\n}\n\nexport interface DeriveBlockPhaseParams {\n runtime: FlowNodeRuntimeState | null | undefined;\n /** The block's action type, used to resolve cardinality from the registry. */\n actionType?: string | null;\n /**\n * Result of `verifyCompletion` for the block. When 'unverified', a\n * `completed` entry derives as `failed`/`unverified` instead of trusting it.\n */\n completionVerification?: CompletionVerification;\n /** Number of queued pending invocations for the block, when known. */\n pendingInvocationCount?: number;\n /** Successful run count from the audit trail, when the caller has it. */\n runCount?: number;\n}\n\n/**\n * Derive the presentation phase of a block from its canonical runtime state.\n *\n * Pure and read-only: never writes, never consults the clock. Cardinality is\n * the main branch — a repeatable ('many') action never derives `complete`;\n * a `completed` entry just means \"has fired at least once\" and the block\n * remains a standing `active` capability (see ActionDefinition.cardinality).\n *\n * Unknown state strings derive as `failed`/`needs_verification` with\n * `safeToRetry: false`: a state this build doesn't understand was written by\n * a newer client, and the only safe assumption is \"do not touch\".\n */\nexport function deriveBlockPhase(params: DeriveBlockPhaseParams): DerivedBlockState {\n const { runtime, actionType, completionVerification, pendingInvocationCount = 0, runCount } = params;\n const repeatable = isRepeatableAction(actionType);\n const state = runtime?.state ?? 'idle';\n\n const base = { repeatable, ...(repeatable && runCount !== undefined ? { runCount } : {}) };\n\n if (state === 'completed' && completionVerification?.status === 'unverified') {\n return { ...base, phase: 'failed', detail: 'unverified', safeToRetry: false };\n }\n\n switch (state) {\n case 'idle':\n if (pendingInvocationCount > 0) {\n return { ...base, phase: 'active', detail: 'queued', safeToRetry: true };\n }\n return { ...base, phase: 'pending', detail: 'idle', safeToRetry: true };\n case 'running':\n return { ...base, phase: 'active', detail: 'running', safeToRetry: false };\n case 'awaiting_readback':\n return { ...base, phase: 'active', detail: 'awaiting_readback', safeToRetry: false };\n case 'completed':\n if (repeatable) {\n return { ...base, phase: 'active', detail: 'standing', safeToRetry: true };\n }\n return { ...base, phase: 'complete', detail: 'completed', safeToRetry: false };\n case 'cancelled':\n // Cancellation deliberately closes the block — terminal even for a\n // repeatable capability, unlike `completed` which just means \"fired\".\n return { ...base, phase: 'complete', detail: 'cancelled', safeToRetry: false };\n case 'failed':\n return { ...base, phase: 'failed', detail: 'failed', safeToRetry: true };\n case 'needs_verification':\n return { ...base, phase: 'failed', detail: 'needs_verification', safeToRetry: false };\n default:\n // Forward-compat guard: an unknown state was written by a newer client.\n // Deriving it as pending would let auto-execute gates fire and risk\n // double-execution — treat it as needs-attention, never retryable.\n return { ...base, phase: 'failed', detail: 'needs_verification', safeToRetry: false };\n }\n}\n\n/**\n * Count the successful runs of a block from the audit trail — the real\n * progress measure for a repeatable ('many') block, whose single runtime\n * entry only says \"has fired at least once\".\n */\nexport function countSuccessfulRuns(yDoc: Y.Doc, blockId: string): number {\n return readRunRecords(yDoc, blockId).filter((record) => !record.error).length;\n}\n","/**\n * Validate a block's user-authored JSON configuration props.\n *\n * The engine's parse helpers absorb malformed JSON (a block with a broken\n * trigger simply never fires) — this helper makes that state visible so the\n * UI can render an \"Invalid configuration\" indicator instead of leaving the\n * block silently inert.\n */\nexport function validateBlockConfig(block: { id?: string; props?: Record<string, unknown> } | null | undefined): string[] {\n const issues: string[] = [];\n if (!block?.props) return issues;\n\n const checkJson = (propName: string, value: unknown, expectObject = true): void => {\n if (value == null || value === '') return;\n if (typeof value !== 'string') return; // already parsed — fine\n try {\n const parsed = JSON.parse(value);\n if (expectObject && (parsed == null || typeof parsed !== 'object')) {\n issues.push(`${propName} is valid JSON but not an object`);\n }\n } catch {\n issues.push(`${propName} is not valid JSON`);\n }\n };\n\n checkJson('inputs', block.props.inputs);\n checkJson('trigger', block.props.trigger);\n checkJson('assignment', block.props.assignment);\n checkJson('conditions', block.props.conditions);\n\n return issues;\n}\n","/**\n * Flow Migration Engine\n *\n * State machine that manages per-flow version upgrades.\n * Migration progress is persisted in a Yjs map so it survives page reloads\n * and is visible to all collaborators.\n *\n * Key properties:\n * - Incremental: each work item is processed and persisted individually\n * - Resumable: interrupted migrations pick up from the last pending item\n * - Safe: version is only stamped after all items complete and post-validation passes\n * - Owner-only: only the flow owner can initiate or resume a migration\n */\n\nimport type { Map as YMap } from 'yjs';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { UcanService } from '../../services/ucanService';\nimport type { FlowVersionString } from './versionManifest';\nimport { getMigrationChain } from './versionManifest';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type MigrationPhase = 'idle' | 'analyzing' | 'ready' | 'executing' | 'validating' | 'finalizing' | 'complete' | 'failed';\n\nexport interface MigrationWorkItem {\n /** Unique identifier for this work item */\n id: string;\n /** Block ID this item relates to (empty for flow-level items like root delegation) */\n nodeId: string;\n /** Type of work to perform */\n type: 'create_root_delegation' | 'create_node_delegation' | 'backfill_capability';\n /** Current status */\n status: 'pending' | 'completed' | 'failed';\n /** Error message if failed */\n error?: string;\n /** Whether this item requires user interaction (e.g., PIN for signing) */\n requiresUserAction: boolean;\n /** Human-readable description */\n description: string;\n}\n\nexport interface MigrationState {\n /** Current phase of the migration */\n phase: MigrationPhase;\n /** Version migrating from */\n fromVersion: string;\n /** Version migrating to */\n toVersion: string;\n /** DID of the user who initiated the migration */\n initiatorDid: string;\n /** ISO timestamp when migration started */\n startedAt: string;\n /** Work items to process */\n workItems: MigrationWorkItem[];\n /** Number of completed items */\n completedItems: number;\n /** Total number of items */\n totalItems: number;\n /** Error message if migration failed */\n error?: string;\n /** ISO timestamp when migration completed */\n completedAt?: string;\n}\n\nexport interface MigrationHistoryEntry {\n from: string;\n to: string;\n migratedBy: string;\n migratedAt: string;\n itemCount: number;\n}\n\nexport interface MigrationPrecondition {\n id: string;\n description: string;\n check: (ctx: MigrationContext) => boolean | Promise<boolean>;\n /** If true, failing this precondition blocks the entire migration */\n blocking: boolean;\n}\n\nexport interface MigrationDefinition {\n from: FlowVersionString;\n to: FlowVersionString;\n\n /** Preconditions that must be met before migration can start */\n preconditions: MigrationPrecondition[];\n\n /** Analyze the flow and return work items */\n analyze: (ctx: MigrationContext) => Promise<MigrationWorkItem[]>;\n\n /** Execute a single work item */\n executeItem: (ctx: MigrationContext, item: MigrationWorkItem) => Promise<{ success: boolean; error?: string }>;\n\n /** Validate the flow after all items are processed */\n postValidate: (ctx: MigrationContext) => Promise<{ valid: boolean; errors: string[] }>;\n\n /** Finalize the migration (stamp version, update context) */\n finalize: (ctx: MigrationContext) => void;\n}\n\nexport interface MigrationContext {\n /** The editor instance */\n editor: IxoEditorType;\n /** The migration Yjs map for persisting state */\n migrationMap: YMap<any>;\n /** DID of the actor performing the migration (must be flow owner) */\n actorDid: string;\n /** DID of the flow owner */\n flowOwnerDid: string;\n /** Flow URI for capability resources */\n flowUri: string;\n /** Flow document ID */\n flowId: string;\n /** UCAN service for creating delegations */\n ucanService: UcanService;\n /** PIN for signing operations */\n pin: string;\n /** Actor type for signing */\n actorType: 'entity' | 'user';\n /** Entity room ID if signing as entity */\n entityRoomId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Migration Registry\n// ---------------------------------------------------------------------------\n\nconst MIGRATION_REGISTRY: Record<string, MigrationDefinition> = {};\n\n/**\n * Register a migration definition. Called by migration files on import.\n */\nexport function registerMigration(definition: MigrationDefinition): void {\n const key = `${definition.from}->${definition.to}`;\n MIGRATION_REGISTRY[key] = definition;\n}\n\n/**\n * Get the migration definition for a version pair.\n */\nexport function getMigrationDefinition(from: string, to: string): MigrationDefinition | null {\n return MIGRATION_REGISTRY[`${from}->${to}`] || null;\n}\n\n// ---------------------------------------------------------------------------\n// State persistence helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current migration state from the Yjs map.\n */\nexport function getMigrationState(migrationMap: YMap<any>): MigrationState | null {\n const raw = migrationMap.get('state');\n if (!raw) return null;\n return typeof raw === 'string' ? JSON.parse(raw) : raw;\n}\n\nfunction persistState(migrationMap: YMap<any>, state: MigrationState): void {\n migrationMap.set('state', JSON.parse(JSON.stringify(state)));\n}\n\nfunction getMigrationHistory(migrationMap: YMap<any>): MigrationHistoryEntry[] {\n const raw = migrationMap.get('history');\n if (!raw) return [];\n return typeof raw === 'string' ? JSON.parse(raw) : raw;\n}\n\nfunction appendMigrationHistory(migrationMap: YMap<any>, entry: MigrationHistoryEntry): void {\n const history = getMigrationHistory(migrationMap);\n history.push(entry);\n migrationMap.set('history', JSON.parse(JSON.stringify(history)));\n}\n\n// ---------------------------------------------------------------------------\n// Migration lifecycle functions\n// ---------------------------------------------------------------------------\n\n/**\n * Start a migration from the flow's current version to the target version.\n * Runs preconditions and analysis, persists work items.\n * Does NOT execute any items — call executeMigrationStep() for that.\n */\nexport async function startMigration(ctx: MigrationContext, fromVersion: string, toVersion: string): Promise<{ success: boolean; state: MigrationState; errors: string[] }> {\n const errors: string[] = [];\n\n // Resolve migration definition\n const definition = getMigrationDefinition(fromVersion, toVersion);\n if (!definition) {\n return {\n success: false,\n state: createFailedState(fromVersion, toVersion, ctx.actorDid, `No migration path from ${fromVersion} to ${toVersion}`),\n errors: [`No migration definition registered for ${fromVersion} -> ${toVersion}`],\n };\n }\n\n // Check preconditions\n for (const precondition of definition.preconditions) {\n const passed = await precondition.check(ctx);\n if (!passed) {\n if (precondition.blocking) {\n const state = createFailedState(fromVersion, toVersion, ctx.actorDid, `Precondition failed: ${precondition.description}`);\n persistState(ctx.migrationMap, state);\n return { success: false, state, errors: [precondition.description] };\n }\n errors.push(`Warning: ${precondition.description}`);\n }\n }\n\n // Analyze\n const workItems = await definition.analyze(ctx);\n\n const state: MigrationState = {\n phase: workItems.length === 0 ? 'ready' : 'ready',\n fromVersion,\n toVersion,\n initiatorDid: ctx.actorDid,\n startedAt: new Date().toISOString(),\n workItems,\n completedItems: 0,\n totalItems: workItems.length,\n };\n\n persistState(ctx.migrationMap, state);\n return { success: true, state, errors };\n}\n\n/**\n * Execute the next pending work item in the migration.\n * Call this repeatedly until all items are processed.\n * Returns the updated state after processing one item.\n */\nexport async function executeMigrationStep(ctx: MigrationContext): Promise<MigrationState> {\n const state = getMigrationState(ctx.migrationMap);\n if (!state) {\n throw new Error('No migration in progress');\n }\n\n if (state.phase === 'complete' || state.phase === 'failed') {\n return state;\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n state.phase = 'failed';\n state.error = `Migration definition not found for ${state.fromVersion} -> ${state.toVersion}`;\n persistState(ctx.migrationMap, state);\n return state;\n }\n\n // Find next pending item\n const pendingItem = state.workItems.find((item) => item.status === 'pending');\n if (!pendingItem) {\n // All items processed, move to validating\n state.phase = 'validating';\n persistState(ctx.migrationMap, state);\n return state;\n }\n\n // Execute the item\n state.phase = 'executing';\n persistState(ctx.migrationMap, state);\n\n const result = await definition.executeItem(ctx, pendingItem);\n\n if (result.success) {\n pendingItem.status = 'completed';\n state.completedItems++;\n } else {\n pendingItem.status = 'failed';\n pendingItem.error = result.error;\n }\n\n // Check if all items are done\n const stillPending = state.workItems.some((item) => item.status === 'pending');\n if (!stillPending) {\n const anyFailed = state.workItems.some((item) => item.status === 'failed');\n state.phase = anyFailed ? 'failed' : 'validating';\n if (anyFailed) {\n state.error = 'One or more migration items failed. Review individual items for details.';\n }\n }\n\n persistState(ctx.migrationMap, state);\n return state;\n}\n\n/**\n * Execute all remaining pending work items in sequence.\n * Convenience wrapper around executeMigrationStep.\n */\nexport async function executeAllMigrationSteps(ctx: MigrationContext): Promise<MigrationState> {\n let state = getMigrationState(ctx.migrationMap);\n if (!state) throw new Error('No migration in progress');\n\n while (state.phase !== 'validating' && state.phase !== 'failed' && state.phase !== 'complete') {\n const hasRemaining = state.workItems.some((item) => item.status === 'pending');\n if (!hasRemaining) break;\n state = await executeMigrationStep(ctx);\n }\n\n return state;\n}\n\n/**\n * Run post-validation after all work items are complete.\n * Returns validation result without modifying the version.\n */\nexport async function validateMigration(ctx: MigrationContext): Promise<{ valid: boolean; errors: string[] }> {\n const state = getMigrationState(ctx.migrationMap);\n if (!state || state.phase !== 'validating') {\n return { valid: false, errors: ['Migration is not in validating phase'] };\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n return { valid: false, errors: ['Migration definition not found'] };\n }\n\n const result = await definition.postValidate(ctx);\n\n if (!result.valid) {\n state.phase = 'failed';\n state.error = `Post-validation failed: ${result.errors.join('; ')}`;\n persistState(ctx.migrationMap, state);\n }\n\n return result;\n}\n\n/**\n * Finalize the migration — stamp the new version and record history.\n * Only call after validateMigration returns { valid: true }.\n */\nexport function finalizeMigration(ctx: MigrationContext): MigrationState {\n const state = getMigrationState(ctx.migrationMap);\n if (!state || state.phase !== 'validating') {\n throw new Error('Cannot finalize: migration is not in validating phase');\n }\n\n const definition = getMigrationDefinition(state.fromVersion, state.toVersion);\n if (!definition) {\n throw new Error('Migration definition not found');\n }\n\n // Run the definition's finalize (stamps version on root map, etc.)\n definition.finalize(ctx);\n\n // Record history\n appendMigrationHistory(ctx.migrationMap, {\n from: state.fromVersion,\n to: state.toVersion,\n migratedBy: ctx.actorDid,\n migratedAt: new Date().toISOString(),\n itemCount: state.totalItems,\n });\n\n // Update state\n state.phase = 'complete';\n state.completedAt = new Date().toISOString();\n persistState(ctx.migrationMap, state);\n\n return state;\n}\n\n/**\n * Abandon an in-progress migration. Safe because the version hasn't been bumped.\n * Resets migration state to idle.\n */\nexport function abandonMigration(migrationMap: YMap<any>): void {\n migrationMap.delete('state');\n}\n\n/**\n * Check if a migration can be resumed (has persisted state with pending items).\n */\nexport function canResumeMigration(migrationMap: YMap<any>): boolean {\n const state = getMigrationState(migrationMap);\n if (!state) return false;\n return state.phase !== 'idle' && state.phase !== 'complete' && state.phase !== 'failed';\n}\n\n/**\n * Run a full migration chain from one version to another,\n * stepping through each intermediate version.\n * For UI-driven migrations, prefer calling the individual lifecycle functions.\n */\nexport async function runMigrationChain(ctx: MigrationContext, fromVersion: string, toVersion: string): Promise<{ success: boolean; finalVersion: string; errors: string[] }> {\n const chain = getMigrationChain(fromVersion, toVersion);\n if (chain.length === 0) {\n return { success: false, finalVersion: fromVersion, errors: ['No migration path found'] };\n }\n\n let currentVersion = fromVersion;\n const allErrors: string[] = [];\n\n for (const targetVersion of chain) {\n // Start\n const startResult = await startMigration(ctx, currentVersion, targetVersion);\n if (!startResult.success) {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, ...startResult.errors] };\n }\n\n // Execute all steps\n const state = await executeAllMigrationSteps(ctx);\n if (state.phase === 'failed') {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, state.error || 'Migration failed'] };\n }\n\n // Validate\n const validation = await validateMigration(ctx);\n if (!validation.valid) {\n return { success: false, finalVersion: currentVersion, errors: [...allErrors, ...validation.errors] };\n }\n\n // Finalize\n finalizeMigration(ctx);\n currentVersion = targetVersion;\n }\n\n return { success: true, finalVersion: currentVersion, errors: allErrors };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction createFailedState(from: string, to: string, initiator: string, error: string): MigrationState {\n return {\n phase: 'failed',\n fromVersion: from,\n toVersion: to,\n initiatorDid: initiator,\n startedAt: new Date().toISOString(),\n workItems: [],\n completedItems: 0,\n totalItems: 0,\n error,\n };\n}\n","/**\n * Migration: 0.3 → 1.0.0\n *\n * Upgrades a flow from optional UCAN to required UCAN authorization.\n *\n * What this migration does:\n * 1. Creates a root delegation if one doesn't exist\n * 2. For each executable block, ensures a delegation granting\n * flow/block/execute exists in the delegation store\n * 3. Validates all delegation chains resolve back to root\n * 4. Stamps schema_version to '1.0.0'\n *\n * In v1.0.0, delegations live in the UcanDelegationStore (Yjs-backed),\n * not as block props. The authorization layer validates chains from\n * the store at execution time.\n */\n\nimport type { MigrationDefinition, MigrationContext, MigrationWorkItem } from '../migration';\nimport { registerMigration } from '../migration';\nimport type { UcanCapability } from '../../../types/ucan';\n\n/** Block types that are structural/content and don't participate in flow execution */\nconst NON_EXECUTABLE_BLOCK_TYPES = new Set(['paragraph', 'heading', 'bulletListItem', 'numberedListItem', 'image', 'table']);\n\n/**\n * Check if a delegation already exists in the store for a given block.\n */\nfunction hasDelegationForBlock(ctx: MigrationContext, blockId: string): boolean {\n const delegations = ctx.ucanService.getAllDelegations();\n const resourceUri = `${ctx.flowUri}:${blockId}`;\n return delegations.some((d) => d.capabilities.some((c) => c.can === 'flow/block/execute' && c.with === resourceUri));\n}\n\nexport const migration_0_3_to_1_0_0: MigrationDefinition = {\n from: '0.3',\n to: '1.0.0',\n\n preconditions: [\n {\n id: 'has_flow_owner',\n description: 'Flow must have a flowOwnerDid set',\n check: (ctx) => {\n const ownerDid = ctx.editor.getFlowOwnerDid?.() || ctx.flowOwnerDid;\n return !!ownerDid;\n },\n blocking: true,\n },\n {\n id: 'is_owner',\n description: 'Only the flow owner can initiate migration',\n check: (ctx) => {\n const ownerDid = ctx.editor.getFlowOwnerDid?.() || ctx.flowOwnerDid;\n return ctx.actorDid === ownerDid;\n },\n blocking: true,\n },\n {\n id: 'ucan_service_available',\n description: 'UCAN service must be configured',\n check: (ctx) => {\n return !!ctx.ucanService && ctx.ucanService.isConfigured();\n },\n blocking: true,\n },\n ],\n\n async analyze(ctx: MigrationContext): Promise<MigrationWorkItem[]> {\n const items: MigrationWorkItem[] = [];\n const blocks = ctx.editor.document;\n\n // Check if root delegation exists\n const rootDelegation = ctx.ucanService.getRootDelegation();\n if (!rootDelegation) {\n items.push({\n id: '__root_delegation__',\n nodeId: '',\n type: 'create_root_delegation',\n status: 'pending',\n requiresUserAction: true,\n description: 'Create root delegation for flow owner',\n });\n }\n\n // Scan all blocks — create delegations for executable blocks that don't have one\n if (blocks) {\n for (const block of blocks) {\n if (NON_EXECUTABLE_BLOCK_TYPES.has(block.type)) continue;\n\n if (!hasDelegationForBlock(ctx, block.id)) {\n items.push({\n id: `node_delegation_${block.id}`,\n nodeId: block.id,\n type: 'create_node_delegation',\n status: 'pending',\n requiresUserAction: true,\n description: `Create delegation for block \"${block.type}\" (${block.id})`,\n });\n }\n }\n }\n\n return items;\n },\n\n async executeItem(ctx: MigrationContext, item: MigrationWorkItem): Promise<{ success: boolean; error?: string }> {\n try {\n switch (item.type) {\n case 'create_root_delegation': {\n await ctx.ucanService.createRootDelegation({\n flowOwnerDid: ctx.flowOwnerDid,\n issuerType: ctx.actorType,\n entityRoomId: ctx.entityRoomId,\n flowUri: ctx.flowUri,\n pin: ctx.pin,\n });\n return { success: true };\n }\n\n case 'create_node_delegation':\n case 'backfill_capability': {\n // Create a delegation from flow owner granting flow/block/execute for this node\n const capability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${ctx.flowUri}:${item.nodeId}`,\n };\n\n await ctx.ucanService.createDelegation({\n issuerDid: ctx.flowOwnerDid,\n issuerType: ctx.actorType,\n entityRoomId: ctx.entityRoomId,\n audience: ctx.flowOwnerDid, // Owner delegates to self initially; actors get sub-delegations\n capabilities: [capability],\n pin: ctx.pin,\n });\n\n return { success: true };\n }\n\n default:\n return { success: false, error: `Unknown work item type: ${item.type}` };\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { success: false, error: message };\n }\n },\n\n async postValidate(ctx: MigrationContext): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n const blocks = ctx.editor.document;\n\n // Verify root delegation exists\n const rootDelegation = ctx.ucanService.getRootDelegation();\n if (!rootDelegation) {\n errors.push('Root delegation is missing after migration');\n }\n\n // Verify each executable block has a valid delegation chain\n if (blocks) {\n for (const block of blocks) {\n if (NON_EXECUTABLE_BLOCK_TYPES.has(block.type)) continue;\n\n const requiredCapability: UcanCapability = {\n can: 'flow/block/execute',\n with: `${ctx.flowUri}:${block.id}`,\n };\n\n const validation = await ctx.ucanService.validateDelegationChain(ctx.flowOwnerDid, requiredCapability);\n if (!validation.valid) {\n errors.push(`Block \"${block.type}\" (${block.id}): delegation chain invalid — ${validation.error || 'unknown error'}`);\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n },\n\n finalize(ctx: MigrationContext): void {\n const root = ctx.editor._yRoot;\n if (!root) {\n throw new Error('Cannot finalize: editor _yRoot not available');\n }\n\n root.set('schema_version', '1.0.0');\n root.set('@context', 'https://ixo.world/flow/1.0');\n },\n};\n\n// Auto-register this migration on import\nregisterMigration(migration_0_3_to_1_0_0);\n","/**\n * Node context records — per-node semantic context written by the flow\n * manager (headless orchestrator) into the top-level `nodeContext` Y.Map,\n * keyed by block/node id. Records are plain JSON objects (no nested Y types)\n * so they replicate atomically and read back as ordinary data.\n *\n * The editor treats these records as advisory input from the flow manager,\n * with one exception: fields whose provenance is `'human'` are permanent\n * manual overrides that the flow manager must never clobber.\n */\n\n/**\n * Where a context field's value came from:\n * - 'derived': mechanically extracted from node inputs.\n * - 'inferred': produced by the flow manager's LLM classification pass.\n * - 'human': manual override; wins and survives re-determination.\n */\nexport type NodeContextFieldProvenance = 'derived' | 'inferred' | 'human';\n\nexport interface NodeContextRecord {\n kind: string;\n shapeVersion: number;\n sourceDigest: string;\n values: Record<string, unknown>;\n fieldProvenance: Record<string, NodeContextFieldProvenance>;\n inferredAt: string;\n model?: string;\n}\n\n/** Top-level Y.Doc map name the flow manager writes node context records to. */\nexport const NODE_CONTEXT_MAP_NAME = 'nodeContext';\n\n/**\n * Top-level Y.Doc map name for per-field human overrides, keyed\n * `${nodeId}:${field}` with the raw override value (JSON-serializable).\n * Writing one key per override (instead of rewriting the whole record in\n * `nodeContext`) makes human overrides race-free against concurrent\n * whole-record writes by the flow manager. Readers overlay these entries on\n * the base record at read time with `fieldProvenance[field] = 'human'`.\n */\nexport const NODE_CONTEXT_OVERRIDES_MAP_NAME = 'nodeContextOverrides';\n\n/**\n * Structural guard for records read out of the shared Y.Map. The map is\n * written by a separate process (the flow manager), so never assume shape —\n * malformed entries are treated as absent rather than crashing the UI.\n */\nexport function isNodeContextRecord(value: unknown): value is NodeContextRecord {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n const record = value as Partial<NodeContextRecord>;\n return (\n typeof record.kind === 'string' &&\n typeof record.shapeVersion === 'number' &&\n typeof record.sourceDigest === 'string' &&\n Boolean(record.values) &&\n typeof record.values === 'object' &&\n !Array.isArray(record.values) &&\n Boolean(record.fieldProvenance) &&\n typeof record.fieldProvenance === 'object' &&\n !Array.isArray(record.fieldProvenance) &&\n typeof record.inferredAt === 'string'\n );\n}\n","/**\n * The operator vocabulary the FE condition evaluator actually understands\n * (`src/mantine/blocks/utils/conditionEvaluator.ts`). The compiler historically wrote the\n * BaseUcan `ConditionRef` vocabulary (`eq`/`neq`/…) verbatim, which the evaluator does NOT\n * recognise (and no normalizer bridged them) — so those conditions silently never fired.\n * This module is the single source of truth that maps every supported spelling onto the\n * evaluator's vocabulary, and assembles the `props.conditions` JSON.\n */\nexport type EvaluatorOperator = 'equals' | 'not_equals' | 'greater_than' | 'less_than' | 'contains' | 'not_contains' | 'is_empty' | 'is_not_empty';\n\nconst OPERATOR_MAP: Record<string, EvaluatorOperator> = {\n // BaseUcan ConditionRef vocabulary\n eq: 'equals',\n neq: 'not_equals',\n gt: 'greater_than',\n lt: 'less_than',\n in: 'contains',\n exists: 'is_not_empty',\n // Friendly camelCase (plugin FlowSpec `is`)\n equals: 'equals',\n notEquals: 'not_equals',\n greaterThan: 'greater_than',\n lessThan: 'less_than',\n isEmpty: 'is_empty',\n isNotEmpty: 'is_not_empty',\n // Evaluator vocabulary passthrough\n not_equals: 'not_equals',\n greater_than: 'greater_than',\n less_than: 'less_than',\n contains: 'contains',\n not_contains: 'not_contains',\n notContains: 'not_contains',\n is_empty: 'is_empty',\n is_not_empty: 'is_not_empty',\n};\n\n/** Normalize any supported operator spelling to the evaluator's vocabulary. Unknown → `equals`. */\nexport function toEvaluatorOperator(operator: string): EvaluatorOperator {\n return OPERATOR_MAP[operator] ?? 'equals';\n}\n\nexport interface BlockConditionInput {\n /** The BLOCK id of the source step (note: the stored shape keys on blockId, not nodeId). */\n sourceBlockId: string;\n /** Property on the source block to test. */\n property: string;\n /** Any supported operator spelling — normalized to the evaluator's vocabulary on write. */\n operator: string;\n value?: unknown;\n effect?: { action: 'enable' | 'disable' | 'show' | 'hide'; message?: string };\n /** Source block type label; defaults to the compiled action type (`'action'`). */\n sourceBlockType?: string;\n name?: string;\n}\n\n/**\n * Build the `props.conditions` JSON string in the exact shape the FE evaluator reads, with\n * operators normalized to its vocabulary. Single source of truth for the conditions prop —\n * used by both the flow compiler (`compileCondition`) and direct authoring writes\n * (`setBlockProps('conditions', buildBlockConditionsProp(...))`), so a condition authored\n * either way actually evaluates.\n */\nexport function buildBlockConditionsProp(conditions: BlockConditionInput[], opts?: { mode?: 'all_must_pass' | 'any_can_pass'; enabled?: boolean }): string {\n return JSON.stringify({\n enabled: opts?.enabled ?? true,\n mode: opts?.mode ?? 'all_must_pass',\n conditions: conditions.map((c, i) => ({\n id: `cond_${c.sourceBlockId}_${c.property}_${i}`,\n name: c.name ?? `Condition from ${c.sourceBlockId}`,\n sourceBlockId: c.sourceBlockId,\n sourceBlockType: c.sourceBlockType ?? 'action',\n rule: {\n type: 'property_value',\n property: c.property,\n operator: toEvaluatorOperator(c.operator),\n value: c.value,\n },\n effect: c.effect ?? { action: 'enable' },\n })),\n });\n}\n","import type { FlowCapability } from '../../types/baseUcan';\n\n/** Default icon per `can` statement. */\nconst ICON_DEFAULTS: Record<string, string> = {\n 'bid/submit': 'gavel',\n 'bid/evaluate': 'check-circle',\n 'claim/submit': 'file-check',\n 'claim/evaluate': 'clipboard-check',\n 'email/send': 'mail',\n 'notification/push': 'bell',\n 'matrix/dm': 'message-circle',\n 'proposal/create': 'scroll',\n 'proposal/vote': 'vote',\n 'domain/card-preview': 'id',\n 'domain/sign': 'feather',\n 'credential/store': 'shield',\n 'http/request': 'cloud',\n 'protocol/select': 'git-branch',\n 'human/checkbox': 'check-square',\n 'human/form': 'file-text',\n 'form/submit': 'file-text',\n 'oracle/query': 'cpu',\n};\n\n/**\n * Compile a FlowCapability into block props for the `action` block type.\n *\n * All capabilities map to the `action` block type — the `actionType` prop\n * routes to the correct registry action at runtime. This is consistent with\n * how the slash menu creates action blocks today.\n *\n * All returned values are strings per BlockNote convention.\n */\nexport function compileBlockProps(cap: FlowCapability, registryType: string): Record<string, string> {\n return {\n title: cap.title || cap.can,\n description: cap.description || '',\n icon: cap.icon || ICON_DEFAULTS[cap.can] || 'bolt',\n actionType: registryType,\n inputs: JSON.stringify(cap.nb || {}),\n requiresConfirmation: '',\n conditions: '', // compiled separately by the compiler\n // Authorization props\n parentCapability: cap.actor?.parentCapability || '',\n authorisedActors: cap.actor?.authorisedActors ? JSON.stringify(cap.actor.authorisedActors) : '',\n // TTL props\n ttlAbsoluteDueDate: cap.ttl?.absoluteDueDate || '',\n ttlFromEnablement: cap.ttl?.fromEnablement || '',\n ttlFromCommitment: cap.ttl?.fromCommitment || '',\n // Trigger props (slice D — events and triggers feature). Stored as a\n // JSON string mirroring how `inputs` serializes `nb`. Default empty\n // string means \"manual\" — the runtime treats absent or empty as manual.\n trigger: cap.trigger ? JSON.stringify(cap.trigger) : '',\n };\n}\n\n/** The BlockNote block type that all capabilities compile to. */\nexport const COMPILED_BLOCK_TYPE = 'action' as const;\n\n/** Get the default icon for a `can` statement. */\nexport function getDefaultIcon(can: string): string {\n return ICON_DEFAULTS[can] || 'bolt';\n}\n","import type { BaseUcanFlow, FlowCapability, CompiledFlow, CompiledBlock, CompiledEdge, CompiledFlowNode, ConditionRef, RuntimeRef, TriggerSpec } from '../../types/baseUcan';\nimport { isRuntimeRef } from '../../types/baseUcan';\nimport type { ActionDefinition } from '../actionRegistry/types';\nimport { getEventsForBlock } from '../actionRegistry/registry';\nimport { compileBlockProps, COMPILED_BLOCK_TYPE } from './blockMapping';\nimport { toEvaluatorOperator } from './conditions';\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/** Registry interface expected by the compiler (keeps it pure / testable). */\nexport interface CompilerRegistry {\n getActionByCan(can: string): ActionDefinition | undefined;\n}\n\n/**\n * Compile a Base UCAN flow plan into blocks, graph state, and metadata.\n *\n * This is a **pure function** — no React, no Yjs, no side effects.\n * The output is consumed by `hydrateFlowFromPlan()`.\n */\nexport function compileBaseUcanFlow(plan: BaseUcanFlow, registry: CompilerRegistry): CompiledFlow {\n if (!Array.isArray(plan.capabilities)) {\n throw new Error('BaseUcanFlow.capabilities must be an array');\n }\n\n const capabilities = plan.capabilities;\n if (capabilities.length === 0) {\n throw new Error('BaseUcanFlow has no capabilities to compile');\n }\n\n // 1. Validate every `can` against the registry\n const actionMap = new Map<string, { action: ActionDefinition; nodeId: string; cap: FlowCapability }>();\n for (const cap of capabilities) {\n const nodeId = cap.id?.trim();\n if (!nodeId) {\n throw new Error('Every capability in BaseUcanFlow.capabilities must include a non-empty id.');\n }\n if (actionMap.has(nodeId)) {\n throw new Error(`Duplicate capability id \"${nodeId}\" in BaseUcanFlow.capabilities.`);\n }\n\n const action = registry.getActionByCan(cap.can);\n if (!action) {\n throw new Error(`Unknown capability \"${cap.can}\" for node \"${nodeId}\". Not found in action registry.`);\n }\n actionMap.set(nodeId, { action, nodeId, cap });\n }\n\n // 2. Pre-generate deterministic block IDs (stable for testing)\n const blockIndex: Record<string, string> = {};\n for (const nodeId of actionMap.keys()) {\n blockIndex[nodeId] = generateBlockId(nodeId);\n }\n\n // 3. Validate triggers (slice D — events and triggers feature).\n // For every block.event-triggered listener:\n // a) source block must exist in the plan\n // b) source action must declare an `events` array\n // c) eventName must match a declared event\n // d) every nodeId.output.* ref in the listener's nb must be reachable\n // (the referenced block must exist; the field shape is enforced\n // loosely because output schemas are optional today)\n // Also: synthesize \"trigger\" edges from each block.event trigger so the\n // visual graph and the cycle detector see the dependency.\n const triggerEdges: CompiledEdge[] = [];\n for (const [nodeId, { cap, action }] of actionMap) {\n const trigger = cap.trigger;\n if (!trigger) continue;\n\n // ── block.event (single source) ──────────────────────────────────\n if (trigger.type === 'block.event') {\n if (action.eligibleForEventTrigger !== true) {\n throw new Error(\n `Block \"${nodeId}\" is configured with a block.event trigger, but its action type \"${action.type}\" is not marked eligibleForEventTrigger. Set eligibleForEventTrigger: true on the action definition or change the trigger to manual.`\n );\n }\n\n const sourceId = trigger.sourceBlockId?.trim();\n const eventName = trigger.eventName?.trim();\n if (!sourceId || !eventName) {\n throw new Error(`Block \"${nodeId}\" has a block.event trigger but is missing sourceBlockId or eventName.`);\n }\n\n const source = actionMap.get(sourceId);\n if (!source) {\n throw new Error(`Trigger on block \"${nodeId}\" references unknown source block \"${sourceId}\".`);\n }\n\n // Resolve events per the source block's current inputs; some actions\n // (e.g. claim.submit) derive the event list from configured state.\n const declaredEvents = getEventsForBlock(source.action, source.cap.nb);\n if (declaredEvents.length === 0) {\n throw new Error(`Trigger on block \"${nodeId}\" references event \"${eventName}\" but source action \"${source.action.type}\" declares no events.`);\n }\n\n const found = declaredEvents.find((e) => e.name === eventName);\n if (!found) {\n const declared = declaredEvents.map((e) => e.name).join(', ');\n throw new Error(`Trigger on block \"${nodeId}\" references unknown event \"${eventName}\" on action type \"${source.action.type}\". Declared events: [${declared}]`);\n }\n\n triggerEdges.push({\n id: `${sourceId}~event:${eventName}~>${nodeId}`,\n source: sourceId,\n target: nodeId,\n kind: 'trigger',\n });\n }\n\n if (trigger.type === 'block.event.all') {\n if (action.eligibleForEventTrigger !== true) {\n throw new Error(`Block \"${nodeId}\" is configured with a block.event.all trigger, but its action type \"${action.type}\" is not marked eligibleForEventTrigger.`);\n }\n\n const sources = trigger.sources || [];\n if (sources.length === 0) {\n throw new Error(`Block \"${nodeId}\" has a block.event.all trigger but no sources configured.`);\n }\n\n for (const src of sources) {\n const srcId = src.sourceBlockId?.trim();\n const evtName = src.eventName?.trim();\n if (!srcId || !evtName) {\n throw new Error(`Block \"${nodeId}\" has a block.event.all source with missing sourceBlockId or eventName.`);\n }\n\n const sourceEntry = actionMap.get(srcId);\n if (!sourceEntry) {\n throw new Error(`Barrier trigger on block \"${nodeId}\" references unknown source block \"${srcId}\".`);\n }\n\n const declaredEvents = getEventsForBlock(sourceEntry.action, sourceEntry.cap.nb);\n const found = declaredEvents.find((e) => e.name === evtName);\n if (!found) {\n const declared = declaredEvents.map((e) => e.name).join(', ');\n throw new Error(`Barrier trigger on block \"${nodeId}\" references unknown event \"${evtName}\" on action type \"${sourceEntry.action.type}\". Declared events: [${declared}]`);\n }\n\n if (!src.alias?.trim()) {\n throw new Error(`Barrier trigger on block \"${nodeId}\" has a source (${srcId}/${evtName}) with no alias.`);\n }\n\n triggerEdges.push({\n id: `${srcId}~event:${evtName}~>${nodeId}`,\n source: srcId,\n target: nodeId,\n kind: 'trigger',\n });\n }\n }\n\n // Validate that every nodeId.output.* ref the listener uses points at a\n // block that exists.\n if (trigger.type === 'block.event' || trigger.type === 'block.event.all') {\n const refs = collectOutputRefs(cap.nb || {});\n for (const ref of refs) {\n const parsed = parseOutputRef(ref);\n if (!parsed) continue;\n if (!actionMap.has(parsed.nodeId)) {\n throw new Error(`Listener \"${nodeId}\" references output of unknown block \"${parsed.nodeId}\" via ref \"${ref}\".`);\n }\n }\n }\n }\n\n // 4. Edges = trigger edges only. Synthesized in step 3 from `block.event`\n // triggers. Each one represents a real runtime relationship: source\n // emits an event, listener queues a pending invocation. There are no\n // other edge kinds — sequential ordering is implicit in the\n // capabilities[] array order, not derived from a separate field.\n const edges: CompiledEdge[] = [...triggerEdges];\n\n // 4b. Trigger graph cycle check. A cycle would cause the reconciliation\n // loop to oscillate (A's emission queues B, B's emission queues A,\n // forever). Hard error at compile time.\n detectTriggerCycles(triggerEdges);\n\n // 5. Order = the order capabilities appeared in the input plan.\n // No topological sort. The author is responsible for the order they\n // want; the compiler does not infer it.\n const order = Array.from(actionMap.keys());\n\n // 6. Compile each block in order\n const blocks: CompiledBlock[] = [];\n const nodes: Record<string, CompiledFlowNode> = {};\n\n for (const nodeId of order) {\n const { action, cap } = actionMap.get(nodeId)!;\n const blockId = blockIndex[nodeId];\n\n // Compile base props from the capability\n const props = compileBlockProps(cap, action.type);\n\n // Compile conditions into the block's conditions prop\n if (cap.condition) {\n props.conditions = compileCondition(cap.condition, blockIndex);\n }\n\n // Rewrite trigger source references from the node-id namespace (what\n // plan authors write, validated in step 3) into the block-id namespace\n // before serialization. The runtime reconciler matches props.trigger\n // against real document block ids (`flow_block_<nodeId>`) — a trigger\n // serialized with node ids validates fine but never fires.\n if (cap.trigger) {\n props.trigger = compileTrigger(cap.trigger, blockIndex);\n }\n\n // Stamp the trigger mode prop so the runtime UI knows whether this\n // block is event-driven or manually invoked. Event-driven blocks\n // suppress all manual run affordances and only fire via pending\n // invocations queued by the reconciliation loop. Default 'manual'.\n props.triggerMode = cap.trigger?.type || 'manual';\n\n blocks.push({\n id: blockId,\n type: COMPILED_BLOCK_TYPE,\n props,\n });\n\n nodes[nodeId] = {\n id: nodeId,\n blockId,\n can: cap.can,\n with: cap.with,\n registryType: action.type,\n title: cap.title || cap.can,\n description: cap.description || '',\n props,\n phase: cap.phase,\n parallelGroup: cap.parallelGroup,\n actor: cap.actor,\n };\n }\n\n return {\n meta: {\n flowId: plan.flowId,\n title: plan.title,\n goal: plan.goal,\n version: plan.version,\n flowOwnerDid: plan.meta?.rootIssuer || '',\n flowUri: plan.meta?.flowUri,\n compiledAt: new Date().toISOString(),\n compiledFrom: 'BaseUcanFlow',\n },\n blocks,\n nodes,\n edges,\n order,\n blockIndex,\n };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Generate a deterministic block ID from a node ID. */\nfunction generateBlockId(nodeId: string): string {\n // Use a prefix to clearly identify compiler-generated blocks\n return `flow_block_${nodeId}`;\n}\n\n/**\n * Compile a ConditionRef into the JSON string format expected by block conditions.\n * Matches the shape used by the existing block conditions system.\n */\nfunction compileCondition(condition: ConditionRef, blockIndex: Record<string, string>): string {\n const sourceBlockId = blockIndex[condition.sourceId];\n if (!sourceBlockId) {\n throw new Error(`Condition references unknown source \"${condition.sourceId}\".`);\n }\n\n const conditionConfig = {\n enabled: true,\n mode: 'all_must_pass',\n conditions: [\n {\n id: `cond_${condition.sourceId}_${condition.field}`,\n name: `Condition from ${condition.sourceId}`,\n sourceBlockId,\n sourceBlockType: COMPILED_BLOCK_TYPE,\n rule: {\n type: 'property_value',\n property: condition.field,\n // Map the BaseUcan ConditionRef operator (eq/neq/…) onto the FE evaluator's\n // vocabulary (equals/not_equals/…). Writing it verbatim is the historical bug\n // that made compiler-authored conditions silently never evaluate.\n operator: toEvaluatorOperator(condition.operator),\n value: condition.value,\n },\n effect: condition.effect || { action: 'enable' },\n },\n ],\n };\n\n return JSON.stringify(conditionConfig);\n}\n\n/**\n * Compile a TriggerSpec into the JSON string stored in props.trigger,\n * remapping every source reference from node id to compiled block id —\n * the same namespace translation compileCondition performs. Trigger\n * validation (step 3) has already guaranteed every source id resolves\n * in blockIndex.\n */\nfunction compileTrigger(trigger: TriggerSpec, blockIndex: Record<string, string>): string {\n if (trigger.type === 'block.event' && trigger.sourceBlockId) {\n return JSON.stringify({ ...trigger, sourceBlockId: blockIndex[trigger.sourceBlockId.trim()] });\n }\n if (trigger.type === 'block.event.all' && trigger.sources) {\n return JSON.stringify({\n ...trigger,\n sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: blockIndex[src.sourceBlockId.trim()] })),\n });\n }\n return JSON.stringify(trigger);\n}\n\n// ─── Trigger validation helpers (slice D — events and triggers) ─────────────\n\n/**\n * Recursively walk an inputs/nb object and collect every RuntimeRef string\n * that targets a node output (i.e. matches `nodeId.output.fieldPath`).\n * Skips `trigger.payload.*` refs which resolve from a different namespace.\n */\nfunction collectOutputRefs(value: unknown): string[] {\n const refs: string[] = [];\n walk(value);\n return refs;\n\n function walk(v: unknown): void {\n if (isRuntimeRef(v)) {\n const r = (v as RuntimeRef).$ref;\n if (!r.startsWith('trigger.')) refs.push(r);\n return;\n }\n if (Array.isArray(v)) {\n for (const item of v) walk(item);\n return;\n }\n if (v !== null && typeof v === 'object') {\n for (const inner of Object.values(v as Record<string, unknown>)) walk(inner);\n }\n }\n}\n\n/** Parse `\"nodeId.output.fieldPath\"` into its parts; returns null if not a node-output ref. */\nfunction parseOutputRef(ref: string): { nodeId: string; fieldPath: string } | null {\n const outputIndex = ref.indexOf('.output.');\n if (outputIndex === -1) return null;\n return {\n nodeId: ref.slice(0, outputIndex),\n fieldPath: ref.slice(outputIndex + '.output.'.length),\n };\n}\n\n/**\n * Detect cycles in the trigger graph.\n *\n * A trigger cycle would mean: block A's event triggers block B, whose event\n * triggers block C, whose event triggers block A. The reconciliation loop\n * would oscillate forever queueing pending invocations. Hard error.\n *\n * Implementation: standard DFS with three-color marking (white/gray/black).\n * If we hit a gray node during DFS, we're inside its own subtree — that's\n * the cycle. ~30 lines and runs in O(V + E) which is sub-millisecond at any\n * realistic block count.\n */\nfunction detectTriggerCycles(triggerEdges: CompiledEdge[]): void {\n if (triggerEdges.length === 0) return;\n\n const adjacency = new Map<string, string[]>();\n const allNodes = new Set<string>();\n for (const edge of triggerEdges) {\n if (!adjacency.has(edge.source)) adjacency.set(edge.source, []);\n adjacency.get(edge.source)!.push(edge.target);\n allNodes.add(edge.source);\n allNodes.add(edge.target);\n }\n\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n const color = new Map<string, number>();\n for (const id of allNodes) color.set(id, WHITE);\n\n const path: string[] = [];\n\n const visit = (node: string): void => {\n color.set(node, GRAY);\n path.push(node);\n for (const next of adjacency.get(node) || []) {\n if (color.get(next) === GRAY) {\n // Found the back-edge. Build a readable cycle path.\n const start = path.indexOf(next);\n const cycle = path.slice(start).concat(next).join(' → ');\n throw new Error(`Trigger cycle detected: ${cycle}. Block.event triggers must form a DAG; remove one of the trigger declarations to break the cycle.`);\n }\n if (color.get(next) === WHITE) {\n visit(next);\n }\n }\n path.pop();\n color.set(node, BLACK);\n };\n\n for (const id of allNodes) {\n if (color.get(id) === WHITE) visit(id);\n }\n}\n","import * as Y from 'yjs';\nimport type { CompiledBlock } from '../../types/baseUcan';\nimport type { MergeResult } from './mergeFlows';\n\n/**\n * Writes compiled blocks into BlockNote's collaborative XmlFragment using the\n * ProseMirror/Yjs structure that BlockNote reads from collaboration.\n */\nexport function writeCompiledBlocksToFragment(fragment: Y.XmlFragment, blocks: CompiledBlock[]): void {\n const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);\n\n for (const block of blocks) {\n appendBlockToGroup(documentBlockGroup, block);\n }\n}\n\n/**\n * Remove all block containers from the document fragment.\n * Used by the `full` strategy to clear existing blocks before rebuilding.\n */\nexport function removeAllFlowBlocks(fragment: Y.XmlFragment): void {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return;\n\n // Delete all children from the blockGroup\n while (blockGroup.length > 0) {\n blockGroup.delete(0, 1);\n }\n}\n\n/**\n * Remove a single block container by its block ID.\n * Returns `true` if the block was found and removed.\n */\nexport function removeBlockFromFragment(fragment: Y.XmlFragment, blockId: string): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (container instanceof Y.XmlElement && container.getAttribute('id') === blockId) {\n blockGroup.delete(i, 1);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Replace a block container in-place (same position) by its block ID.\n * Returns `true` if the block was found and replaced.\n */\nexport function replaceBlockInFragment(fragment: Y.XmlFragment, block: CompiledBlock): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (container instanceof Y.XmlElement && container.getAttribute('id') === block.id) {\n blockGroup.delete(i, 1);\n const newContainer = createBlockContainer(block);\n blockGroup.insert(i, [newContainer]);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Swap the document positions of two block containers, identified by block id.\n * Uses `clone()` so each block — including any inline/prose content — moves\n * intact (its `id` attribute is preserved, so runtime/graph linkage keyed on the\n * block id survives). Non-target blocks between them keep their positions.\n *\n * Returns `false` if either id is missing or they resolve to the same container.\n */\nexport function swapBlocksInFragment(fragment: Y.XmlFragment, idA: string, idB: string): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n let ia = -1;\n let ib = -1;\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (container instanceof Y.XmlElement) {\n const id = container.getAttribute('id');\n if (id === idA) ia = i;\n else if (id === idB) ib = i;\n }\n }\n if (ia < 0 || ib < 0 || ia === ib) return false;\n\n const lo = Math.min(ia, ib);\n const hi = Math.max(ia, ib);\n const loClone = (blockGroup.get(lo) as Y.XmlElement).clone();\n const hiClone = (blockGroup.get(hi) as Y.XmlElement).clone();\n\n // Rewrite the higher index first so the lower index stays valid.\n blockGroup.delete(hi, 1);\n blockGroup.insert(hi, [loClone]);\n blockGroup.delete(lo, 1);\n blockGroup.insert(lo, [hiClone]);\n return true;\n}\n\n/**\n * Apply a MergeResult to the document fragment.\n * Replaces changed blocks in-place and appends new blocks.\n */\nexport function applyMergeResultToFragment(fragment: Y.XmlFragment, mergeResult: MergeResult): void {\n const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);\n\n // Build a lookup from nodeId → block for the merged output\n const blockByNodeId = new Map<string, CompiledBlock>();\n for (const block of mergeResult.merged.blocks) {\n // blockId is `flow_block_{nodeId}`, reverse-map to nodeId\n for (const [nodeId, blockId] of Object.entries(mergeResult.merged.blockIndex)) {\n if (blockId === block.id) {\n blockByNodeId.set(nodeId, block);\n break;\n }\n }\n }\n\n // Replace existing blocks that were patched\n for (const nodeId of mergeResult.replaced) {\n const block = blockByNodeId.get(nodeId);\n if (block) {\n replaceBlockInFragment(fragment, block);\n }\n }\n\n // Append new blocks\n for (const nodeId of mergeResult.added) {\n const block = blockByNodeId.get(nodeId);\n if (block) {\n appendBlockToGroup(documentBlockGroup, block);\n }\n }\n}\n\n/**\n * Read all blocks (with their props) back out of the document fragment.\n *\n * The inverse of `writeCompiledBlocksToFragment` / `createBlockContainer`: walks the single\n * `blockGroup` and, for each `blockContainer`, returns `{ id, type, props }` where `props` is\n * the inner `blockContent` element's attributes — the **authoritative per-block prop store**\n * (the `qi.flow.nodes` map omits props, so this is the only place to recover them headlessly).\n *\n * `textColor`/`backgroundColor` are folded back into `props` only when non-`'default'`, so a\n * default-styled block round-trips to exactly its content props. Note: props written as `''`\n * are not persisted by `createBlockContainer`, so they do not reappear here.\n *\n * Returns `[]` when the fragment has no `blockGroup`.\n */\nexport function readBlocksFromFragment(fragment: Y.XmlFragment): CompiledBlock[] {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return [];\n\n const blocks: CompiledBlock[] = [];\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (!(container instanceof Y.XmlElement) || container.nodeName !== 'blockContainer') continue;\n\n const id = container.getAttribute('id');\n if (typeof id !== 'string' || id.length === 0) continue;\n\n const content = container.get(0);\n if (!(content instanceof Y.XmlElement)) continue;\n\n const props: Record<string, string> = { ...(content.getAttributes() as Record<string, string>) };\n\n // createBlockContainer hoists the color attrs onto the container and defaults them to\n // 'default'. Fold them back only when explicitly set, so a default block's props match\n // exactly what was written (no color noise).\n const textColor = container.getAttribute('textColor');\n if (typeof textColor === 'string' && textColor !== 'default') props.textColor = textColor;\n const backgroundColor = container.getAttribute('backgroundColor');\n if (typeof backgroundColor === 'string' && backgroundColor !== 'default') props.backgroundColor = backgroundColor;\n\n blocks.push({ id, type: content.nodeName, props });\n }\n\n return blocks;\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Create a blockContainer XmlElement from a CompiledBlock. */\nfunction createBlockContainer(block: CompiledBlock): Y.XmlElement {\n const blockContainer = new Y.XmlElement('blockContainer');\n const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;\n\n blockContainer.setAttribute('id', block.id);\n blockContainer.setAttribute('textColor', rawTextColor || 'default');\n blockContainer.setAttribute('backgroundColor', rawBackgroundColor || 'default');\n\n const blockContent = new Y.XmlElement(block.type);\n for (const [key, value] of Object.entries(contentProps)) {\n if (value !== '') {\n blockContent.setAttribute(key, value);\n }\n }\n\n blockContainer.insert(0, [blockContent]);\n return blockContainer;\n}\n\n/** Append a single block to a blockGroup. */\nfunction appendBlockToGroup(blockGroup: Y.XmlElement, block: CompiledBlock): void {\n const container = createBlockContainer(block);\n blockGroup.insert(blockGroup.length, [container]);\n}\n\nfunction getOrCreateDocumentBlockGroup(fragment: Y.XmlFragment): Y.XmlElement {\n if (fragment.length === 0) {\n const blockGroup = new Y.XmlElement('blockGroup');\n fragment.insert(0, [blockGroup]);\n return blockGroup;\n }\n\n if (fragment.length === 1) {\n const rootNode = fragment.get(0);\n if (rootNode instanceof Y.XmlElement && rootNode.nodeName === 'blockGroup') {\n return rootNode;\n }\n }\n\n throw new Error('Unexpected BlockNote document shape in XmlFragment. ' + 'Expected a single top-level blockGroup node.');\n}\n\n/** Get the existing blockGroup or null if the fragment is empty. */\nfunction getExistingBlockGroup(fragment: Y.XmlFragment): Y.XmlElement | null {\n if (fragment.length === 0) return null;\n\n if (fragment.length === 1) {\n const rootNode = fragment.get(0);\n if (rootNode instanceof Y.XmlElement && rootNode.nodeName === 'blockGroup') {\n return rootNode;\n }\n }\n\n return null;\n}\n","import type { Doc as YDoc, Map as YMap } from 'yjs';\nimport * as Y from 'yjs';\nimport type { CompiledFlow, CompiledFlowNode, CompiledEdge, CompiledBlock } from '../../types/baseUcan';\nimport { COMPILED_BLOCK_TYPE } from './blockMapping';\n\n/**\n * Read the current compiled flow state from a live Y.Doc.\n *\n * This is the inverse of `hydrateYDocFromCompiledFlow`. It extracts the flow\n * graph state from Yjs maps so that the pure merge/patch logic can operate\n * on plain objects.\n *\n * Returns `null` if the document has no flow state.\n */\nexport function readCompiledFlowFromYDoc(yDoc: YDoc): CompiledFlow | null {\n // ── qi.flow.meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n\n // ── qi.flow.nodes ──\n // Read this BEFORE deciding null. Old behavior returned null on empty\n // flowId, which broke the read for any flow whose plan was authored\n // with `flowId: \"\"` (the documented agent convention). The right\n // signal that the room has no flow is \"no nodes AND no meta,\" not\n // \"flowId is falsy.\"\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n const nodes: Record<string, CompiledFlowNode> = {};\n flowNodes.forEach((value, nodeId) => {\n if (value instanceof Y.Map) {\n nodes[nodeId] = yMapToFlowNode(value);\n }\n });\n\n if (flowNodes.size === 0 && flowMeta.size === 0) {\n return null;\n }\n\n const meta = {\n flowId: (flowMeta.get('flowId') as string) || '',\n title: (flowMeta.get('title') as string) || '',\n goal: flowMeta.get('goal') as string | undefined,\n version: (flowMeta.get('version') as string) || '',\n flowOwnerDid: (flowMeta.get('flowOwnerDid') as string) || '',\n flowUri: flowMeta.get('flowUri') as string | undefined,\n compiledAt: (flowMeta.get('compiledAt') as string) || '',\n compiledFrom: 'BaseUcanFlow' as const,\n };\n\n // ── qi.flow.edges ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n const edges: CompiledEdge[] = [];\n flowEdges.forEach((value) => {\n if (value instanceof Y.Map) {\n edges.push(yMapToEdge(value));\n }\n });\n\n // ── qi.flow.order ──\n const flowOrder = yDoc.getArray<string>('qi.flow.order');\n const order = flowOrder.toArray();\n\n // ── qi.flow.blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n const blockIndex: Record<string, string> = {};\n flowBlockIndex.forEach((value, key) => {\n blockIndex[key] = value as string;\n });\n\n // ── Reconstruct blocks from nodes (in topological order) ──\n const blocks: CompiledBlock[] = order\n .filter((nodeId) => nodes[nodeId])\n .map((nodeId) => {\n const node = nodes[nodeId];\n return {\n id: node.blockId,\n type: COMPILED_BLOCK_TYPE,\n props: { ...node.props },\n };\n });\n\n return { meta, blocks, nodes, edges, order, blockIndex };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\nfunction yMapToFlowNode(yMap: YMap<unknown>): CompiledFlowNode {\n return {\n id: (yMap.get('id') as string) || '',\n blockId: (yMap.get('blockId') as string) || '',\n can: (yMap.get('can') as string) || '',\n with: (yMap.get('with') as string) || '',\n registryType: (yMap.get('registryType') as string) || '',\n title: (yMap.get('title') as string) || '',\n description: (yMap.get('description') as string) || '',\n props: (yMap.get('props') as Record<string, string>) || {},\n phase: yMap.get('phase') as string | undefined,\n parallelGroup: yMap.get('parallelGroup') as string | undefined,\n actor: yMap.get('actor') as CompiledFlowNode['actor'],\n };\n}\n\nfunction yMapToEdge(yMap: YMap<unknown>): CompiledEdge {\n return {\n id: (yMap.get('id') as string) || '',\n source: (yMap.get('source') as string) || '',\n target: (yMap.get('target') as string) || '',\n // Only 'trigger' edges exist. Legacy 'dependency' edges from older\n // Y.Docs (before dependsOn was removed) get coerced — they'll be\n // overwritten on the next compile pass.\n kind: 'trigger',\n condition: yMap.get('condition') as CompiledEdge['condition'],\n };\n}\n","import type { CompiledFlow, CompiledFlowNode, CompiledEdge, CompiledBlock } from '../../types/baseUcan';\nimport { COMPILED_BLOCK_TYPE } from './blockMapping';\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/** Describes what changed when merging two compiled flows. */\nexport interface MergeResult {\n /** The merged compiled flow (full state). */\n merged: CompiledFlow;\n /** Node IDs that were added (new in incoming, not in existing). */\n added: string[];\n /** Node IDs that were replaced (patch only — existed and was overwritten). */\n replaced: string[];\n /** Node IDs that were kept unchanged from existing. */\n kept: string[];\n}\n\n/**\n * Merge an incoming compiled flow into an existing one.\n *\n * This is a **pure function** — no Yjs, no side effects.\n *\n * Strategies:\n * - `merge`: existing nodes win on ID collision. Incoming nodes with new IDs\n * are added. Existing nodes are never modified.\n * - `patch`: incoming nodes overwrite existing nodes on ID collision. Incoming\n * nodes with new IDs are added. Existing nodes not in incoming are kept.\n *\n * Edges in the merged result are the union of edges from both sides, filtered\n * to those whose source and target both exist in the merged node set, with\n * duplicates collapsed by edge id. Order is the merged node insertion order\n * (existing first, then newly added) — there is no topological sort because\n * there is no inferred dependency relationship.\n */\nexport function mergeCompiledFlows(existing: CompiledFlow, incoming: CompiledFlow, strategy: 'merge' | 'patch'): MergeResult {\n const added: string[] = [];\n const replaced: string[] = [];\n const kept: string[] = [];\n\n // Build the merged node set\n const mergedNodes: Record<string, CompiledFlowNode> = {};\n const mergedBlockIndex: Record<string, string> = {};\n\n // Start with existing nodes\n for (const [nodeId, node] of Object.entries(existing.nodes)) {\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = existing.blockIndex[nodeId];\n }\n\n // Apply incoming nodes based on strategy\n for (const [nodeId, node] of Object.entries(incoming.nodes)) {\n if (mergedNodes[nodeId]) {\n if (strategy === 'patch') {\n // Patch: incoming overwrites existing\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];\n replaced.push(nodeId);\n } else {\n // Merge: existing wins, skip incoming\n kept.push(nodeId);\n }\n } else {\n // New node in both strategies\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];\n added.push(nodeId);\n }\n }\n\n // Mark existing nodes that weren't replaced as kept\n for (const nodeId of Object.keys(existing.nodes)) {\n if (!replaced.includes(nodeId)) {\n kept.push(nodeId);\n }\n }\n\n // Merge edges from both sides, filter to those whose endpoints survive,\n // dedupe by id (last write wins on dupes — irrelevant since edges are\n // content-derived from trigger props and identical inputs produce identical\n // edge ids).\n const edgeMap = new Map<string, CompiledEdge>();\n for (const edge of [...existing.edges, ...incoming.edges]) {\n if (mergedNodes[edge.source] && mergedNodes[edge.target]) {\n edgeMap.set(edge.id, edge);\n }\n }\n const edges = Array.from(edgeMap.values());\n\n // Order = the natural insertion order of the merged node map\n // (existing first, then newly added). No topological sort.\n const order = Object.keys(mergedNodes);\n\n // Build blocks array in the same order\n const blocks: CompiledBlock[] = order.map((nodeId) => {\n const node = mergedNodes[nodeId];\n return {\n id: node.blockId,\n type: COMPILED_BLOCK_TYPE,\n props: { ...node.props },\n };\n });\n\n // Use incoming meta (newer timestamp) but preserve existing flowId\n const meta = {\n ...incoming.meta,\n flowId: existing.meta.flowId,\n compiledAt: new Date().toISOString(),\n };\n\n return {\n merged: { meta, blocks, nodes: mergedNodes, edges, order, blockIndex: mergedBlockIndex },\n added,\n replaced,\n kept,\n };\n}\n","import type { BaseUcanFlow, CompiledFlow, CompiledFlowNode, FlowCapability, ActorConstraint, TTLConstraint, TriggerSpec } from '../../types/baseUcan';\n\n/**\n * Reconstruct a BaseUcanFlow plan from a CompiledFlow.\n *\n * This is the inverse of `compileBaseUcanFlow`. It allows the AI agent to\n * read the current flow in the same format it writes — a plain capability\n * list it can reason about, modify, and pass back to the compiler.\n *\n * This is a **pure function** — no Yjs, no side effects.\n *\n * Note: some information is lossy (e.g. conditions are stored as a JSON\n * string in props and are not fully round-tripped back to ConditionRef).\n * The core capability data (can, with, nb, trigger, actor, ttl, metadata)\n * is fully preserved.\n */\nexport function decompileToBaseUcanFlow(compiled: CompiledFlow): BaseUcanFlow {\n // Reverse of the compiler's blockIndex (blockId → nodeId), used to map\n // trigger source references — serialized as block ids in props.trigger\n // for the runtime reconciler — back into the node-id namespace the plan\n // format uses (and the compiler validates against).\n const nodeIdByBlockId: Record<string, string> = {};\n for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {\n nodeIdByBlockId[blockId] = nodeId;\n }\n\n const capabilities: FlowCapability[] = compiled.order.map((nodeId) => {\n const node = compiled.nodes[nodeId];\n return nodeToCapability(node, nodeIdByBlockId);\n });\n\n return {\n kind: 'qi.flow.base-ucan',\n version: '1.0',\n flowId: compiled.meta.flowId,\n title: compiled.meta.title,\n goal: compiled.meta.goal,\n meta: {\n rootIssuer: compiled.meta.flowOwnerDid || undefined,\n flowUri: compiled.meta.flowUri,\n },\n capabilities,\n };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\nfunction nodeToCapability(node: CompiledFlowNode, nodeIdByBlockId: Record<string, string>): FlowCapability {\n const cap: FlowCapability = {\n id: node.id,\n can: node.can,\n with: node.with,\n };\n\n // ── nb (caveats) — stored as JSON string in props.inputs ──\n if (node.props.inputs) {\n try {\n const nb = JSON.parse(node.props.inputs);\n if (nb && typeof nb === 'object' && Object.keys(nb).length > 0) {\n cap.nb = nb;\n }\n } catch {\n // props.inputs wasn't valid JSON — skip\n }\n }\n\n // ── Workflow topology ──\n if (node.parallelGroup) {\n cap.parallelGroup = node.parallelGroup;\n }\n\n if (node.phase) {\n cap.phase = node.phase;\n }\n\n // ── Authorization ──\n if (node.actor) {\n cap.actor = { ...node.actor } as ActorConstraint;\n }\n\n // ── TTL — stored in individual props ──\n const ttl: TTLConstraint = {};\n if (node.props.ttlAbsoluteDueDate) ttl.absoluteDueDate = node.props.ttlAbsoluteDueDate;\n if (node.props.ttlFromEnablement) ttl.fromEnablement = node.props.ttlFromEnablement;\n if (node.props.ttlFromCommitment) ttl.fromCommitment = node.props.ttlFromCommitment;\n if (Object.keys(ttl).length > 0) {\n cap.ttl = ttl;\n }\n\n // ── Trigger — stored as JSON string in props.trigger ──\n // Mirrors how `nb` round-trips through props.inputs. Empty / missing /\n // unparseable trigger means manual (the compiler treats absent trigger\n // as type='manual'), so we omit the field in that case to keep the\n // round-tripped plan minimal.\n if (typeof node.props.trigger === 'string' && node.props.trigger.length > 0) {\n try {\n const trigger = JSON.parse(node.props.trigger) as Partial<TriggerSpec>;\n if (trigger && typeof trigger === 'object' && typeof trigger.type === 'string') {\n cap.trigger = triggerToNodeIds(trigger as TriggerSpec, nodeIdByBlockId);\n }\n } catch {\n // props.trigger wasn't valid JSON — skip, treat as manual\n }\n }\n\n // ── Human-facing metadata ──\n // Title: only set if it differs from the `can` string (compiler falls back to can)\n if (node.title && node.title !== node.can) {\n cap.title = node.title;\n }\n\n if (node.description) {\n cap.description = node.description;\n }\n\n if (node.props.icon) {\n cap.icon = node.props.icon;\n }\n\n return cap;\n}\n\n/**\n * Map trigger source references from the block-id namespace back to node\n * ids so the round-tripped plan validates against the compiler. Ids with\n * no reverse-index entry pass through unchanged — that covers documents\n * compiled before the compiler remapped trigger sources, whose triggers\n * already carry node ids.\n */\nfunction triggerToNodeIds(trigger: TriggerSpec, nodeIdByBlockId: Record<string, string>): TriggerSpec {\n if (trigger.type === 'block.event' && trigger.sourceBlockId) {\n return { ...trigger, sourceBlockId: nodeIdByBlockId[trigger.sourceBlockId] ?? trigger.sourceBlockId };\n }\n if (trigger.type === 'block.event.all' && trigger.sources) {\n return {\n ...trigger,\n sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: nodeIdByBlockId[src.sourceBlockId] ?? src.sourceBlockId })),\n };\n }\n return trigger;\n}\n","import * as Y from 'yjs';\nimport { MatrixProvider } from '@ixo/matrix-crdt';\nimport type { MatrixClient } from 'matrix-js-sdk';\nimport type { BaseUcanFlow, CompiledFlow, FlowStrategy } from '../../types/baseUcan';\nimport { compileBaseUcanFlow } from './compiler';\nimport { hydrateYDocFromCompiledFlow, initializeRuntime, clearFlowState, hydrateYDocFromMergeResult, initializeRuntimeForNodes } from './hydrate';\nimport { getActionByCan } from '../actionRegistry';\nimport { writeCompiledBlocksToFragment, removeAllFlowBlocks, applyMergeResultToFragment } from './documentFragment';\nimport { readCompiledFlowFromYDoc } from './readFlow';\nimport { mergeCompiledFlows } from './mergeFlows';\nimport { decompileToBaseUcanFlow } from './decompile';\n\n// ─── Public Types ───────────────────────────────────────────────────────────\n\nexport interface SetupFlowOptions {\n /** The Base UCAN flow plan to compile. */\n plan: BaseUcanFlow;\n /** Matrix room ID to hydrate the flow into. */\n roomId: string;\n /** Authenticated Matrix client. */\n matrixClient: MatrixClient;\n /** DID of the user setting up the flow. */\n creatorDid: string;\n /** Optional doc ID override (defaults to plan.flowId). */\n docId?: string;\n /**\n * Room ID of the template this flow was instantiated from, if any.\n * Recorded into the root map as `source_template_id` for lineage tracking.\n */\n templateId?: string;\n /**\n * How to apply the plan to the existing document.\n * - `full` (default): wipe existing flow state and rebuild entirely.\n * - `merge`: keep existing blocks, add new capabilities from the plan.\n * - `patch`: replace matching nodes, add new ones, keep the rest.\n */\n strategy?: FlowStrategy;\n}\n\nexport interface SetupFlowResult {\n /** The compiled flow artifacts. */\n compiled: CompiledFlow;\n /** The room ID (same as input, for convenience). */\n roomId: string;\n /** The flow ID from the plan. */\n flowId: string;\n}\n\nexport interface ReadFlowOptions {\n /** Matrix room ID to read from. */\n roomId: string;\n /** Authenticated Matrix client. */\n matrixClient: MatrixClient;\n}\n\nexport interface ReadFlowResult {\n /** The current flow plan in BaseUcanFlow format (what the agent reads/writes). */\n plan: BaseUcanFlow;\n /** The compiled flow state (lower-level representation). */\n compiled: CompiledFlow;\n /** The room ID (same as input, for convenience). */\n roomId: string;\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * Read the current Base UCAN flow plan from a Matrix room.\n *\n * Connects to the room, reads the Y.Doc, decompiles the flow state\n * back into a `BaseUcanFlow`, and disconnects. Returns `null` if the\n * room has no flow state.\n *\n * **This is the lower-level API.** It exists for cases where you need\n * to read a flow from a room you are NOT currently editing — e.g.\n * cross-room operations or background reads. For the common case of\n * \"read the flow the user is currently looking at,\" use\n * `readFlowFromEditor(editor)` instead. That function takes no\n * parameters from the agent and reads from the editor's existing\n * Y.Doc directly — no Matrix connection, no async, no room ID\n * resolution. The browser tool that exposes `read_flow` to the AI\n * agent should wrap `readFlowFromEditor`, not this function.\n */\nexport async function readFlowAsBaseUcan(options: ReadFlowOptions): Promise<ReadFlowResult | null> {\n const { roomId, matrixClient } = options;\n\n const { yDoc, provider } = await connectToRoom(roomId, matrixClient);\n\n try {\n const compiled = readCompiledFlowFromYDoc(yDoc);\n if (!compiled) return null;\n\n const plan = decompileToBaseUcanFlow(compiled);\n\n return { plan, compiled, roomId };\n } finally {\n provider.dispose();\n yDoc.destroy();\n }\n}\n\n/**\n * Minimal editor shape required by `readFlowFromEditor` and the active\n * editor registry. The full `IxoEditorType` is fine to pass — this is\n * just a structural lower bound so test harnesses can construct fake\n * editors without pulling in React dependencies.\n */\nexport interface ReadableEditor {\n _yDoc?: import('yjs').Doc;\n getRoomId?: () => string;\n}\n\n/**\n * Read the current flow from a specific editor instance, synchronously.\n *\n * Use this when you have an editor reference in hand (e.g. from inside a\n * React component, a test, or a multi-editor host that needs to target a\n * specific instance). For the common case of \"read the flow the user is\n * currently looking at,\" prefer the parameterless `readFlow()` below — it\n * uses the active editor registry so you don't have to thread an editor\n * reference through your call sites.\n *\n * Returns `null` ONLY when the editor's Y.Doc has no flow state at all\n * (no nodes AND no meta). An empty `flowId` string is no longer treated\n * as \"no flow\" — that was the historical bug where successful\n * `setup_flow` calls authored with `flowId: \"\"` (the documented agent\n * convention) showed up as null on subsequent reads.\n */\nexport function readFlowFromEditor(editor: ReadableEditor): ReadFlowResult | null {\n const yDoc = editor._yDoc;\n if (!yDoc) return null;\n\n const compiled = readCompiledFlowFromYDoc(yDoc);\n if (!compiled) return null;\n\n const plan = decompileToBaseUcanFlow(compiled);\n const roomId = editor.getRoomId?.() || '';\n\n return { plan, compiled, roomId };\n}\n\n// ─── Active editor registry ─────────────────────────────────────────────────\n//\n// Module-level state holding the editor instance the user is currently\n// interacting with. The collaborative editor mount hook\n// (`useCreateCollaborativeIxoEditor`) registers the editor on mount and\n// clears it on unmount.\n//\n// The registry exists so that exported library functions like `readFlow()`\n// and any agent browser tool can be parameterless. The agent doesn't have\n// to pass an editor reference; the editor package keeps track of which\n// instance is live.\n//\n// **Single-editor assumption.** This is a singleton. If a host app ever\n// mounts two editors in the same JS context, only the most recently\n// registered one is reachable through `readFlow()`. Use\n// `readFlowFromEditor(editor)` (the explicit form) when you need to target\n// a specific instance — tests and multi-editor hosts both go this route.\n\nlet activeEditor: ReadableEditor | null = null;\n\n/**\n * Register an editor as the current active editor. Called by the editor's\n * mount hook when the document is connected and ready. Pass `null` on\n * unmount to clear the registry.\n *\n * If a different editor is already registered, it is replaced silently —\n * the most recent registration wins. This matches the single-editor\n * assumption above.\n */\nexport function setActiveEditor(editor: ReadableEditor | null): void {\n activeEditor = editor;\n}\n\n/**\n * Get the currently registered active editor, or null if none is set.\n * Provided for cases where a caller wants to check the registry directly\n * (e.g. for diagnostics) without going through `readFlow()`.\n */\nexport function getActiveEditor(): ReadableEditor | null {\n return activeEditor;\n}\n\n/**\n * Read the current flow from the active editor, with no parameters at all.\n *\n * This is the parameterless API the AI agent's `read_flow` browser tool\n * should wrap. The browser tool literally becomes `read_flow: () => readFlow()`.\n *\n * Returns `null` if there is no active editor registered (e.g. the editor\n * hasn't finished mounting yet, or no editor is open in this JS context),\n * OR if the active editor's Y.Doc has no flow state at all.\n *\n * If `null` is returned and the user is referencing an existing flow, that\n * is a hard signal to STOP and report to the user — never silently rebuild,\n * because the duplicate-blocks bug is the inevitable consequence.\n */\nexport function readFlow(): ReadFlowResult | null {\n if (!activeEditor) {\n console.warn('[readFlow] No active editor registered. Did the editor finish mounting?');\n return null;\n }\n return readFlowFromEditor(activeEditor);\n}\n\n/**\n * One-shot function that compiles a Base UCAN flow plan and writes it\n * into a Matrix room's Y.Doc. After this completes, the room is a\n * normal flow that anyone can open via `useCreateCollaborativeIxoEditor`.\n *\n * Supports three strategies:\n * - `full` (default): clears any existing flow and rebuilds from scratch.\n * - `merge`: adds new capabilities alongside existing ones.\n * - `patch`: replaces matching nodes and adds new ones.\n */\nexport async function setupFlowFromBaseUcan(options: SetupFlowOptions): Promise<SetupFlowResult> {\n const { plan: rawPlan, roomId, matrixClient, creatorDid, docId, templateId, strategy = 'full' } = options;\n\n // The agent convention is \"leave flowId empty — set at instantiation.\"\n // The runtime is responsible for honoring that. If the plan came in with\n // an empty flowId, fill it from docId or roomId so the resulting Y.Doc\n // has a non-empty `qi.flow.meta.flowId`. Without this, downstream reads\n // that check the flowId field as a presence signal would silently treat\n // a real flow as missing — which was the read_flow null bug.\n const plan = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: docId || roomId };\n\n // 1. Compile the incoming plan (pure, synchronous)\n const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });\n\n // 2. Connect to the Matrix room\n const { yDoc, provider } = await connectToRoom(roomId, matrixClient);\n\n let finalCompiled: CompiledFlow;\n\n try {\n const root = yDoc.getMap('root');\n const fragment = yDoc.getXmlFragment('document');\n const existingFlow = readCompiledFlowFromYDoc(yDoc);\n\n if (strategy === 'full') {\n // ── Full strategy: clear existing state and rebuild ──\n if (existingFlow) {\n clearFlowState(yDoc);\n removeAllFlowBlocks(fragment);\n // Clear runtime\n const runtime = yDoc.getMap('runtime');\n runtime.forEach((_, key) => runtime.delete(key));\n }\n\n // Set metadata\n setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);\n\n hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);\n\n const runtimeMap = yDoc.getMap('runtime');\n initializeRuntime(runtimeMap, incomingCompiled);\n\n yDoc.transact(() => {\n writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);\n });\n\n finalCompiled = incomingCompiled;\n } else {\n // ── Merge / Patch strategy ──\n if (!existingFlow) {\n // No existing flow — fall back to full behavior\n setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);\n\n hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);\n\n const runtimeMap = yDoc.getMap('runtime');\n initializeRuntime(runtimeMap, incomingCompiled);\n\n yDoc.transact(() => {\n writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);\n });\n\n finalCompiled = incomingCompiled;\n } else {\n // Merge or patch the incoming plan into the existing flow\n const mergeResult = mergeCompiledFlows(existingFlow, incomingCompiled, strategy);\n\n hydrateYDocFromMergeResult(yDoc, mergeResult);\n\n const runtimeMap = yDoc.getMap('runtime');\n const nodesToInit = [...mergeResult.added, ...mergeResult.replaced];\n initializeRuntimeForNodes(runtimeMap, mergeResult.merged, nodesToInit);\n\n yDoc.transact(() => {\n applyMergeResultToFragment(fragment, mergeResult);\n });\n\n finalCompiled = mergeResult.merged;\n }\n }\n\n // Wait for the provider to flush all writes to Matrix\n await provider.waitForFlush();\n } finally {\n provider.dispose();\n yDoc.destroy();\n }\n\n return {\n compiled: finalCompiled,\n roomId,\n flowId: plan.flowId,\n };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Connect to a Matrix room and return a synced Y.Doc + provider. */\nasync function connectToRoom(roomId: string, matrixClient: MatrixClient): Promise<{ yDoc: Y.Doc; provider: MatrixProvider }> {\n const yDoc = new Y.Doc();\n\n const client = matrixClient;\n (client as any).canSupportVoip = false;\n (client as any).clientOpts = { lazyLoadMembers: true };\n\n const provider = new MatrixProvider(\n yDoc,\n client,\n { type: 'id', id: roomId },\n {\n translator: {\n updateEventType: 'matrix-crdt.doc_update',\n snapshotEventType: 'matrix-crdt.doc_snapshot',\n },\n enableExperimentalWebrtcSync: false,\n enableAwareness: false,\n reader: { snapshotInterval: 10 },\n writer: { flushInterval: 300, retryIfForbiddenInterval: 30000 },\n }\n );\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Timed out connecting to room ${roomId}`));\n }, 30000);\n\n provider.onDocumentAvailable(() => {\n clearTimeout(timeout);\n resolve();\n });\n\n provider.onDocumentUnavailable(() => {\n clearTimeout(timeout);\n reject(new Error(`Room ${roomId} is unavailable`));\n });\n\n provider.initialize().catch((err: Error) => {\n clearTimeout(timeout);\n reject(err);\n });\n });\n\n return { yDoc, provider };\n}\n\n/** Set root metadata on the Y.Doc (shared between full and fallback paths). */\nfunction setRootMetadata(yDoc: Y.Doc, root: Y.Map<unknown>, plan: BaseUcanFlow, creatorDid: string, docId?: string, templateId?: string): void {\n yDoc.transact(() => {\n if (!root.get('@context')) root.set('@context', 'https://ixo.world/flow/0.3');\n if (!root.get('_type')) root.set('_type', 'ixo.flow.crdt');\n if (!root.get('schema_version')) root.set('schema_version', '0.3');\n if (!root.get('doc_id')) root.set('doc_id', docId || plan.flowId);\n if (!root.get('createdAt')) root.set('createdAt', new Date().toISOString());\n if (!root.get('createdBy')) root.set('createdBy', creatorDid);\n root.set('flowOwnerDid', creatorDid);\n\n // Template lineage — record alongside doc_id, never overwriting an\n // existing value (e.g. one stamped at clone time).\n if (templateId && !root.get('source_template_id')) {\n root.set('source_template_id', templateId);\n }\n\n const titleText = yDoc.getText('title');\n if (titleText.length === 0 && plan.title) {\n titleText.insert(0, plan.title);\n }\n });\n}\n","import type { Map as YMap, Doc as YDoc } from 'yjs';\nimport * as Y from 'yjs';\nimport type { CompiledFlow, CompiledFlowNode } from '../../types/baseUcan';\nimport type { MergeResult } from './mergeFlows';\n\n/**\n * Insert compiled flow artifacts into a live collaborative editor's Y.Doc.\n *\n * This function:\n * 1. Populates qi.flow.* Yjs maps with graph state\n * 2. Returns the compiled blocks for insertion into BlockNote\n *\n * Should be called ONCE when the editor connects to an empty document.\n *\n * Note: Block insertion into BlockNote must be done by the caller via\n * `editor.insertBlocks()` because BlockNote's API is not accessible here\n * without pulling in React dependencies.\n */\nexport function hydrateYDocFromCompiledFlow(yDoc: YDoc, compiled: CompiledFlow): void {\n yDoc.transact(() => {\n // ── qi.flow.meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n for (const [key, value] of Object.entries(compiled.meta)) {\n if (value !== undefined) {\n flowMeta.set(key, value);\n }\n }\n\n // ── qi.flow.nodes ──\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n for (const [nodeId, node] of Object.entries(compiled.nodes)) {\n flowNodes.set(nodeId, createYMapFromNode(node));\n }\n\n // ── qi.flow.edges ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n for (const edge of compiled.edges) {\n const yEdge = new Y.Map();\n yEdge.set('id', edge.id);\n yEdge.set('source', edge.source);\n yEdge.set('target', edge.target);\n yEdge.set('kind', edge.kind);\n if (edge.condition) yEdge.set('condition', edge.condition);\n flowEdges.set(edge.id, yEdge);\n }\n\n // ── qi.flow.order ──\n const flowOrder = yDoc.getArray('qi.flow.order');\n for (const nodeId of compiled.order) {\n flowOrder.push([nodeId]);\n }\n\n // ── qi.flow.blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {\n flowBlockIndex.set(nodeId, blockId);\n }\n });\n}\n\n/**\n * Clear all flow graph state from a Y.Doc.\n * Used by the `full` strategy before rebuilding.\n */\nexport function clearFlowState(yDoc: YDoc): void {\n yDoc.transact(() => {\n const flowMeta = yDoc.getMap('qi.flow.meta');\n flowMeta.forEach((_, key) => flowMeta.delete(key));\n\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n flowNodes.forEach((_, key) => flowNodes.delete(key));\n\n const flowEdges = yDoc.getMap('qi.flow.edges');\n flowEdges.forEach((_, key) => flowEdges.delete(key));\n\n const flowOrder = yDoc.getArray('qi.flow.order');\n if (flowOrder.length > 0) {\n flowOrder.delete(0, flowOrder.length);\n }\n\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n flowBlockIndex.forEach((_, key) => flowBlockIndex.delete(key));\n });\n}\n\n/**\n * Apply a MergeResult to the Y.Doc's flow graph state.\n *\n * - Added nodes: create new Y.Map entries\n * - Replaced nodes: delete + recreate with new data\n * - Kept nodes: untouched\n * - Edges: cleared entirely and rewritten from the merged trigger edges\n * - Order: cleared and rewritten as the merged node insertion order\n */\nexport function hydrateYDocFromMergeResult(yDoc: YDoc, mergeResult: MergeResult): void {\n const { merged, added, replaced } = mergeResult;\n\n yDoc.transact(() => {\n // ── Update meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n for (const [key, value] of Object.entries(merged.meta)) {\n if (value !== undefined) {\n flowMeta.set(key, value);\n }\n }\n\n // ── Add / replace nodes ──\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n for (const nodeId of replaced) {\n flowNodes.delete(nodeId);\n flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));\n }\n for (const nodeId of added) {\n flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));\n }\n\n // ── Rewrite edges (derived state — always recompute) ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n flowEdges.forEach((_, key) => flowEdges.delete(key));\n for (const edge of merged.edges) {\n const yEdge = new Y.Map();\n yEdge.set('id', edge.id);\n yEdge.set('source', edge.source);\n yEdge.set('target', edge.target);\n yEdge.set('kind', edge.kind);\n if (edge.condition) yEdge.set('condition', edge.condition);\n flowEdges.set(edge.id, yEdge);\n }\n\n // ── Rewrite order (derived state — always recompute) ──\n const flowOrder = yDoc.getArray('qi.flow.order');\n if (flowOrder.length > 0) {\n flowOrder.delete(0, flowOrder.length);\n }\n for (const nodeId of merged.order) {\n flowOrder.push([nodeId]);\n }\n\n // ── Update blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n for (const nodeId of [...added, ...replaced]) {\n flowBlockIndex.set(nodeId, merged.blockIndex[nodeId]);\n }\n });\n}\n\n/**\n * Initialize runtime state for all compiled nodes.\n * Sets each node to 'idle' state in the runtime Y.Map.\n */\nexport function initializeRuntime(runtimeMap: YMap<unknown>, compiled: CompiledFlow): void {\n for (const nodeId of compiled.order) {\n runtimeMap.set(compiled.blockIndex[nodeId], { state: 'idle' });\n }\n}\n\n/**\n * Initialize runtime state for specific nodes only.\n * Used by merge/patch strategies to only initialize new or replaced nodes.\n */\nexport function initializeRuntimeForNodes(runtimeMap: YMap<unknown>, compiled: CompiledFlow, nodeIds: string[]): void {\n for (const nodeId of nodeIds) {\n const blockId = compiled.blockIndex[nodeId];\n if (blockId) {\n runtimeMap.set(blockId, { state: 'idle' });\n }\n }\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Create a Y.Map from a CompiledFlowNode. */\nexport function createYMapFromNode(node: CompiledFlowNode): Y.Map<unknown> {\n const yNode = new Y.Map();\n yNode.set('id', node.id);\n yNode.set('blockId', node.blockId);\n yNode.set('can', node.can);\n yNode.set('with', node.with);\n yNode.set('registryType', node.registryType);\n yNode.set('title', node.title);\n yNode.set('description', node.description);\n if (node.phase) yNode.set('phase', node.phase);\n if (node.parallelGroup) yNode.set('parallelGroup', node.parallelGroup);\n if (node.actor) yNode.set('actor', node.actor);\n return yNode;\n}\n","import * as Y from 'yjs';\nimport type { Doc } from 'yjs';\nimport type { FlowAgentCommand, FlowAgentLedgerEvent, FlowAgentLedgerEventType, FlowAgentMaps } from '../../types/flowAgent';\nimport { createIntentHash, stableStringify } from './utils';\n\nexport const FLOW_AGENT_OUTBOX_KEY = 'agentOutbox';\nexport const FLOW_AGENT_LEASES_KEY = 'agentLeases';\nexport const FLOW_AGENT_AUDIT_SCOPE = '__flow_agent__';\n\nexport function getFlowAgentMaps(yDoc: Doc): FlowAgentMaps {\n return {\n outbox: yDoc.getMap<FlowAgentCommand>(FLOW_AGENT_OUTBOX_KEY),\n leases: yDoc.getMap(FLOW_AGENT_LEASES_KEY),\n };\n}\n\nexport function computeAgentCommandId(params: { flowId: string; nodeId: string; type: string; payload: Record<string, unknown> }): string {\n const intentHash = createIntentHash(params);\n return `${params.flowId}:${params.nodeId}:${intentHash}`;\n}\n\nexport function queueAgentCommand(yDoc: Doc, command: FlowAgentCommand): { command: FlowAgentCommand; created: boolean } {\n const { outbox } = getFlowAgentMaps(yDoc);\n const existing = outbox.get(command.id);\n if (existing) {\n const retryFailedAssignment = existing.type === 'assign_actor' && existing.status === 'failed';\n const retryFailedDiagnosis = existing.type === 'diagnose_blocker' && existing.status === 'failed';\n const retryUnprovenDiagnosis = existing.type === 'diagnose_blocker' && existing.status === 'confirmed' && typeof existing.payload.delegatedInvocationId !== 'string';\n if (retryFailedAssignment || retryFailedDiagnosis || retryUnprovenDiagnosis) {\n const retried: FlowAgentCommand = {\n ...existing,\n status: 'queued',\n error: undefined,\n lease: undefined,\n reason: command.reason,\n payload: command.payload,\n capability: command.capability,\n actorDid: command.actorDid,\n updatedAt: command.updatedAt,\n };\n outbox.set(command.id, retried);\n try {\n appendAgentLedgerEvent(yDoc, {\n type: 'agent.command',\n flowId: retried.flowId,\n nodeId: retried.nodeId,\n commandId: retried.id,\n actorDid: retried.actorDid,\n timestamp: retried.updatedAt,\n details: {\n commandType: retried.type,\n status: retried.status,\n idempotencyKey: retried.idempotencyKey,\n reason: retried.reason,\n retry: true,\n retryCause: retryFailedDiagnosis ? 'diagnosis_failed' : retryUnprovenDiagnosis ? 'missing_delegated_invocation' : 'assignment_failed',\n },\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (!message.includes('Unexpected content type') && !message.includes('already been defined with a different constructor')) {\n throw error;\n }\n }\n return { command: retried, created: true };\n }\n return { command: existing, created: false };\n }\n outbox.set(command.id, command);\n try {\n appendAgentLedgerEvent(yDoc, {\n type: 'agent.command',\n flowId: command.flowId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: command.actorDid,\n timestamp: command.createdAt,\n details: {\n commandType: command.type,\n status: command.status,\n idempotencyKey: command.idempotencyKey,\n reason: command.reason,\n },\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (!message.includes('Unexpected content type') && !message.includes('already been defined with a different constructor')) {\n throw error;\n }\n }\n return { command, created: true };\n}\n\nexport function readQueuedAgentCommands(yDoc: Doc): FlowAgentCommand[] {\n const { outbox } = getFlowAgentMaps(yDoc);\n const commands: FlowAgentCommand[] = [];\n outbox.forEach((command) => {\n if (command.status === 'queued' || command.status === 'leased' || command.status === 'running') {\n commands.push(command);\n }\n });\n commands.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));\n return commands;\n}\n\nexport function updateAgentCommand(yDoc: Doc, commandId: string, patch: Partial<FlowAgentCommand>): FlowAgentCommand | null {\n const { outbox } = getFlowAgentMaps(yDoc);\n const current = outbox.get(commandId);\n if (!current) return null;\n const next = { ...current, ...patch };\n outbox.set(commandId, next);\n return next;\n}\n\nexport function appendAgentLedgerEvent(\n yDoc: Doc,\n event: Omit<FlowAgentLedgerEvent, 'id'> & {\n id?: string;\n }\n): FlowAgentLedgerEvent {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n let arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);\n if (!arr) {\n arr = new Y.Array<unknown>();\n auditMap.set(FLOW_AGENT_AUDIT_SCOPE, arr);\n }\n\n const fullEvent: FlowAgentLedgerEvent = {\n id: event.id || `${event.type}:${event.commandId || event.nodeId || 'flow'}:${createIntentHash(event.details)}:${event.timestamp}`,\n type: event.type,\n flowId: event.flowId,\n actorDid: event.actorDid,\n timestamp: event.timestamp,\n details: JSON.parse(stableStringify(event.details)) as Record<string, unknown>,\n };\n\n if (event.nodeId) fullEvent.nodeId = event.nodeId;\n if (event.commandId) fullEvent.commandId = event.commandId;\n\n arr.push([\n {\n id: fullEvent.id,\n type: fullEvent.type,\n details: fullEvent,\n meta: {\n timestamp: new Date(fullEvent.timestamp).toISOString(),\n userId: fullEvent.actorDid,\n editable: false,\n },\n },\n ]);\n\n return fullEvent;\n}\n\nexport function readAgentLedgerEvents(yDoc: Doc, eventType?: FlowAgentLedgerEventType): FlowAgentLedgerEvent[] {\n const auditMap = yDoc.getMap<Y.Array<unknown>>('auditTrail');\n const arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);\n if (!arr) return [];\n const events: FlowAgentLedgerEvent[] = [];\n arr.forEach((value) => {\n if (!value || typeof value !== 'object') return;\n const entry = value as { type?: string; details?: FlowAgentLedgerEvent };\n if (!entry.details) return;\n if (eventType && entry.details.type !== eventType) return;\n events.push(entry.details);\n });\n events.sort((a, b) => a.timestamp - b.timestamp || a.id.localeCompare(b.id));\n return events;\n}\n","import type { Block } from '@blocknote/core';\nimport type { UcanCapability } from '../../types/ucan';\n\nexport function stableStringify(value: unknown): string {\n if (value === undefined) return 'null';\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b));\n return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`).join(',')}}`;\n}\n\nexport function fnv1a32(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\nexport function createIntentHash(intent: Record<string, unknown>): string {\n return fnv1a32(stableStringify(intent));\n}\n\nexport function parseJsonProp<T>(value: unknown, fallback: T): T {\n if (value == null || value === '') return fallback;\n if (typeof value === 'object') return value as T;\n if (typeof value !== 'string') return fallback;\n try {\n const parsed = JSON.parse(value);\n return parsed as T;\n } catch {\n return fallback;\n }\n}\n\nexport function getBlockActionType(block: unknown): string | undefined {\n const props = (block as { props?: Record<string, unknown> })?.props;\n const actionType = props?.actionType;\n return typeof actionType === 'string' && actionType.length > 0 ? actionType : undefined;\n}\n\nexport function getBlockTitle(block: unknown): string | undefined {\n const props = (block as { props?: Record<string, unknown> })?.props;\n const title = props?.title;\n return typeof title === 'string' && title.length > 0 ? title : undefined;\n}\n\nexport function getBlockType(block: unknown): string {\n const type = (block as { type?: string })?.type;\n return typeof type === 'string' && type.length > 0 ? type : 'block';\n}\n\nexport function getBlockProps(block: unknown): Record<string, unknown> {\n return ((block as { props?: Record<string, unknown> })?.props || {}) as Record<string, unknown>;\n}\n\nexport function getBlockId(block: unknown): string | undefined {\n const id = (block as { id?: string })?.id;\n return typeof id === 'string' && id.length > 0 ? id : undefined;\n}\n\nexport function getAssigneeDid(block: unknown): string | undefined {\n const props = getBlockProps(block);\n const assignment = parseJsonProp<Record<string, any>>(props.assignment, {});\n const did = assignment?.assignedActor?.did;\n return typeof did === 'string' && did.length > 0 ? did : undefined;\n}\n\nexport function getDueAt(block: unknown): number | undefined {\n const props = getBlockProps(block);\n const ttlAbsoluteDueDate = props.ttlAbsoluteDueDate;\n if (typeof ttlAbsoluteDueDate !== 'string' || ttlAbsoluteDueDate.length === 0) return undefined;\n const parsed = new Date(ttlAbsoluteDueDate).getTime();\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nexport function normalizeBlocks(blocks: unknown[]): Block[] {\n return blocks.filter((block) => typeof getBlockId(block) === 'string') as Block[];\n}\n\nexport function capabilityForCommand(can: string, flowUri: string, nodeId: string): UcanCapability {\n return {\n can,\n with: `${flowUri}:${nodeId}`,\n };\n}\n","import type { FlowAgentCommandType, FlowAgentPolicyDecision } from '../../types/flowAgent';\nimport type { StoredDelegation, UcanCapability } from '../../types/ucan';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { capabilityForCommand } from './utils';\n\nconst COMMAND_CAPABILITIES: Record<FlowAgentCommandType, string> = {\n diagnose_blocker: 'flow/observe',\n assign_actor: 'flow/node/assign',\n notify_actor: 'flow/notify',\n execute_action: 'flow/node/execute',\n validate_external_state: 'flow/mutation/execute',\n archive_flow: 'flow/archive',\n propose_config_change: 'flow/config/propose',\n};\n\nexport function requiredCapabilityForCommand(type: FlowAgentCommandType, flowUri: string, nodeId: string): UcanCapability {\n return capabilityForCommand(COMMAND_CAPABILITIES[type], flowUri, nodeId);\n}\n\nexport function isCapabilityMatch(granted: UcanCapability, required: UcanCapability): boolean {\n return canMatches(granted.can, required.can) && resourceMatches(granted.with, required.with);\n}\n\nexport function canMatches(granted: string, required: string): boolean {\n if (granted === '*' || granted === required) return true;\n if (granted.endsWith('/*')) {\n const prefix = granted.slice(0, -1);\n return required.startsWith(prefix);\n }\n return false;\n}\n\nexport function resourceMatches(granted: string, required: string): boolean {\n if (granted === '*' || granted === required) return true;\n if (granted.endsWith('*')) {\n const prefix = granted.slice(0, -1);\n return required.startsWith(prefix);\n }\n return false;\n}\n\nexport interface EvaluateFlowAgentPolicyParams {\n actorDid: string;\n commandType: FlowAgentCommandType;\n flowUri: string;\n nodeId: string;\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n now?: number;\n}\n\nexport function evaluateFlowAgentPolicy({\n actorDid,\n commandType,\n flowUri,\n nodeId,\n delegationStore,\n delegations,\n now = Date.now(),\n}: EvaluateFlowAgentPolicyParams): FlowAgentPolicyDecision {\n const required = requiredCapabilityForCommand(commandType, flowUri, nodeId);\n const candidates = delegations || delegationStore?.getByAudience(actorDid) || [];\n\n for (const delegation of candidates) {\n if (delegation.audienceDid !== actorDid) continue;\n if (delegation.expiration != null && delegation.expiration <= now) continue;\n if (!delegation.capabilities.some((capability) => isCapabilityMatch(capability, required))) continue;\n\n return {\n allowed: true,\n reason: 'Allowed by UCAN delegation',\n capability: required,\n proofCids: [delegation.cid, ...delegation.proofCids],\n };\n }\n\n return {\n allowed: false,\n reason: `Actor ${actorDid} lacks ${required.can} on ${required.with}`,\n capability: required,\n proofCids: [],\n };\n}\n","import type { FlowAgentActor, FlowAgentCommand, FlowAgentCommandType } from '../../types/flowAgent';\nimport type { UcanCapability } from '../../types/ucan';\nimport { computeAgentCommandId } from './store';\nimport { requiredCapabilityForCommand } from './policy';\nimport { createIntentHash } from './utils';\n\nexport interface CreateAgentCommandParams {\n type: FlowAgentCommandType;\n flowId: string;\n flowUri: string;\n nodeId: string;\n actor: FlowAgentActor;\n reason: string;\n payload?: Record<string, unknown>;\n now?: number;\n}\n\nexport function createAgentCommand({ type, flowId, flowUri, nodeId, actor, reason, payload = {}, now = Date.now() }: CreateAgentCommandParams): FlowAgentCommand {\n const capability: UcanCapability = requiredCapabilityForCommand(type, flowUri, nodeId);\n const id = computeAgentCommandId({ flowId, nodeId, type, payload });\n return {\n id,\n type,\n flowId,\n flowUri,\n nodeId,\n actorDid: actor.did,\n status: 'queued',\n capability,\n idempotencyKey: `${id}:${createIntentHash({ capability, payload })}`,\n createdAt: now,\n updatedAt: now,\n reason,\n payload,\n };\n}\n\nexport function validateAgentCommand(command: FlowAgentCommand): { valid: boolean; error?: string } {\n if (!command.id) return { valid: false, error: 'Command id is required' };\n if (!command.flowId) return { valid: false, error: 'flowId is required' };\n if (!command.flowUri) return { valid: false, error: 'flowUri is required' };\n if (!command.nodeId) return { valid: false, error: 'nodeId is required' };\n if (!command.actorDid) return { valid: false, error: 'actorDid is required' };\n if (!command.capability?.can || !command.capability?.with) return { valid: false, error: 'capability is required' };\n if (!command.idempotencyKey) return { valid: false, error: 'idempotencyKey is required' };\n\n if (isExternalMutation(command.type) && !command.payload.validator) {\n return {\n valid: false,\n error: `${command.type} requires payload.validator for post-action read-back validation`,\n };\n }\n\n if (command.type === 'propose_config_change' && !command.payload.proposal) {\n return { valid: false, error: 'Config changes must be expressed as payload.proposal' };\n }\n\n return { valid: true };\n}\n\nexport function isExternalMutation(type: FlowAgentCommandType): boolean {\n return type === 'validate_external_state';\n}\n","import type { FlowAgentActor, FlowAgentContext } from '../../types/flowAgent';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { Doc } from 'yjs';\n\nexport interface BuildFlowAgentContextParams {\n yDoc: Doc;\n flowId: string;\n flowUri?: string;\n actor: FlowAgentActor;\n blocks?: unknown[];\n editor?: IxoEditorType;\n now?: () => number;\n}\n\n/**\n * Builds the host-facing runtime context expected by the Flow Agent.\n *\n * Headless hosts own Matrix login, room joins, and Y.Doc sync. Once a host has\n * a live room document and an agent identity, this helper gives it the stable\n * context shape to pass into `tickFlowAgent` or `FlowAgentService`.\n */\nexport function buildFlowAgentContext({ yDoc, flowId, flowUri = `ixo:flow:${flowId}`, actor, blocks, editor, now }: BuildFlowAgentContextParams): FlowAgentContext {\n return {\n yDoc,\n flowId,\n flowUri,\n actor,\n ...(blocks ? { blocks } : {}),\n ...(editor ? { editor } : {}),\n ...(now ? { now } : {}),\n };\n}\n","import type { Map as YMap } from 'yjs';\nimport type { FlowAgentLease } from '../../types/flowAgent';\n\nexport const DEFAULT_FLOW_AGENT_LEASE_TTL_MS = 60_000;\n\nexport interface AcquireFlowAgentLeaseParams {\n leases: YMap<FlowAgentLease>;\n commandId: string;\n nodeId: string;\n actorDid: string;\n now?: number;\n ttlMs?: number;\n}\n\nexport function acquireFlowAgentLease({\n leases,\n commandId,\n nodeId,\n actorDid,\n now = Date.now(),\n ttlMs = DEFAULT_FLOW_AGENT_LEASE_TTL_MS,\n}: AcquireFlowAgentLeaseParams): FlowAgentLease | null {\n const current = leases.get(commandId);\n if (current && current.expiresAt > now && current.actorDid !== actorDid) {\n return null;\n }\n\n const nextEpoch = current ? current.epoch + 1 : 1;\n const lease: FlowAgentLease = {\n id: `${commandId}:lease:${nextEpoch}`,\n commandId,\n nodeId,\n actorDid,\n acquiredAt: now,\n expiresAt: now + ttlMs,\n epoch: nextEpoch,\n };\n\n leases.set(commandId, lease);\n return lease;\n}\n\nexport function validateFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease, now = Date.now()): boolean {\n const current = leases.get(lease.commandId);\n return !!current && current.actorDid === lease.actorDid && current.epoch === lease.epoch && current.expiresAt > now;\n}\n\nexport function releaseFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease): boolean {\n const current = leases.get(lease.commandId);\n if (!current || current.actorDid !== lease.actorDid || current.epoch !== lease.epoch) return false;\n leases.delete(lease.commandId);\n return true;\n}\n\nexport function cleanupExpiredFlowAgentLeases(leases: YMap<FlowAgentLease>, now = Date.now()): FlowAgentLease[] {\n const expired: FlowAgentLease[] = [];\n leases.forEach((lease, commandId) => {\n if (lease.expiresAt <= now) {\n expired.push(lease);\n leases.delete(commandId);\n }\n });\n return expired;\n}\n","import type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { CompletionVerification } from '../flowEngine/verifiedCompletion';\nimport { deriveBlockPhase } from '../flowEngine/blockPhase';\nimport type { FlowAgentBlockerCause, FlowAgentNodeSnapshot, FlowAgentPublicNodeState } from '../../types/flowAgent';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockTitle, getBlockType, getDueAt, getBlockProps, parseJsonProp } from './utils';\n\ninterface ConditionConfig {\n enabled?: boolean;\n conditions?: Array<Record<string, unknown>>;\n}\n\nexport interface ClassifyNodeStateInput {\n block: unknown;\n runtime: FlowNodeRuntimeState;\n now: number;\n pendingInvocationCount?: number;\n /**\n * Verification of a `completed` runtime entry (see\n * `flowEngine/verifiedCompletion.ts`). When provided and 'unverified', the\n * node classifies as Blocked instead of Done — the planner must not advance\n * past a completion that lacks proof or a valid invocation. Omitted ⇒\n * legacy behavior (completed = Done).\n */\n completionVerification?: CompletionVerification;\n}\n\nexport function classifyBlockerCause(block: unknown, runtime: FlowNodeRuntimeState): FlowAgentBlockerCause | undefined {\n const props = getBlockProps(block);\n if (runtime.error?.code === 'missing_ucan') return 'missing_ucan';\n if (runtime.error?.code === 'validation_mismatch') return 'validation_mismatch';\n if (runtime.error?.code === 'external_confirmation_pending') return 'external_confirmation_pending';\n if (runtime.error) return 'service_error';\n\n const conditions = parseJsonProp<ConditionConfig>(props.conditions, {});\n if (conditions.enabled && Array.isArray(conditions.conditions) && conditions.conditions.length > 0) {\n return 'failed_upstream';\n }\n\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n if (requiredInputs.some((key) => inputs[key] == null || inputs[key] === '')) {\n return 'missing_input';\n }\n\n return undefined;\n}\n\nexport function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0, completionVerification }: ClassifyNodeStateInput): FlowAgentPublicNodeState {\n const derived = deriveBlockPhase({\n runtime,\n actionType: getBlockActionType(block),\n completionVerification,\n pendingInvocationCount,\n });\n\n // `failed` covers plain failures, `needs_verification` (a side-effecting\n // action that ran but couldn't prove it did — never auto-retry, that would\n // double-execute), unverified completions, and unknown state strings from\n // newer clients. All of them are dead-ends the planner must not advance\n // past or queue an execute for; Blocked routes them to diagnosis instead.\n if (derived.phase === 'failed') return 'Blocked';\n if (derived.phase === 'complete') return 'Done';\n // A repeatable ('many') block that has fired stays a standing capability —\n // it never latches Done while invocations are queued on it. With an empty\n // queue there is nothing for the planner to do, which is what Done means\n // here; the block itself remains invocable.\n if (derived.detail === 'standing' && pendingInvocationCount === 0) return 'Done';\n if (runtime.error) return 'Blocked';\n\n const dueAt = getDueAt(block);\n if (dueAt != null && dueAt <= now) return 'Overdue';\n\n return 'Pending';\n}\n\nexport function snapshotNode(\n block: unknown,\n runtime: FlowNodeRuntimeState,\n now: number,\n pendingInvocationCount = 0,\n completionVerification?: CompletionVerification\n): FlowAgentNodeSnapshot {\n const nodeId = getBlockId(block);\n if (!nodeId) {\n throw new Error('Cannot snapshot a block without an id');\n }\n\n const publicState = classifyNodeState({ block, runtime, now, pendingInvocationCount, completionVerification });\n const dueAt = getDueAt(block);\n const assigneeDid = getAssigneeDid(block);\n\n const snapshot: FlowAgentNodeSnapshot = {\n nodeId,\n blockType: getBlockType(block),\n runtime,\n publicState,\n pendingInvocationCount,\n };\n\n const actionType = getBlockActionType(block);\n if (actionType) snapshot.actionType = actionType;\n\n const title = getBlockTitle(block);\n if (title) snapshot.title = title;\n\n if (publicState === 'Blocked') {\n if (runtime.state === 'needs_verification') {\n snapshot.blockerCause = 'awaiting_verification';\n } else if (runtime.state === 'completed' && completionVerification?.status === 'unverified') {\n snapshot.blockerCause = 'unverified_completion';\n } else {\n snapshot.blockerCause = classifyBlockerCause(block, runtime) || 'unknown';\n }\n }\n\n if (assigneeDid) snapshot.assigneeDid = assigneeDid;\n if (dueAt != null) snapshot.dueAt = dueAt;\n\n return snapshot;\n}\n","import type { FlowAgentCommand } from '../../types/flowAgent';\nimport { getBlockActionType, getBlockProps, parseJsonProp } from './utils';\n\nexport type FlowAgentActionExecutionMode = 'saved-input' | 'runtime-input-required' | 'human-only';\n\nexport interface FlowAgentActionExecutionPolicy {\n mode: FlowAgentActionExecutionMode;\n requiredRuntimeInputs: string[];\n}\n\nexport interface FlowAgentExecuteActionValidation {\n valid: boolean;\n reason?: string;\n mode: FlowAgentActionExecutionMode;\n missingRuntimeInputs: string[];\n}\n\nconst RUNTIME_INPUT_REQUIRED_ACTIONS = new Set(['qi/form.submit', 'qi/human.form.submit', 'qi/human.checkbox.set', 'qi/protocol.select']);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction parseStringList(value: unknown): string[] {\n const parsed = parseJsonProp<unknown>(value, []);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is string => typeof item === 'string' && item.length > 0);\n}\n\nfunction normalizeMode(value: unknown): FlowAgentActionExecutionMode | undefined {\n if (value === 'saved-input' || value === 'saved_input' || value === 'savedInput') return 'saved-input';\n if (value === 'runtime-input-required' || value === 'runtime_input_required' || value === 'runtimeInputRequired') return 'runtime-input-required';\n if (value === 'human-only' || value === 'human_only' || value === 'humanOnly') return 'human-only';\n return undefined;\n}\n\nfunction parseExecutionConfig(value: unknown): Partial<FlowAgentActionExecutionPolicy> {\n if (value == null || value === '') return {};\n if (typeof value === 'string') {\n const directMode = normalizeMode(value);\n if (directMode) return { mode: directMode };\n }\n\n const parsed = parseJsonProp<Record<string, unknown>>(value, {});\n if (!isRecord(parsed)) return {};\n\n return {\n mode: normalizeMode(parsed.mode),\n requiredRuntimeInputs: parseStringList(parsed.requiredRuntimeInputs),\n };\n}\n\nfunction inferDefaultMode(actionType: string | undefined, requiredRuntimeInputs: string[]): FlowAgentActionExecutionMode {\n if (requiredRuntimeInputs.length > 0) return 'runtime-input-required';\n if (actionType && RUNTIME_INPUT_REQUIRED_ACTIONS.has(actionType)) return 'runtime-input-required';\n return 'saved-input';\n}\n\nexport function getFlowAgentActionExecutionPolicy(block: unknown): FlowAgentActionExecutionPolicy {\n const props = getBlockProps(block);\n const actionType = getBlockActionType(block);\n const config = parseExecutionConfig(props.flowAgentExecution || props.flowAgentExecutionMode || props.agentExecutionMode);\n const requiredRuntimeInputs = [\n ...(config.requiredRuntimeInputs || []),\n ...parseStringList(props.requiredRuntimeInputs || props.runtimeRequiredInputs || props.flowAgentRequiredRuntimeInputs),\n ];\n\n return {\n mode: config.mode || inferDefaultMode(actionType, requiredRuntimeInputs),\n requiredRuntimeInputs: Array.from(new Set(requiredRuntimeInputs)),\n };\n}\n\nexport function getCommandRuntimeInputs(payload: FlowAgentCommand['payload']): Record<string, unknown> | undefined {\n return isRecord(payload.runtimeInputs) ? payload.runtimeInputs : undefined;\n}\n\nexport function validateFlowAgentExecuteActionPayload(block: unknown, payload: FlowAgentCommand['payload']): FlowAgentExecuteActionValidation {\n const policy = getFlowAgentActionExecutionPolicy(block);\n if (policy.mode === 'human-only') {\n return {\n valid: false,\n mode: policy.mode,\n missingRuntimeInputs: [],\n reason: 'Action requires human execution and cannot be run by the Flow Agent',\n };\n }\n\n if (policy.mode !== 'runtime-input-required') {\n return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };\n }\n\n const runtimeInputs = getCommandRuntimeInputs(payload);\n const missingRuntimeInputs =\n policy.requiredRuntimeInputs.length > 0\n ? policy.requiredRuntimeInputs.filter((key) => runtimeInputs?.[key] == null || runtimeInputs[key] === '')\n : runtimeInputs\n ? []\n : ['runtimeInputs'];\n\n if (missingRuntimeInputs.length > 0) {\n return {\n valid: false,\n mode: policy.mode,\n missingRuntimeInputs,\n reason:\n policy.requiredRuntimeInputs.length > 0\n ? `Missing required runtimeInputs: ${missingRuntimeInputs.join(', ')}`\n : 'Action requires runtimeInputs before the Flow Agent can execute it',\n };\n }\n\n return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };\n}\n","import type { Doc } from 'yjs';\nimport type {\n FlowAgentActor,\n FlowAgentCommand,\n FlowAgentCommandResult,\n FlowAgentContext,\n FlowAgentExecutor,\n FlowAgentNodeSnapshot,\n FlowAgentTickResult,\n} from '../../types/flowAgent';\nimport type { StoredDelegation } from '../../types/ucan';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { readPendingInvocations } from '../flowEngine/triggers';\nimport { createAgentCommand, validateAgentCommand } from './commands';\nimport { acquireFlowAgentLease, releaseFlowAgentLease, validateFlowAgentLease } from './lease';\nimport { evaluateFlowAgentPolicy } from './policy';\nimport { appendAgentLedgerEvent, getFlowAgentMaps, queueAgentCommand, readQueuedAgentCommands, updateAgentCommand } from './store';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockProps, parseJsonProp } from './utils';\nimport { snapshotNode } from './state';\nimport { validateFlowAgentExecuteActionPayload } from './actionExecutionPolicy';\nimport { verifyCompletion } from '../flowEngine/verifiedCompletion';\nimport type { StoredInvocation } from '../../types/ucan';\n\nconst BLOCKER_DIAGNOSIS_VERSION = 2;\n\nexport interface FlowAgentOrchestratorOptions {\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n candidateActors?: FlowAgentActor[];\n executor?: FlowAgentExecutor;\n leaseTtlMs?: number;\n archiveWhenDone?: boolean;\n}\n\ninterface InputsValidation {\n valid: boolean;\n reason?: string;\n}\n\nfunction getBlocks(context: FlowAgentContext): unknown[] {\n return context.blocks || context.editor?.document || [];\n}\n\nfunction getRuntime(yDoc: Doc, nodeId: string): Record<string, any> {\n const runtime = yDoc.getMap<Record<string, any>>('runtime');\n const value = runtime.get(nodeId);\n return value && typeof value === 'object' ? value : {};\n}\n\nfunction validateInputs(block: unknown): InputsValidation {\n const props = getBlockProps(block);\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n const missing = requiredInputs.filter((key) => inputs[key] == null || inputs[key] === '');\n if (missing.length > 0) {\n return { valid: false, reason: `Missing required inputs: ${missing.join(', ')}` };\n }\n return { valid: true };\n}\n\nfunction chooseActor(block: unknown, options: FlowAgentOrchestratorOptions): FlowAgentActor | undefined {\n const props = getBlockProps(block);\n const actionType = getBlockActionType(block);\n const requiredSkill = typeof props.requiredSkill === 'string' ? props.requiredSkill : actionType;\n if (!options.candidateActors || options.candidateActors.length === 0) return undefined;\n if (!requiredSkill) return options.candidateActors[0];\n return options.candidateActors.find((actor) => actor.skills?.includes(requiredSkill)) || options.candidateActors[0];\n}\n\nfunction canQueueCommand(type: FlowAgentCommand['type'], nodeId: string, context: FlowAgentContext, options: FlowAgentOrchestratorOptions): boolean {\n return evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now: context.now?.() || Date.now(),\n }).allowed;\n}\n\nfunction safeAppendAgentLedgerEvent(yDoc: Doc, event: Parameters<typeof appendAgentLedgerEvent>[1]): void {\n try {\n appendAgentLedgerEvent(yDoc, event);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return;\n }\n throw error;\n }\n}\n\nfunction queueIfAuthorized(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions,\n type: FlowAgentCommand['type'],\n nodeId: string,\n reason: string,\n payload: Record<string, unknown>\n): FlowAgentCommand | null {\n const now = context.now?.() || Date.now();\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: 'agent.decision',\n flowId: context.flowId,\n nodeId,\n actorDid: context.actor.did,\n timestamp: now,\n details: {\n commandType: type,\n allowed: policy.allowed,\n reason: policy.reason,\n capability: policy.capability,\n },\n });\n\n if (!policy.allowed) return null;\n\n const command = createAgentCommand({\n type,\n flowId: context.flowId,\n flowUri: context.flowUri,\n nodeId,\n actor: context.actor,\n reason,\n payload,\n now,\n });\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: 'agent.validation',\n flowId: context.flowId,\n nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: now,\n details: { valid: false, error: validation.error },\n });\n return null;\n }\n return queueAgentCommand(context.yDoc, command).created ? command : null;\n}\n\nfunction statusForResult(result: FlowAgentCommandResult): FlowAgentCommand['status'] {\n if (result.status) return result.status;\n if (!result.success) return 'failed';\n return result.confirmed === false ? 'awaiting_readback' : 'confirmed';\n}\n\nfunction planForSnapshot(context: FlowAgentContext, options: FlowAgentOrchestratorOptions, block: unknown, snapshot: FlowAgentNodeSnapshot): FlowAgentCommand[] {\n const queued: FlowAgentCommand[] = [];\n const actionType = getBlockActionType(block);\n\n if (snapshot.publicState === 'Done') {\n return queued;\n }\n\n if (snapshot.publicState === 'Overdue') {\n const command = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is overdue', {\n assigneeDid: snapshot.assigneeDid,\n dueAt: snapshot.dueAt,\n severity: 'overdue',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (snapshot.publicState === 'Blocked') {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, 'Action node is blocked and requires diagnosis', {\n cause: snapshot.blockerCause || 'unknown',\n error: snapshot.runtime.error,\n diagnosisVersion: BLOCKER_DIAGNOSIS_VERSION,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const assigneeDid = getAssigneeDid(block);\n if (!assigneeDid) {\n const actor = chooseActor(block, options);\n const command = queueIfAuthorized(context, options, 'assign_actor', snapshot.nodeId, 'Action node has no assigned actor', {\n targetActorDid: actor?.did,\n targetMatrixUserId: actor?.matrixUserId,\n requiredActionType: actionType,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const inputValidation = validateInputs(block);\n if (!inputValidation.valid) {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, inputValidation.reason || 'Action node inputs are not ready', {\n cause: 'missing_input',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (actionType && canQueueCommand('execute_action', snapshot.nodeId, context, options)) {\n const pendingInvocation = readPendingInvocations(context.yDoc, snapshot.nodeId)[0];\n const payload = {\n actionType,\n ...(pendingInvocation ? { pendingInvocationId: pendingInvocation.id } : {}),\n };\n const actionValidation = validateFlowAgentExecuteActionPayload(block, payload);\n if (!actionValidation.valid) {\n const commandType = actionValidation.mode === 'human-only' ? 'notify_actor' : 'diagnose_blocker';\n const command = queueIfAuthorized(context, options, commandType, snapshot.nodeId, actionValidation.reason || 'Action node cannot be executed by Flow Agent yet', {\n cause: actionValidation.mode === 'runtime-input-required' ? 'missing_input' : 'unknown',\n requiredActionType: actionType,\n requiredRuntimeInputs: actionValidation.missingRuntimeInputs,\n severity: actionValidation.mode === 'human-only' ? 'attention' : undefined,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const command = queueIfAuthorized(context, options, 'execute_action', snapshot.nodeId, 'Action node is pending and executable', {\n ...payload,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const notifyCommand = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is pending but the Flow Agent cannot execute it', {\n assigneeDid,\n requiredActionType: actionType,\n severity: 'attention',\n });\n if (notifyCommand) queued.push(notifyCommand);\n return queued;\n}\n\nexport function planRalphLoopCommands(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions = {}\n): { snapshots: FlowAgentNodeSnapshot[]; queuedCommands: FlowAgentCommand[]; flowDone: boolean } {\n const now = context.now?.() || Date.now();\n const blocks = getBlocks(context);\n const snapshots: FlowAgentNodeSnapshot[] = [];\n const queuedCommands: FlowAgentCommand[] = [];\n\n const invocationsMap = context.yDoc.getMap('invocations');\n const schemaVersionRaw = context.yDoc.getMap('root').get('schema_version');\n const schemaVersion = typeof schemaVersionRaw === 'string' ? schemaVersionRaw : undefined;\n const getInvocation = (cid: string) => invocationsMap.get(cid) as StoredInvocation | undefined;\n\n for (const block of blocks) {\n const nodeId = getBlockId(block);\n if (!nodeId) continue;\n const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId).length;\n const runtime = getRuntime(context.yDoc, nodeId);\n const actionType = getBlockActionType(block);\n // The planner never advances past a completion that lacks proof or (on\n // UCAN-enforced flows) a valid success invocation — see verifiedCompletion.ts.\n const completionVerification = verifyCompletion({\n runtime,\n blockId: nodeId,\n actionType,\n getInvocation,\n schemaVersion,\n });\n const snapshot = snapshotNode(block, runtime, now, pendingInvocationCount, completionVerification);\n snapshots.push(snapshot);\n queuedCommands.push(...planForSnapshot(context, options, block, snapshot));\n }\n\n const flowDone = snapshots.length > 0 && snapshots.every((snapshot) => snapshot.publicState === 'Done');\n if (flowDone && options.archiveWhenDone !== false) {\n const archiveCommand = queueIfAuthorized(context, options, 'archive_flow', context.flowId, 'All Ralph loop action nodes are done', {\n restartIfRepeats: true,\n });\n if (archiveCommand) queuedCommands.push(archiveCommand);\n }\n\n return { snapshots, queuedCommands, flowDone };\n}\n\nasync function callExecutor(command: FlowAgentCommand, context: FlowAgentContext, executor: FlowAgentExecutor): Promise<FlowAgentCommandResult> {\n switch (command.type) {\n case 'execute_action':\n return executor.executeAction ? executor.executeAction(command, context) : { commandId: command.id, success: false, error: 'No executeAction handler configured' };\n case 'assign_actor':\n return executor.assignActor ? executor.assignActor(command, context) : { commandId: command.id, success: false, error: 'No assignActor handler configured' };\n case 'notify_actor':\n return executor.notifyActor ? executor.notifyActor(command, context) : { commandId: command.id, success: false, error: 'No notifyActor handler configured' };\n case 'validate_external_state':\n return executor.validateExternalState\n ? executor.validateExternalState(command, context)\n : { commandId: command.id, success: false, error: 'No validateExternalState handler configured' };\n case 'archive_flow':\n return executor.archiveFlow ? executor.archiveFlow(command, context) : { commandId: command.id, success: false, error: 'No archiveFlow handler configured' };\n case 'propose_config_change':\n return executor.proposeConfigChange\n ? executor.proposeConfigChange(command, context)\n : { commandId: command.id, success: false, error: 'No proposeConfigChange handler configured' };\n case 'diagnose_blocker':\n return executor.diagnoseBlocker ? executor.diagnoseBlocker(command, context) : { commandId: command.id, success: false, error: 'No diagnoseBlocker handler configured' };\n }\n}\n\nexport async function executeQueuedAgentCommands(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentCommandResult[]> {\n const executor = options.executor;\n if (!executor) return [];\n\n const now = context.now?.() || Date.now();\n const { leases } = getFlowAgentMaps(context.yDoc);\n const results: FlowAgentCommandResult[] = [];\n\n for (const command of readQueuedAgentCommands(context.yDoc)) {\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: validation.error, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: validation.error });\n continue;\n }\n\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: command.type,\n flowUri: context.flowUri,\n nodeId: command.nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n if (!policy.allowed) {\n updateAgentCommand(context.yDoc, command.id, { status: 'skipped', error: policy.reason, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: policy.reason });\n continue;\n }\n\n const lease = acquireFlowAgentLease({\n leases,\n commandId: command.id,\n nodeId: command.nodeId,\n actorDid: context.actor.did,\n now,\n ttlMs: options.leaseTtlMs,\n });\n\n if (!lease) {\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, { status: 'running', lease, updatedAt: now });\n\n try {\n const result = await callExecutor({ ...command, lease, status: 'running' }, context, executor);\n if (!validateFlowAgentLease(leases, lease, context.now?.() || Date.now())) {\n const leaseError = 'Lease expired or was superseded before command commit';\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: leaseError, updatedAt: context.now?.() || Date.now() });\n results.push({ commandId: command.id, success: false, error: leaseError });\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, {\n status: statusForResult(result),\n error: result.error,\n updatedAt: context.now?.() || Date.now(),\n });\n\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: result.success ? 'agent.validation' : 'agent.escalation',\n flowId: context.flowId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: context.now?.() || Date.now(),\n details: {\n success: result.success,\n confirmed: result.confirmed,\n output: result.output,\n error: result.error,\n },\n });\n\n results.push(result);\n } finally {\n releaseFlowAgentLease(leases, lease);\n }\n }\n\n return results;\n}\n\nexport async function tickFlowAgent(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentTickResult> {\n const plan = planRalphLoopCommands(context, options);\n const executedCommands = await executeQueuedAgentCommands(context, options);\n return {\n flowDone: plan.flowDone,\n snapshots: plan.snapshots,\n queuedCommands: plan.queuedCommands,\n executedCommands,\n };\n}\n","import type { Doc } from 'yjs';\nimport type { ActionHandlers, ActionServices } from '../actionRegistry';\nimport { executeActionBlock } from '../flowEngine';\nimport type { FlowRuntimeStateManager } from '../flowEngine/runtime';\nimport type { UcanService } from '../../services/ucanService';\nimport type { StoredDelegation } from '../../types/ucan';\nimport type { InvocationStore } from '../invocationStore';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport type { FlowAgentCommand, FlowAgentCommandResult, FlowAgentContext, FlowAgentExecutor } from '../../types/flowAgent';\nimport { acquireFlowAgentLease, releaseFlowAgentLease, validateFlowAgentLease } from './lease';\nimport { evaluateFlowAgentPolicy } from './policy';\nimport { appendAgentLedgerEvent, getFlowAgentMaps, readQueuedAgentCommands, updateAgentCommand } from './store';\nimport { getBlockId, getBlockProps } from './utils';\nimport { validateAgentCommand } from './commands';\nimport { getCommandRuntimeInputs, validateFlowAgentExecuteActionPayload } from './actionExecutionPolicy';\n\nexport interface ExecuteFlowAgentCoreCommandOptions {\n ucanService: UcanService;\n pin: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n actionServices?: ActionServices;\n actionHandlers?: ActionHandlers;\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n invocationStore?: InvocationStore;\n leaseTtlMs?: number;\n flowOwnerDid?: string;\n schemaVersion?: string;\n now?: () => number;\n}\n\nexport interface ExecuteQueuedFlowAgentCoreCommandsOptions extends ExecuteFlowAgentCoreCommandOptions {\n executor?: FlowAgentExecutor;\n commandTypes?: FlowAgentCommand['type'][];\n}\n\nconst DEFAULT_SCHEMA_VERSION = '1.0.0';\n\nfunction safeAppendAgentLedgerEvent(yDoc: Doc, event: Parameters<typeof appendAgentLedgerEvent>[1]): void {\n try {\n appendAgentLedgerEvent(yDoc, event);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return;\n }\n throw error;\n }\n}\n\nfunction createYDocRuntimeManager(yDoc: Doc): FlowRuntimeStateManager {\n const runtime = yDoc.getMap<Record<string, unknown>>('runtime');\n return {\n get: (nodeId) => {\n const value = runtime.get(nodeId);\n return value && typeof value === 'object' ? { ...value } : {};\n },\n update: (nodeId, updates) => {\n const current = runtime.get(nodeId);\n runtime.set(nodeId, {\n ...(current && typeof current === 'object' ? current : {}),\n ...updates,\n });\n },\n };\n}\n\nfunction getRuntimeRecord(yDoc: Doc, nodeId: string): Record<string, unknown> {\n const runtime = yDoc.getMap<Record<string, unknown>>('runtime');\n const value = runtime.get(nodeId);\n return value && typeof value === 'object' ? value : {};\n}\n\nfunction clearRuntimeBlocker(yDoc: Doc, nodeId: string, updates: Record<string, unknown>): void {\n const runtime = yDoc.getMap<Record<string, unknown>>('runtime');\n const current = getRuntimeRecord(yDoc, nodeId);\n const { state: _state, error: _error, ...rest } = current;\n runtime.set(nodeId, {\n ...rest,\n ...updates,\n });\n}\n\nfunction findContextBlock(context: FlowAgentContext, nodeId: string): Record<string, unknown> | null {\n const block = (context.blocks || context.editor?.document || []).find((entry) => getBlockId(entry) === nodeId);\n return block && typeof block === 'object' ? (block as Record<string, unknown>) : null;\n}\n\ntype YXmlAttributeReader = {\n getAttribute: (key: string) => unknown;\n};\n\nfunction getXmlAttribute<T>(element: YXmlAttributeReader, key: string): T | undefined {\n return element.getAttribute(key) as T | undefined;\n}\n\nfunction setXmlAttribute(element: { setAttribute: (key: string, value: unknown) => unknown }, key: string, value: unknown): void {\n (element as unknown as { setAttribute: (key: string, value: unknown) => void }).setAttribute(key, value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\ntype YXmlContainerLike = {\n toArray: () => unknown[];\n};\n\ntype YXmlElementLike = YXmlContainerLike & {\n nodeName: string;\n getAttribute: (key: string) => unknown;\n setAttribute: (key: string, value: unknown) => unknown;\n};\n\nfunction isYXmlContainerLike(value: unknown): value is YXmlContainerLike {\n return value != null && typeof value === 'object' && typeof (value as { toArray?: unknown }).toArray === 'function';\n}\n\nfunction isYXmlElementLike(value: unknown): value is YXmlElementLike {\n return (\n isYXmlContainerLike(value) &&\n typeof (value as { nodeName?: unknown }).nodeName === 'string' &&\n typeof (value as { getAttribute?: unknown }).getAttribute === 'function' &&\n typeof (value as { setAttribute?: unknown }).setAttribute === 'function'\n );\n}\n\nfunction getElementBlockId(element: YXmlElementLike): string | undefined {\n const directId = getXmlAttribute<string>(element, 'id');\n if (typeof directId === 'string' && directId.length > 0) return directId;\n\n const attrs = getXmlAttribute<Record<string, unknown>>(element, 'attrs');\n const attrsId = isRecord(attrs) ? attrs.id : undefined;\n return typeof attrsId === 'string' && attrsId.length > 0 ? attrsId : undefined;\n}\n\nfunction updateXmlElementProps(element: YXmlElementLike, blockId: string, propsPatch: Record<string, unknown>): void {\n const attrs = getXmlAttribute<Record<string, unknown>>(element, 'attrs');\n if (isRecord(attrs)) {\n const existingProps = isRecord(attrs.props) ? attrs.props : {};\n setXmlAttribute(element, 'attrs', {\n ...attrs,\n id: typeof attrs.id === 'string' ? attrs.id : blockId,\n props: {\n ...existingProps,\n ...propsPatch,\n },\n });\n }\n\n for (const [key, value] of Object.entries(propsPatch)) {\n element.setAttribute(key, typeof value === 'string' ? value : JSON.stringify(value));\n }\n}\n\nfunction findXmlElementById(container: YXmlContainerLike, blockId: string): YXmlElementLike | null {\n for (const node of container.toArray()) {\n if (!isYXmlElementLike(node)) continue;\n const id = getElementBlockId(node);\n if (id === blockId) return node;\n const nested = findXmlElementById(node, blockId);\n if (nested) return nested;\n }\n return null;\n}\n\nfunction updateDocumentBlockProps(yDoc: Doc, blockId: string, propsPatch: Record<string, unknown>): boolean {\n const target = findXmlElementById(yDoc.getXmlFragment('document'), blockId);\n if (!target) return false;\n\n updateXmlElementProps(target, blockId, propsPatch);\n\n const content = target.toArray().find((node): node is YXmlElementLike => isYXmlElementLike(node) && node.nodeName !== 'blockGroup');\n if (content) {\n updateXmlElementProps(content, blockId, propsPatch);\n }\n\n return true;\n}\n\nfunction assignActorInYDoc(yDoc: Doc, command: FlowAgentCommand, context: FlowAgentContext): Record<string, unknown> {\n const targetActorDid = typeof command.payload.targetActorDid === 'string' && command.payload.targetActorDid.length > 0 ? command.payload.targetActorDid : context.actor.did;\n const targetMatrixUserId = typeof command.payload.targetMatrixUserId === 'string' ? command.payload.targetMatrixUserId : undefined;\n const assignment = {\n assignedActor: {\n did: targetActorDid,\n avatar: '',\n displayName: targetMatrixUserId || targetActorDid,\n },\n assignedBy: {\n did: context.actor.did,\n avatar: '',\n displayName: context.actor.displayName || context.actor.matrixUserId || '',\n },\n assignedTimestamp: new Date(context.now?.() || Date.now()).toISOString(),\n };\n const assignmentJson = JSON.stringify(assignment);\n\n const updatedDocument = updateDocumentBlockProps(yDoc, command.nodeId, {\n assignment: assignmentJson,\n });\n\n if (!updatedDocument) {\n throw new Error(`Block ${command.nodeId} was not found for assignment`);\n }\n\n const runtime = createYDocRuntimeManager(yDoc);\n runtime.update(command.nodeId, {\n assignedActorDid: targetActorDid,\n assignedByDid: context.actor.did,\n assignedAt: assignment.assignedTimestamp,\n lastCommandId: command.id,\n } as Record<string, unknown>);\n\n return assignment;\n}\n\nasync function executeAssignActorCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const capability = { can: 'flow/node/assign', with: `${context.flowUri}:${command.nodeId}` };\n const proofs = await options.ucanService.findValidProofs(context.actor.did, capability);\n if (!proofs.found || !proofs.proofCids) {\n return {\n commandId: command.id,\n success: false,\n error: proofs.error || 'No valid delegation found for assignment',\n };\n }\n\n const result = await options.ucanService.executeWithInvocation(\n {\n invokerDid: context.actor.did,\n invokerType: options.actorType,\n entityRoomId: options.entityRoomId,\n capability,\n proofs: proofs.proofCids,\n pin: options.pin,\n },\n async () => assignActorInYDoc(context.yDoc, command, context),\n context.flowId,\n command.nodeId\n );\n\n return {\n commandId: command.id,\n success: result.success,\n confirmed: result.success,\n output:\n result.actionResult && typeof result.actionResult === 'object'\n ? { assignment: result.actionResult as Record<string, unknown>, invocationCid: result.invocationCid }\n : { invocationCid: result.invocationCid },\n error: result.error,\n };\n}\n\nasync function executeActionCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const actionType = typeof command.payload.actionType === 'string' ? command.payload.actionType : undefined;\n if (!actionType) {\n return { commandId: command.id, success: false, error: 'execute_action command is missing payload.actionType' };\n }\n\n const block = findContextBlock(context, command.nodeId);\n if (!block) {\n return { commandId: command.id, success: false, error: `Block ${command.nodeId} was not found in runtime context` };\n }\n\n const props = getBlockProps(block);\n if (typeof props.actionType === 'string' && props.actionType !== actionType) {\n return {\n commandId: command.id,\n success: false,\n error: `execute_action payload.actionType ${actionType} does not match block actionType ${props.actionType}`,\n };\n }\n\n const runtimeInputs = command.payload.runtimeInputs;\n if (runtimeInputs != null && !isRecord(runtimeInputs)) {\n return { commandId: command.id, success: false, error: 'execute_action payload.runtimeInputs must be an object when provided' };\n }\n\n const inputValidation = validateFlowAgentExecuteActionPayload(block, command.payload);\n if (!inputValidation.valid) {\n return {\n commandId: command.id,\n success: false,\n confirmed: false,\n status: inputValidation.mode === 'human-only' ? 'skipped' : 'failed',\n error: inputValidation.reason,\n };\n }\n\n const pendingInvocationId = typeof command.payload.pendingInvocationId === 'string' ? command.payload.pendingInvocationId : undefined;\n const outcome = await executeActionBlock({\n editorOrYDoc: context.editor || context.yDoc,\n block,\n blockId: command.nodeId,\n document: (context.blocks || context.editor?.document || []) as any[],\n actorDid: context.actor.did,\n actorType: options.actorType,\n entityRoomId: options.entityRoomId,\n ucanService: options.ucanService,\n invocationStore: options.invocationStore,\n services: options.actionServices || {},\n handlers: options.actionHandlers,\n runtimeInputs: getCommandRuntimeInputs(command.payload),\n pendingInvocationId,\n pin: options.pin,\n flowUri: context.flowUri,\n flowId: context.flowId,\n flowOwnerDid: options.flowOwnerDid || '',\n schemaVersion: options.schemaVersion || DEFAULT_SCHEMA_VERSION,\n now: options.now || context.now,\n });\n\n return {\n commandId: command.id,\n success: outcome.success,\n confirmed: outcome.success && outcome.completionState === 'completed',\n output: {\n ...(outcome.output && typeof outcome.output === 'object' ? outcome.output : {}),\n ...(outcome.invocationCid ? { invocationCid: outcome.invocationCid } : {}),\n ...(outcome.capabilityId ? { capabilityId: outcome.capabilityId } : {}),\n ...(outcome.runId ? { runId: outcome.runId } : {}),\n ...(outcome.events.length > 0 ? { events: outcome.events } : {}),\n ...(pendingInvocationId ? { pendingInvocationId, pendingInvocationRemoved: outcome.pendingInvocationRemoved } : {}),\n completionState: outcome.completionState,\n },\n error: outcome.error,\n completionState: outcome.completionState,\n };\n}\n\nfunction getRecoverableBlockerReason(runtime: Record<string, unknown>): string | null {\n const error = runtime.error;\n const message =\n error && typeof error === 'object' && typeof (error as Record<string, unknown>).message === 'string'\n ? ((error as Record<string, unknown>).message as string)\n : typeof error === 'string'\n ? error\n : undefined;\n\n if (!message) return null;\n if (message.includes('Invalid DID') && message.includes(\"must start with 'did:'\")) {\n return 'matrix_did_normalization';\n }\n if (message.includes('Failed to parse URL from undefined')) {\n return 'http_endpoint_input_normalization';\n }\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return 'audit_trail_shape';\n }\n return null;\n}\n\nfunction resetFailedActionCommands(context: FlowAgentContext, nodeId: string, now: number): string[] {\n const { outbox } = getFlowAgentMaps(context.yDoc);\n const resetIds: string[] = [];\n outbox.forEach((command) => {\n if (command.nodeId !== nodeId || command.type !== 'execute_action' || command.status !== 'failed') {\n return;\n }\n outbox.set(command.id, {\n ...command,\n status: 'queued',\n error: undefined,\n lease: undefined,\n updatedAt: now,\n reason: `Retry after blocker diagnosis: ${command.reason}`,\n });\n resetIds.push(command.id);\n });\n return resetIds;\n}\n\nasync function executeDiagnoseBlockerCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const now = options.now?.() || context.now?.() || Date.now();\n const runtime = getRuntimeRecord(context.yDoc, command.nodeId);\n const recovery = getRecoverableBlockerReason(runtime);\n\n if (!recovery) {\n return {\n commandId: command.id,\n success: true,\n confirmed: true,\n output: {\n blockerCause: command.payload.cause || 'unknown',\n recovery: 'manual_intervention_required',\n },\n };\n }\n\n clearRuntimeBlocker(context.yDoc, command.nodeId, {\n diagnosedAt: now,\n diagnosedByDid: context.actor.did,\n lastDiagnosisCommandId: command.id,\n lastRecovery: recovery,\n });\n const resetCommandIds = resetFailedActionCommands(context, command.nodeId, now);\n\n return {\n commandId: command.id,\n success: true,\n confirmed: true,\n output: {\n blockerCause: command.payload.cause || 'unknown',\n recovery,\n resetCommandIds,\n },\n };\n}\n\nexport async function executeFlowAgentCoreCommand(\n command: FlowAgentCommand,\n context: FlowAgentContext,\n options: ExecuteFlowAgentCoreCommandOptions\n): Promise<FlowAgentCommandResult> {\n switch (command.type) {\n case 'assign_actor':\n return executeAssignActorCommand(command, context, options);\n case 'execute_action':\n return executeActionCommand(command, context, options);\n case 'diagnose_blocker':\n return executeDiagnoseBlockerCommand(command, context, options);\n default:\n return { commandId: command.id, success: false, error: `No editor-core executor for ${command.type}` };\n }\n}\n\nasync function callConfiguredExecutor(\n command: FlowAgentCommand,\n context: FlowAgentContext,\n options: ExecuteQueuedFlowAgentCoreCommandsOptions\n): Promise<FlowAgentCommandResult | undefined> {\n if (!options.executor) return undefined;\n switch (command.type) {\n case 'assign_actor':\n return options.executor.assignActor?.(command, context);\n case 'execute_action':\n return options.executor.executeAction?.(command, context);\n case 'notify_actor':\n return options.executor.notifyActor?.(command, context);\n case 'diagnose_blocker':\n return options.executor.diagnoseBlocker?.(command, context);\n default:\n return undefined;\n }\n}\n\nfunction statusForResult(result: FlowAgentCommandResult): FlowAgentCommand['status'] {\n if (result.status) return result.status;\n if (!result.success) return 'failed';\n return result.confirmed === false ? 'awaiting_readback' : 'confirmed';\n}\n\nexport async function executeQueuedFlowAgentCoreCommands(context: FlowAgentContext, options: ExecuteQueuedFlowAgentCoreCommandsOptions): Promise<FlowAgentCommandResult[]> {\n const now = options.now?.() || context.now?.() || Date.now();\n const { leases } = getFlowAgentMaps(context.yDoc);\n const results: FlowAgentCommandResult[] = [];\n\n for (const command of readQueuedAgentCommands(context.yDoc)) {\n if (options.commandTypes && !options.commandTypes.includes(command.type)) {\n continue;\n }\n\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: validation.error, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: validation.error });\n continue;\n }\n\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: command.type,\n flowUri: context.flowUri,\n nodeId: command.nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n if (!policy.allowed) {\n updateAgentCommand(context.yDoc, command.id, { status: 'skipped', error: policy.reason, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: policy.reason });\n continue;\n }\n\n const lease = acquireFlowAgentLease({\n leases,\n commandId: command.id,\n nodeId: command.nodeId,\n actorDid: context.actor.did,\n now,\n ttlMs: options.leaseTtlMs,\n });\n if (!lease) continue;\n\n updateAgentCommand(context.yDoc, command.id, { status: 'running', lease, updatedAt: now });\n\n try {\n const runningCommand = { ...command, lease, status: 'running' as const };\n const result = (await Promise.resolve(callConfiguredExecutor(runningCommand, context, options))) || (await executeFlowAgentCoreCommand(runningCommand, context, options));\n const normalized = result || {\n commandId: command.id,\n success: false,\n error: `No executor configured for ${command.type}`,\n };\n\n if (!validateFlowAgentLease(leases, lease, options.now?.() || context.now?.() || Date.now())) {\n const error = 'Lease expired or was superseded before command commit';\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error, updatedAt: options.now?.() || context.now?.() || Date.now() });\n results.push({ commandId: command.id, success: false, error });\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, {\n status: statusForResult(normalized),\n error: normalized.error,\n updatedAt: options.now?.() || context.now?.() || Date.now(),\n });\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: normalized.success ? 'agent.validation' : 'agent.escalation',\n flowId: context.flowId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: options.now?.() || context.now?.() || Date.now(),\n details: {\n success: normalized.success,\n confirmed: normalized.confirmed,\n output: normalized.output,\n error: normalized.error,\n },\n });\n results.push(normalized);\n } finally {\n releaseFlowAgentLease(leases, lease);\n }\n }\n\n return results;\n}\n","import type { FlowAgentContext, FlowAgentTickResult } from '../../types/flowAgent';\nimport type { FlowAgentOrchestratorOptions } from './orchestrator';\nimport { tickFlowAgent } from './orchestrator';\n\nexport interface FlowAgentServiceOptions extends FlowAgentOrchestratorOptions {\n intervalMs?: number;\n onTick?: (result: FlowAgentTickResult) => void | Promise<void>;\n onError?: (error: unknown) => void;\n}\n\n/**\n * Headless-service adapter boundary.\n *\n * Host applications own Matrix login, room joins, and Y.Doc sync. Once they\n * have a live Y.Doc/editor snapshot, this service provides the deterministic\n * Ralph-loop tick and command execution cycle.\n */\nexport class FlowAgentService {\n private timer: ReturnType<typeof setInterval> | null = null;\n private running = false;\n\n constructor(\n private readonly context: FlowAgentContext,\n private readonly options: FlowAgentServiceOptions = {}\n ) {}\n\n async tick(): Promise<FlowAgentTickResult> {\n if (this.running) {\n return {\n flowDone: false,\n snapshots: [],\n queuedCommands: [],\n executedCommands: [],\n };\n }\n\n this.running = true;\n try {\n const result = await tickFlowAgent(this.context, this.options);\n await this.options.onTick?.(result);\n return result;\n } catch (error) {\n this.options.onError?.(error);\n throw error;\n } finally {\n this.running = false;\n }\n }\n\n start(): void {\n if (this.timer) return;\n const intervalMs = this.options.intervalMs || 30_000;\n this.timer = setInterval(() => {\n this.tick().catch((error) => {\n this.options.onError?.(error);\n });\n }, intervalMs);\n }\n\n stop(): void {\n if (!this.timer) return;\n clearInterval(this.timer);\n this.timer = null;\n }\n}\n"],"mappings":";AAYA;AAAA,EACE,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AA4LP,SAAS,eAAe,KAAuC;AAC7D,MAAI,IAAI,WAAW,UAAU,KAAK,IAAI,WAAW,UAAU,GAAG;AAC5D,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,KAAqB;AACzC,MAAI,IAAI,WAAW,MAAM,EAAG,QAAO;AACnC,MAAI,IAAI,WAAW,MAAM,EAAG,QAAO,WAAW,GAAG;AACjD,MAAI,CAAC,IAAI,WAAW,OAAO,EAAG,QAAO;AAErC,QAAM,CAAC,SAAS,IAAI,IAAI,MAAM,GAAG;AACjC,QAAM,QAAQ,UAAU,MAAM,GAAG;AACjC,MAAI,MAAM,SAAS,KAAK,MAAM,CAAC,MAAM,OAAQ,QAAO;AACpD,SAAO,OAAO,MAAM,CAAC,CAAC,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC;AACpD;AAEA,SAAS,wBAAwB,KAA2B;AAC1D,QAAM,aAAa,aAAa,GAAG;AACnC,QAAM,YAAY,eAAe,UAAU;AAC3C,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAA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MAAM,cAAc,KAAK,SAAS,KAAK,OAAO;AAC7D,YAAM,KAAK,QAAQ,SAAS,MAAM;AAClC,aAAO;AAAA,IACT,SAAS,OAAO;AACd,WAAK,QAAQ,UAAU,KAAK;AAC5B,YAAM;AAAA,IACR,UAAE;AACA,WAAK,UAAU;AAAA,IACjB;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,MAAO;AAChB,UAAM,aAAa,KAAK,QAAQ,cAAc;AAC9C,SAAK,QAAQ,YAAY,MAAM;AAC7B,WAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,aAAK,QAAQ,UAAU,KAAK;AAAA,MAC9B,CAAC;AAAA,IACH,GAAG,UAAU;AAAA,EACf;AAAA,EAEA,OAAa;AACX,QAAI,CAAC,KAAK,MAAO;AACjB,kBAAc,KAAK,KAAK;AACxB,SAAK,QAAQ;AAAA,EACf;AACF;","names":["storedDelegation","actions","output","missing","actions","seen","claimId","BASELINE_OUTPUT","normalizeDecision","actions","members","SENSITIVE_PLAINTEXT_KEYS","SENSITIVE_PLAINTEXT_KEYS","CollectionStateEnum","transactionHash","collectionId","result","granteeAddress","transactionHash","roleLabel","roleLabel","formatCoin","USDC_DENOM","DECIMALS","formatCoin","formatCoin","formatQuota","USDC_DENOM","formatCoin","value","getNodeOutput","getNodeOutput","XERO_WORK_ITEMS_MAP_NAME","XERO_WORK_TERMINAL_MAP_NAME","getNodeOutput","fieldPath","Y","Y","runId","isYDoc","getYDoc","parseInputs","getRuntime","getEditor","makeRunId","getReconcileEditor","parseOutputRef","Y","Y","Y","Y","Y","fnv1a32","getRuntime","command","safeAppendAgentLedgerEvent","createYDocRuntimeManager","isRecord","statusForResult"]}