@ixo/editor 5.24.0 → 5.25.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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/lib/actionRegistry/registry.ts","../src/core/lib/actionRegistry/canMapping.ts","../src/core/lib/actionRegistry/adapters.ts","../src/core/lib/matrixDm.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/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/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/xeroWorkItems.ts","../src/core/lib/actionRegistry/actions/xero/invoiceCreate.types.ts","../src/core/lib/actionRegistry/actions/xero/paymentCreate.types.ts","../src/mantine/utils/referenceResolver.ts","../src/core/lib/xeroWorkItemPayloads.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/payment.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/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/services/ucanService.ts","../src/core/lib/ucanDelegationStore.ts","../src/core/lib/invocationStore.ts","../src/core/lib/flowEngine/utils.ts","../src/core/lib/flowEngine/runtime.ts","../src/core/types/baseUcan.ts","../src/core/lib/flowCompiler/resolveRefs.ts","../src/core/lib/flowEngine/versionManifest.ts","../src/core/lib/flowEngine/authorization.ts","../src/core/lib/flowEngine/executor.ts","../src/core/lib/flowEngine/triggers.ts","../src/core/lib/flowEngine/reconcile.ts","../src/core/lib/flowEngine/emitEvents.ts","../src/core/lib/flowEngine/actionExecutor.ts","../src/core/lib/flowEngine/readBackReconciler.ts","../src/core/lib/flowEngine/migration.ts","../src/core/lib/flowEngine/migrations/v0_3_to_v1_0_0.ts","../src/core/lib/flowCompiler/blockMapping.ts","../src/core/lib/flowCompiler/compiler.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/flowCompiler/documentFragment.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":["import type { ActionDefinition, ActionEventDefinition, OutputSchemaField } from './types';\n\nconst actions = new Map<string, ActionDefinition>();\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 payment: 'qi/payment.execute',\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\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 if (action.getDynamicEvents) {\n const parsed = normalizeInputs(inputs);\n try {\n return action.getDynamicEvents(parsed) || [];\n } catch {\n // A crashing resolver must not break the picker or compiler.\n return [];\n }\n }\n return action.events || [];\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 return action.getDynamicOutputSchema(parsed) || [];\n } catch {\n return action.outputSchema || [];\n }\n }\n return action.outputSchema || [];\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 return {};\n }\n }\n return {};\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 '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 'domain/card-preview': 'qi/domain.card-preview',\n 'domain/sign': 'qi/domain.sign',\n 'credential/store': 'qi/credential.store',\n 'payment/execute': 'qi/payment.execute',\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 // Calendar integration\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","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 */\nexport function buildServicesFromHandlers(handlers: any): ActionServices {\n return {\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 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 }\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 };\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","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 defaultRequiresConfirmation: false,\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 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 defaultRequiresConfirmation: false,\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';\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 defaultRequiresConfirmation: false,\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 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';\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 defaultRequiresConfirmation: false,\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 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 defaultRequiresConfirmation: false,\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 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 defaultRequiresConfirmation: false,\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';\n\nregisterAction({\n type: 'qi/http.request',\n can: 'http/request',\n sideEffect: false,\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 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 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/events-and-triggers-plan.md §3.6.\n eligibleForEventTrigger: true,\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: 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 defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\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 defaultRequiresConfirmation: false,\n requiredCapability: 'flow/execute',\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 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 };\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 defaultRequiresConfirmation: true,\n requiredCapability: 'notify/send',\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 { registerAction } from '../../registry';\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\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 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 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 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 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 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 { 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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 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 type { Map as YMap } from 'yjs';\n\nexport type XeroWorkKind = 'invoice.create' | 'payment.create';\nexport type XeroWorkStatus = 'pending' | '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 completedAt?: number;\n completedByDid?: string;\n}\n\nexport const XERO_WORK_ITEMS_MAP_NAME = 'xeroWorkItems';\n\nfunction getXeroWorkItemsMap(editor?: any): YMap<XeroWorkItem> | null {\n return (editor?._yXeroWorkItems as YMap<XeroWorkItem> | undefined) || null;\n}\n\nfunction readMapItems(map: YMap<XeroWorkItem> | null): XeroWorkItem[] {\n if (!map) return [];\n const items: XeroWorkItem[] = [];\n map.forEach((value) => {\n if (value && typeof value === 'object' && 'id' in value) {\n items.push({ ...(value as XeroWorkItem) });\n }\n });\n return items;\n}\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 attempts: existing.attempts ?? [],\n originalPayload: existing.originalPayload,\n submittedPayload: existing.submittedPayload,\n result: existing.result,\n completedAt: existing.completedAt,\n completedByDid: existing.completedByDid,\n };\n}\n\nexport function buildXeroInvoiceWorkKey(params: { flowId: string; evaluationBlockId: string; claimId: string; invoiceBlockId: string }): string {\n return ['xero', 'invoice.create', params.flowId, params.evaluationBlockId, params.claimId, params.invoiceBlockId].join(':');\n}\n\nexport function buildXeroPaymentWorkKey(params: { flowId: string; evaluationBlockId: string; claimId: string; paymentBlockId: string; invoiceWorkItemId: string }): string {\n return ['xero', 'payment.create', params.flowId, params.evaluationBlockId, params.claimId, params.paymentBlockId, params.invoiceWorkItemId].join(':');\n}\n\nexport function findXeroWorkItemsForEditor(editor: any, filter: { kind?: XeroWorkKind; assignedBlockId?: string; statuses?: XeroWorkStatus[] }): XeroWorkItem[] {\n return readMapItems(getXeroWorkItemsMap(editor)).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\nexport function upsertXeroWorkItemForEditor(editor: any, next: XeroWorkItem): XeroWorkItem {\n const map = getXeroWorkItemsMap(editor);\n if (!map) {\n return next;\n }\n\n let existing: XeroWorkItem | undefined;\n map.forEach((item) => {\n if (item?.idempotencyKey === next.idempotencyKey) existing = item;\n });\n\n const stored = existing ? mergeItem(existing, next) : next;\n map.set(stored.id, stored);\n return stored;\n}\n\nexport function updateXeroWorkReviewPayloadForEditor(editor: any, itemId: string, reviewPayload: Record<string, any>): XeroWorkItem | null {\n const map = getXeroWorkItemsMap(editor);\n if (!map) return null;\n const item = map.get(itemId);\n if (!item) return null;\n const updatedItem = { ...item, reviewPayload };\n map.set(itemId, updatedItem);\n return updatedItem;\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 const map = getXeroWorkItemsMap(editor);\n if (!map) return null;\n const item = map.get(itemId);\n if (!item) return null;\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\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 const map = getXeroWorkItemsMap(editor);\n if (!map) return null;\n const item = map.get(itemId);\n if (!item) return null;\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 map.set(itemId, updatedItem);\n return updatedItem;\n}\n","import type { PinnedConnection } from '@/mantine/blocks/action/actionTypes/_shared/ConnectionSelector';\n\n/**\n * A single line-item row as the template author typed it. Every cell is a\n * string so `{{blockId.field}}` and `{{item.field}}` references survive the\n * round-trip through JSON. Numeric cells are `Number()`-coerced at execute\n * time by the flow detail component.\n */\nexport interface XeroLineItemCells {\n Description: string;\n Quantity: string;\n UnitAmount: string;\n AccountCode: string;\n TaxType: string;\n ItemCode: string;\n DiscountRate: string;\n}\n\n/** Field keys the template author can map in iterative mode. */\nexport const LINE_ITEM_FIELD_KEYS = ['Description', 'Quantity', 'UnitAmount', 'AccountCode', 'TaxType', 'ItemCode', 'DiscountRate'] as const;\n\nexport type XeroLineItemsConfig =\n | { mode: 'manual'; rows: XeroLineItemCells[] }\n | {\n mode: 'iterative';\n /** DataInput value pointing at an upstream array (e.g. `{{formId.output.LineItems}}`). */\n source: string;\n /** Per-field mapping — cells may use `{{item.<field>}}` refs. */\n map: XeroLineItemCells;\n };\n\n/**\n * Template storage shape for `qi/xero.invoice.create`.\n * Mirrors `XERO_CREATE_INVOICE` verbatim. `LineItems` is structured (manual\n * rows or iterative binding) rather than a raw JSON string.\n */\nexport interface XeroInvoiceCreateInputs {\n connection: PinnedConnection | null;\n tenant_id: string;\n /** 'ACCREC' (sale) | 'ACCPAY' (bill). Required by Xero. */\n Type: string;\n Status: string;\n Date: string;\n DueDate: string;\n /** Prefer ContactID (UUID); ContactName is the fallback. */\n ContactID: string;\n ContactName: string;\n Reference: string;\n InvoiceNumber: string;\n CurrencyCode: string;\n /** Structured line-items config. See `XeroLineItemsConfig`. Required by Xero. */\n LineItems: XeroLineItemsConfig;\n}\n\nexport function emptyLineItemCells(): XeroLineItemCells {\n return {\n Description: '',\n Quantity: '1',\n UnitAmount: '',\n AccountCode: '',\n TaxType: '',\n ItemCode: '',\n DiscountRate: '',\n };\n}\n\nfunction emptyLineItems(): XeroLineItemsConfig {\n return { mode: 'manual', rows: [emptyLineItemCells()] };\n}\n\nfunction coerceCells(raw: any): XeroLineItemCells {\n const base = emptyLineItemCells();\n if (!raw || typeof raw !== 'object') return base;\n for (const key of LINE_ITEM_FIELD_KEYS) {\n const v = (raw as any)[key];\n if (typeof v === 'string') base[key] = v;\n else if (typeof v === 'number') base[key] = String(v);\n else if (typeof v === 'boolean') base[key] = v ? 'true' : 'false';\n }\n return base;\n}\n\n/**\n * Normalise whatever we find in `inputs.LineItems` into the structured shape.\n *\n * Handles three forms:\n * - Already-structured `XeroLineItemsConfig` (current shape) → returned as-is.\n * - Legacy JSON string (`'[{...}]'`) → migrated to `{ mode: 'manual', rows }`.\n * - Anything unrecognised → one empty manual row.\n */\nfunction normaliseLineItems(raw: unknown): XeroLineItemsConfig {\n if (raw && typeof raw === 'object') {\n const candidate = raw as { mode?: unknown; rows?: unknown; source?: unknown; map?: unknown };\n if (candidate.mode === 'iterative') {\n return {\n mode: 'iterative',\n source: typeof candidate.source === 'string' ? candidate.source : '',\n map: coerceCells(candidate.map),\n };\n }\n if (candidate.mode === 'manual') {\n const rows = Array.isArray(candidate.rows) ? candidate.rows.map(coerceCells) : [];\n return { mode: 'manual', rows: rows.length > 0 ? rows : [emptyLineItemCells()] };\n }\n }\n\n // Legacy: LineItems stored as a JSON string array of plain objects.\n if (typeof raw === 'string') {\n const trimmed = raw.trim();\n if (!trimmed) return emptyLineItems();\n try {\n const parsed = JSON.parse(trimmed);\n if (Array.isArray(parsed) && parsed.length > 0) {\n return { mode: 'manual', rows: parsed.map(coerceCells) };\n }\n } catch {\n // fall through\n }\n }\n\n return emptyLineItems();\n}\n\nexport function parseXeroInvoiceCreateInputs(raw: string | Record<string, any> | undefined): XeroInvoiceCreateInputs {\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 tenant_id: typeof parsed.tenant_id === 'string' ? parsed.tenant_id : '',\n Type: typeof parsed.Type === 'string' && parsed.Type ? parsed.Type : 'ACCREC',\n Status: typeof parsed.Status === 'string' ? parsed.Status : 'DRAFT',\n Date: typeof parsed.Date === 'string' ? parsed.Date : '',\n DueDate: typeof parsed.DueDate === 'string' ? parsed.DueDate : '',\n ContactID: typeof parsed.ContactID === 'string' ? parsed.ContactID : '',\n ContactName: typeof parsed.ContactName === 'string' ? parsed.ContactName : '',\n Reference: typeof parsed.Reference === 'string' ? parsed.Reference : '',\n InvoiceNumber: typeof parsed.InvoiceNumber === 'string' ? parsed.InvoiceNumber : '',\n CurrencyCode: typeof parsed.CurrencyCode === 'string' ? parsed.CurrencyCode : '',\n LineItems: normaliseLineItems(parsed.LineItems),\n };\n } catch {\n return {\n connection: null,\n tenant_id: '',\n Type: 'ACCREC',\n Status: 'DRAFT',\n Date: '',\n DueDate: '',\n ContactID: '',\n ContactName: '',\n Reference: '',\n InvoiceNumber: '',\n CurrencyCode: '',\n LineItems: emptyLineItems(),\n };\n }\n}\n\nexport function serializeXeroInvoiceCreateInputs(inputs: XeroInvoiceCreateInputs): string {\n return JSON.stringify(inputs);\n}\n\n/**\n * Numeric field keys — stringly-typed in the editor, `Number()`-coerced at\n * execute time before sending to Xero.\n */\nexport const NUMERIC_LINE_ITEM_FIELDS: Array<keyof XeroLineItemCells> = ['Quantity', 'UnitAmount', 'DiscountRate'];\n\n/**\n * Finalise a single resolved cells object into a Xero LineItem — strips empty\n * fields and coerces numerics. Exported so both the action run() and the\n * diff resolver can reuse the coercion rules.\n */\nexport function finaliseLineItem(cells: XeroLineItemCells): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of LINE_ITEM_FIELD_KEYS) {\n const raw = (cells[key] ?? '').trim();\n if (!raw) continue;\n if (NUMERIC_LINE_ITEM_FIELDS.includes(key)) {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n throw new Error(`Line item field ${key} must be a number; got \"${raw}\"`);\n }\n out[key] = n;\n } else {\n out[key] = raw;\n }\n }\n if (!out.Description) {\n out.Description = 'payment';\n }\n return out;\n}\n","import type { PinnedConnection } from '@/mantine/blocks/action/actionTypes/_shared/ConnectionSelector';\n\n/**\n * Template storage shape for `qi/xero.payment.create`.\n *\n * Mirrors the Composio `XERO_CREATE_PAYMENT` request — records a payment\n * against an existing AUTHORISED invoice. Used as the settlement step after\n * an on-chain payout: `Reference` carries the tx hash so the bookkeeper can\n * reconcile against the wallet/treasury feed.\n *\n * `Amount` is stringly-typed in the editor (so `{{...}}` refs survive\n * round-trip) and `Number()`-coerced at execute time.\n */\nexport interface XeroPaymentCreateInputs {\n connection: PinnedConnection | null;\n tenant_id: string;\n /** UUID of the invoice being paid. Resolved from the upstream capture step. */\n InvoiceID: string;\n /** UUID of the bank/treasury account in Xero the payment debits. Org-level config. */\n AccountID: string;\n /** Payment date (YYYY-MM-DD). Defaults to today at execute time if blank. */\n Date: string;\n /** Payment amount. Stringly-typed for refs; coerced at execute time. */\n Amount: string;\n /** Free-text reference — typically the on-chain tx hash for crypto payouts. */\n Reference: string;\n /** Optional currency rate for multicurrency payments. */\n CurrencyRate: string;\n}\n\nexport function parseXeroPaymentCreateInputs(raw: string | Record<string, any> | undefined): XeroPaymentCreateInputs {\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 tenant_id: typeof parsed.tenant_id === 'string' ? parsed.tenant_id : '',\n InvoiceID: typeof parsed.InvoiceID === 'string' ? parsed.InvoiceID : '',\n AccountID: typeof parsed.AccountID === 'string' ? parsed.AccountID : '',\n Date: typeof parsed.Date === 'string' ? parsed.Date : '',\n Amount: typeof parsed.Amount === 'string' ? parsed.Amount : typeof parsed.Amount === 'number' ? String(parsed.Amount) : '',\n Reference: typeof parsed.Reference === 'string' ? parsed.Reference : '',\n CurrencyRate: typeof parsed.CurrencyRate === 'string' ? parsed.CurrencyRate : '',\n };\n } catch {\n return {\n connection: null,\n tenant_id: '',\n InvoiceID: '',\n AccountID: '',\n Date: '',\n Amount: '',\n Reference: '',\n CurrencyRate: '',\n };\n }\n}\n\nexport function serializeXeroPaymentCreateInputs(inputs: XeroPaymentCreateInputs): string {\n return JSON.stringify(inputs);\n}\n","/**\n * Reference Resolver Utility\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\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 *\n * @param input - String containing references\n * @returns Array of parsed references\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 *\n * @param obj - Object to extract value from\n * @param path - Dot-separated path (e.g., \"props.email\" or \"props.user.name\")\n * @returns Value at the path, or undefined if not found\n */\nexport function getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => {\n return current?.[key];\n }, obj);\n}\n\n/**\n * Resolve a single reference by finding the block and extracting the property value\n *\n * @param blockId - ID of the block to reference\n * @param propPath - Property path (can be nested)\n * @param editorDocument - Array of all blocks in the editor\n * @param yRuntime - Optional Yjs runtime map for resolving action block output paths\n * @param scope - Optional local scope bindings (e.g. `{ item: <row> }` inside\n * an iterative mapper). `{{item.foo}}` resolves against\n * `scope.item.foo` before falling back to editor blocks.\n * @returns Resolved value, or undefined if block or property not found\n */\nexport function resolveSingleReference(blockId: string, propPath: string, editorDocument: any[], yRuntime?: any, scope?: Record<string, any>): any {\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 undefined;\n return getNestedValue(root, propPath);\n }\n\n if (!editorDocument || !Array.isArray(editorDocument)) {\n return undefined;\n }\n\n // Find the block by ID\n const block = editorDocument.find((b) => b.id === blockId);\n\n if (!block) {\n return undefined;\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 undefined;\n\n const runtimeState = yRuntime.get(blockId);\n if (!runtimeState?.output) return undefined;\n\n const innerPath = propPath.substring('output.'.length);\n const direct = getNestedValue(runtimeState.output, innerPath);\n if (direct !== undefined) return 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 return getNestedValue(runtimeState.output.data, innerPath);\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 return getNestedValue(runtimeState.output.http.data, innerPath);\n }\n\n return undefined;\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 undefined;\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;\n } catch (error) {\n return undefined;\n }\n }\n\n // Default behavior for other properties: direct prop access\n const value = getNestedValue(block.props, propPath);\n\n return value;\n}\n\n/**\n * Resolve all references in a string and return the resolved string\n *\n * @param input - String containing references (e.g., \"Hello {{user.name}}\")\n * @param editorDocument - Array of all blocks in the editor\n * @param options - Options for resolution\n * @returns String with all references resolved to their values\n */\nexport function resolveReferences(\n input: string | null | undefined,\n editorDocument: any[],\n options: {\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): string {\n const { fallback = '', stringifyObjects = true, yRuntime, scope } = options;\n\n // Handle null/undefined input\n if (input == null) {\n return '';\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 inputStr;\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 resolvedValue = resolveSingleReference(ref.blockId, ref.propPath, editorDocument, yRuntime, scope);\n\n // Convert resolved value to string\n let replacementStr: string;\n\n if (resolvedValue === undefined || resolvedValue === null) {\n replacementStr = fallback;\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 return result;\n}\n\n/**\n * Check if a string contains any references\n *\n * @param input - String to check\n * @returns True if the string contains at least one reference\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 *\n * @param blockId - Block ID\n * @param propPath - Property path\n * @returns Reference string in format {{blockId.propPath}}\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 *\n * @param obj - Object with potential references in its values\n * @param editorDocument - Array of all blocks in the editor\n * @param options - Resolution options\n * @returns New object with resolved values\n */\nexport function resolveObjectReferences<T extends Record<string, any>>(obj: T, editorDocument: any[], options?: Parameters<typeof resolveReferences>[2]): 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","import { getDiffResolver, type DiffResult } from '@/core/lib/actionRegistry';\nimport {\n finaliseLineItem,\n LINE_ITEM_FIELD_KEYS,\n parseXeroInvoiceCreateInputs,\n type XeroLineItemCells,\n type XeroLineItemsConfig,\n} from '@/core/lib/actionRegistry/actions/xero/invoiceCreate.types';\nimport { parseXeroPaymentCreateInputs } from '@/core/lib/actionRegistry/actions/xero/paymentCreate.types';\nimport { parseReferences, resolveReferences, resolveSingleReference } from '@/mantine/utils/referenceResolver';\n\nexport interface XeroBindings {\n invoiceCreateBlock: any | null;\n paymentCreateBlock: any | null;\n evaluateBlockId: string | null;\n}\n\nexport function resolveXeroBindings(editorDocument: any[] | undefined, invoiceBlockId: string, paymentBlockId: string): XeroBindings {\n if (!Array.isArray(editorDocument)) return { invoiceCreateBlock: null, paymentCreateBlock: null, evaluateBlockId: null };\n const findById = (id: string, expectedActionType: string): any | null => {\n const trimmed = String(id || '').trim();\n if (!trimmed) return null;\n const block = editorDocument.find((b) => b?.id === trimmed);\n if (!block || block.type !== 'action' || block.props?.actionType !== expectedActionType) return null;\n return block;\n };\n return {\n invoiceCreateBlock: findById(invoiceBlockId, 'qi/xero.invoice.create'),\n paymentCreateBlock: findById(paymentBlockId, 'qi/xero.payment.create'),\n evaluateBlockId: null,\n };\n}\n\nexport function findBoundXeroBlocks(editorDocument: any[] | undefined, deedDid: string, collectionId: string): XeroBindings {\n if (!Array.isArray(editorDocument)) return { invoiceCreateBlock: null, paymentCreateBlock: null, evaluateBlockId: null };\n const evaluateBlocks = editorDocument.filter((b) => b?.type === 'action' && b.props?.actionType === 'qi/claim.evaluate');\n const evaluateBlock =\n evaluateBlocks.find((b) => {\n const inputs = parseInputs(b?.props?.inputs);\n return inputs?.deedDid === deedDid && inputs?.collectionId === collectionId;\n }) ?? evaluateBlocks[0];\n if (!evaluateBlock) return { invoiceCreateBlock: null, paymentCreateBlock: null, evaluateBlockId: null };\n const evalInputs = parseInputs(evaluateBlock.props?.inputs);\n const bindings = resolveXeroBindings(editorDocument, String(evalInputs?.xeroInvoiceBlockId || ''), String(evalInputs?.xeroPaymentBlockId || ''));\n return { ...bindings, evaluateBlockId: String(evaluateBlock.id) };\n}\n\nfunction parseInputs(raw: unknown): Record<string, any> | null {\n if (!raw) return null;\n if (typeof raw === 'object') return raw as Record<string, any>;\n if (typeof raw === 'string') {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n }\n return null;\n}\n\nexport function buildClaimScope(\n claim: any,\n claimData: any,\n evaluateBlockId?: string,\n evaluateContext?: { deedDid?: string; collectionId?: string; evaluationOutput?: Record<string, any> }\n): Record<string, any> {\n const surveyAnswers = claimData && typeof claimData === 'object' ? (claimData as any).credentialSubject ?? (claimData as any).surveyAnswers ?? claimData : {};\n const evaluationOutput = evaluateContext?.evaluationOutput ?? {};\n const scope: Record<string, any> = {\n claim: {\n claimId: claim?.claimId || evaluationOutput.claimId || '',\n agentDid: claim?.agentDid || '',\n agentAddress: claim?.agentAddress || '',\n submissionDate: claim?.submissionDate || '',\n surveyAnswers,\n ...surveyAnswers,\n },\n evaluation: {\n transactionHash: evaluationOutput.transactionHash || '',\n amount: evaluationOutput.amount || '',\n date: new Date().toISOString().slice(0, 10),\n },\n };\n\n const trimmedId = String(evaluateBlockId || '').trim();\n if (trimmedId) {\n scope[trimmedId] = {\n output: {\n claimId: claim?.claimId || evaluationOutput.claimId || '',\n collectionId: evaluateContext?.collectionId || '',\n deedDid: evaluateContext?.deedDid || '',\n surveyAnswers,\n ...evaluationOutput,\n },\n };\n }\n\n return scope;\n}\n\ntype ResolveOpts = { yRuntime?: any; scope?: Record<string, any> };\n\nfunction resolveIterativeSource(source: string, editorDocument: any[], opts: ResolveOpts): any[] {\n const refs = parseReferences(source || '');\n if (refs.length === 0) return [];\n const ref = refs[0];\n const value = resolveSingleReference(ref.blockId, ref.propPath, editorDocument, opts.yRuntime, opts.scope);\n return Array.isArray(value) ? value : [];\n}\n\nfunction resolveCells(cells: XeroLineItemCells, editorDocument: any[], opts: ResolveOpts): XeroLineItemCells {\n const out: any = {};\n for (const key of LINE_ITEM_FIELD_KEYS) {\n out[key] = resolveReferences(cells[key] || '', editorDocument, opts);\n }\n return out as XeroLineItemCells;\n}\n\nexport function buildLineItemsArray(config: XeroLineItemsConfig, editorDocument: any[], opts: ResolveOpts): Array<Record<string, unknown>> {\n if (config.mode === 'manual') {\n if (config.rows.length === 0) throw new Error('At least one line item is required.');\n return config.rows.map((row) => finaliseLineItem(resolveCells(row, editorDocument, opts)));\n }\n\n const elements = resolveIterativeSource(config.source, editorDocument, opts);\n if (elements.length === 0) throw new Error('The bound source list is empty or could not be resolved.');\n return elements.map((element) => {\n const perItemOpts: ResolveOpts = { ...opts, scope: { ...(opts.scope || {}), item: element } };\n return finaliseLineItem(resolveCells(config.map, editorDocument, perItemOpts));\n });\n}\n\nexport async function resolveInvoiceWorkPayload(block: any, editorDocument: any[], scope: Record<string, any>): Promise<{ payload: Record<string, any>; preview: DiffResult[] }> {\n const parsed = parseXeroInvoiceCreateInputs(block?.props?.inputs);\n const opts: ResolveOpts = { scope };\n const resolveStr = (v: string | undefined) => resolveReferences(v || '', editorDocument, opts);\n\n const payload: Record<string, any> = {\n connection: parsed.connection,\n tenant_id: resolveStr(parsed.tenant_id),\n Type: resolveStr(parsed.Type) || 'ACCREC',\n Status: resolveStr(parsed.Status) || 'DRAFT',\n Date: resolveStr(parsed.Date),\n DueDate: resolveStr(parsed.DueDate),\n ContactID: resolveStr(parsed.ContactID),\n ContactName: resolveStr(parsed.ContactName),\n Reference: resolveStr(parsed.Reference),\n InvoiceNumber: resolveStr(parsed.InvoiceNumber),\n CurrencyCode: resolveStr(parsed.CurrencyCode),\n LineItems: buildLineItemsArray(parsed.LineItems, editorDocument, opts),\n };\n\n let preview: DiffResult[] = [];\n const resolver = getDiffResolver('qi/xero.invoice.create');\n if (resolver) {\n try {\n preview = await resolver.resolver({ ...payload, LineItems: parsed.LineItems }, {} as any);\n } catch {\n preview = [];\n }\n }\n\n return { payload, preview };\n}\n\nexport async function resolvePaymentWorkPayload(\n block: any,\n editorDocument: any[],\n baseScope: Record<string, any>,\n settlement: { invoiceId: string; transactionHash: string; amount: number; date?: string }\n): Promise<{ payload: Record<string, any>; preview: DiffResult[] }> {\n const parsed = parseXeroPaymentCreateInputs(block?.props?.inputs);\n const scope = {\n ...baseScope,\n invoice: { invoiceId: settlement.invoiceId, InvoiceID: settlement.invoiceId },\n evaluation: {\n transactionHash: settlement.transactionHash,\n amount: settlement.amount,\n date: settlement.date || new Date().toISOString().slice(0, 10),\n },\n };\n const opts: ResolveOpts = { scope };\n const resolveStr = (v: string | undefined) => resolveReferences(v || '', editorDocument, opts);\n\n const currencyRateRaw = resolveStr(parsed.CurrencyRate);\n const currencyRate = currencyRateRaw ? Number(currencyRateRaw) : undefined;\n const amountRaw = resolveStr(parsed.Amount);\n const amount = Number.isFinite(Number(amountRaw)) && Number(amountRaw) > 0 ? Number(amountRaw) : settlement.amount;\n\n const payload: Record<string, any> = {\n connection: parsed.connection,\n tenant_id: resolveStr(parsed.tenant_id),\n InvoiceID: resolveStr(parsed.InvoiceID) || settlement.invoiceId,\n AccountID: resolveStr(parsed.AccountID),\n Date: resolveStr(parsed.Date) || settlement.date || new Date().toISOString().slice(0, 10),\n Amount: amount,\n Reference: resolveStr(parsed.Reference) || settlement.transactionHash,\n CurrencyRate: typeof currencyRate === 'number' && Number.isFinite(currencyRate) ? currencyRate : undefined,\n };\n\n let preview: DiffResult[] = [];\n const resolver = getDiffResolver('qi/xero.payment.create');\n if (resolver) {\n try {\n preview = await resolver.resolver({ ...payload, Amount: String(payload.Amount) }, {} as any);\n } catch {\n preview = [];\n }\n }\n\n return { payload, preview };\n}\n\nexport function getInvoiceTotal(output: Record<string, any>): number {\n const total = typeof output.total === 'number' ? output.total : Number(output.total);\n return Number.isFinite(total) && total > 0 ? total : 0;\n}\n","import { registerAction } from '../../registry';\nimport type { ActionEventDefinition, OutputSchemaField } from '../../types';\nimport { buildXeroInvoiceWorkKey, upsertXeroWorkItemForEditor } from '../../../xeroWorkItems';\nimport { buildClaimScope, resolveInvoiceWorkPayload, resolveXeroBindings } from '../../../xeroWorkItemPayloads';\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\nregisterAction<EvaluateClaimRunInputs>({\n type: 'qi/claim.evaluate',\n can: 'claim/evaluate',\n sideEffect: true,\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 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.\n const handlers = ctx.handlers as any;\n const actorAddress = 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 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 const xeroInvoiceBlockId = String(inputs.xeroInvoiceBlockId || '').trim();\n if (decision === 'approve' && xeroInvoiceBlockId) {\n const editorDoc = (ctx.editor?.document as any[]) || [];\n const runtime = ctx.runtime;\n if (!runtime) {\n throw new Error('Cannot queue Xero invoice work: runtime state manager is unavailable');\n }\n\n const bindings = resolveXeroBindings(editorDoc, xeroInvoiceBlockId, String(inputs.xeroPaymentBlockId || ''));\n const invoiceBlock = bindings.invoiceCreateBlock;\n if (!invoiceBlock) {\n throw new Error('Cannot queue Xero invoice work: bound invoice block was not found');\n }\n\n const flowId = String(ctx.flowId || ctx.flowUri || 'flow');\n const scope = buildClaimScope(inputs.claimSnapshot || { claimId }, claimData || surveyAnswers, ctx.nodeId, {\n deedDid,\n collectionId,\n evaluationOutput: output,\n });\n const { payload } = await resolveInvoiceWorkPayload(invoiceBlock, editorDoc, scope);\n const idempotencyKey = buildXeroInvoiceWorkKey({\n flowId,\n evaluationBlockId: ctx.nodeId,\n claimId,\n invoiceBlockId: invoiceBlock.id,\n });\n\n upsertXeroWorkItemForEditor(ctx.editor, {\n id: idempotencyKey,\n kind: 'invoice.create',\n status: 'pending',\n assignedBlockId: invoiceBlock.id,\n idempotencyKey,\n source: {\n claimId,\n evaluationBlockId: ctx.nodeId,\n deedDid,\n collectionId,\n },\n originalPayload: payload,\n reviewPayload: payload,\n provenance: {\n createdAt: Date.now(),\n createdByDid: ctx.actorDid,\n templateBlockId: invoiceBlock.id,\n templateInputsSnapshot: invoiceBlock.props?.inputs,\n evaluationOutput: output,\n claimSnapshot: inputs.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/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 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: '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\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'vote', displayName: 'Vote', type: 'string', description: 'The vote cast (yes, no, no_with_veto, 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\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 const validVotes = ['yes', 'no', 'no_with_veto', '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 defaultRequiresConfirmation: false,\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 { 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/**\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 */\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\n const baseConfig: Record<string, unknown> = {\n proposalDurationAmount: duration.amount,\n proposalDurationUnit: duration.unit,\n proposalSubmissionPolicy: 'members',\n voteSwitching: false,\n };\n\n if (groupType === 'multisig') {\n const members = (memberConfig?.members || []) as Array<{ did: string }>;\n return {\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 nftContractAddress: memberConfig?.nftContractAddress || '',\n unstakingDuration: governance.unstakingDuration ? parseDuration(governance.unstakingDuration) : undefined,\n };\n }\n\n if (groupType === 'tokenStaking') {\n const tokenConfig = memberConfig?.tokenConfig || {};\n return {\n ...baseConfig,\n passingThreshold: thresholdNum === 0.5 ? 'majority' : 'percentage',\n passingThresholdPercentage: Math.round(thresholdNum * 100),\n tokenName: tokenConfig.tokenName || '',\n tokenSymbol: tokenConfig.tokenSymbol || '',\n tokenSupply: tokenConfig.tokenSupply || 0,\n distributionCategory: tokenConfig.distributionCategory || [],\n unstakingDuration: governance.unstakingDuration ? parseDuration(governance.unstakingDuration) : undefined,\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 passingThreshold: thresholdNum === 0.5 ? 'majority' : 'percentage',\n passingThresholdPercentage: Math.round(thresholdNum * 100),\n membershipCategory: Array.from(byRole.values()).map(({ dids, weight }) => ({\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 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\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 const pin = await handlers.requestPin({\n title: 'Sign Domain Card',\n description: 'Enter your PIN to sign the Domain Card credential',\n submitText: 'Sign',\n });\n\n const { signedCredential } = await handlers.signCredential({\n issuerDid,\n issuerType: 'user',\n credential: unsignedCredential,\n pin,\n });\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 handlers.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';\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 defaultRequiresConfirmation: false,\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 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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/execute',\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';\n\n/**\n * Payment block action — drives the worklist via the companion oracle.\n *\n * The block holds an array of `PaymentRow`s; this action def is invoked by\n * the FlowDetail's per-row and bulk-action buttons. It does NOT touch the\n * worker directly — it sends a structured prompt to the companion oracle\n * which:\n *\n * 1. Reads the payment block (via the editor sub-agent) to fetch the\n * selected row(s)' resolved fields + block-level static config\n * (worker URL, sender info, defaults).\n * 2. Calls the worker's batch route for the requested action\n * (`/payouts/propose/batch`, `/payouts/execute/batch`, or\n * `/payouts/status/batch`).\n * 3. Writes the per-row result back to the block via `edit_block` so the\n * UI's filter tabs and detail panels update reactively.\n *\n * The action accepts:\n * - `rowIds: string[]` — which rows in the block to operate on.\n * - `verb: 'propose'|'execute'|'check'` — which worker route to hit.\n * - `paymentBlockId: string` — the block ID so the oracle can edit_block\n * back into the right place.\n * - `delegationCid: string` — the user's UCAN delegation to the oracle.\n *\n * The block-level `workerBaseUrl`, `sender`, `customerType`, etc. live in\n * `block.props.inputs` and are read by the oracle from the same block —\n * we do NOT duplicate them in this action's inputs to avoid drift.\n */\nregisterAction({\n type: 'qi/payment.execute',\n can: 'payment/execute',\n sideEffect: true,\n defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n\n outputSchema: [\n { path: 'verb', displayName: 'Action verb', type: 'string' },\n { path: 'rowCount', displayName: 'Rows targeted', type: 'number' },\n { path: 'paymentBlockId', displayName: 'Payment block ID', type: 'string' },\n ],\n\n events: [\n {\n name: 'rows.completed',\n displayName: 'Payment rows completed',\n description: 'Fires after the oracle writes terminal status for one or more rows in this batch. Listeners can react to the just-completed payouts.',\n payloadSchema: [\n { path: 'paymentBlockId', displayName: 'Payment block ID', type: 'string' },\n { path: 'completedRowIds', displayName: 'Completed row IDs', type: 'string' },\n { path: 'failedRowIds', displayName: 'Failed row IDs', type: 'string' },\n ],\n },\n ],\n\n run: async (inputs, ctx) => {\n const rowIds = Array.isArray(inputs.rowIds) ? (inputs.rowIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.length > 0) : [];\n if (rowIds.length === 0) {\n throw new Error('rowIds is required — pick at least one row before sending');\n }\n\n const verb = String(inputs.verb || '')\n .trim()\n .toLowerCase();\n if (verb !== 'propose' && verb !== 'execute' && verb !== 'check') {\n throw new Error('verb is required and must be one of: \"propose\", \"execute\", \"check\"');\n }\n\n const paymentBlockId = String(inputs.paymentBlockId || '').trim();\n if (!paymentBlockId) {\n throw new Error('paymentBlockId is required');\n }\n\n const delegationCid = typeof inputs.delegationCid === 'string' ? inputs.delegationCid : '';\n\n const skillCtx = inputs.skill && typeof inputs.skill === 'object' ? (inputs.skill as { cid?: string; name?: string }) : null;\n\n if (!ctx.handlers?.askCompanion) {\n throw new Error('askCompanion handler is not available');\n }\n\n const verbDescription =\n verb === 'propose'\n ? 'Make payout proposals for the rows listed below.'\n : verb === 'execute'\n ? 'Execute the previously-proposed payouts for the rows listed below.'\n : 'Check status for the rows listed below.';\n\n const lines: string[] = [verbDescription];\n lines.push(\n \"Read the flow context and the payment block to find the worker base URL, sender info, defaults, and the rows. Follow the skill's SKILL.md for the workflow.\",\n `Payment block ID: ${paymentBlockId}`,\n `Verb: ${verb}`,\n `Row IDs (in this batch): ${rowIds.join(', ')}`\n );\n if (skillCtx?.name) lines.push(`Skill name: ${skillCtx.name}`);\n if (skillCtx?.cid) lines.push(`Skill CID: ${skillCtx.cid}`);\n if (delegationCid) lines.push(`UCAN delegation CID: ${delegationCid}`);\n\n await ctx.handlers.askCompanion(lines.join('\\n'));\n\n return {\n output: {\n verb,\n rowCount: rowIds.length,\n paymentBlockId,\n },\n completion: {\n state: 'awaiting_readback',\n readBack: {\n kind: 'paymentRows',\n paymentBlockId,\n rowIds,\n verb,\n },\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: true,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 defaultRequiresConfirmation: false,\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 { 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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 defaultRequiresConfirmation: false,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: false,\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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 defaultRequiresConfirmation: false,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: false,\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 defaultRequiresConfirmation: true,\n requiredCapability: 'flow/block/execute',\n eligibleForEventTrigger: true,\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\nfunction formatCoin(coin: { denom: string; amount: string }): string {\n const denom = coin.denom === USDC_DENOM ? 'USDC' : coin.denom === 'uixo' ? 'IXO' : coin.denom;\n return `${coin.amount} ${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","/**\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 { 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 { 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_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 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 xeroConnection.forEach((_, key) => xeroConnection.delete(key));\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/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\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 { isRuntimeRef } from '../../types/baseUcan';\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/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\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current == null || typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\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 /** TEMP Disablement - needs to be true TODO */\n ucanRequired: false, \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/** 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];\n if (!policy) {\n return VERSION_MANIFEST[LATEST_VERSION];\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 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 * as Y from 'yjs';\nimport type { RuntimeRef } from '../../types/baseUcan';\nimport { isRuntimeRef } from '../../types/baseUcan';\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/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/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/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\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\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// ─── 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","import * as Y from 'yjs';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { TriggerSpec } from '../../types/baseUcan';\nimport { getAction } from '../actionRegistry/registry';\nimport {\n computePendingInvocationId,\n computeBarrierInvocationId,\n mergeBarrierPayloads,\n queuePendingInvocation,\n readRunRecords,\n readBarrierState,\n recordBarrierEvent,\n clearBarrierState,\n snapshotInputRefs,\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/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 // 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 processRunRecord(yDoc, sourceBlockId, record, listenersBySource, getNodeOutput, runtimeMap);\n processBarrierRunRecord(yDoc, sourceBlockId, record, barrierListenersBySource, getNodeOutput, runtimeMap);\n }\n }\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): 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 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 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): 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 const allFired = allSources.length > 0 && allSources.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 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 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\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\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 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 * as Y from 'yjs';\nimport { getAction, 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 } 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 type { IxoEditorType } from '../../types/editor';\n\ntype 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';\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?: unknown;\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 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 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 }\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 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 type { ActionResult } from '../actionRegistry';\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 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","/**\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","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 'payment/execute': 'credit-card',\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 } 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';\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 // 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 operator: 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// ─── 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 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 const capabilities: FlowCapability[] = compiled.order.map((nodeId) => {\n const node = compiled.nodes[nodeId];\n return nodeToCapability(node);\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): 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 = trigger as TriggerSpec;\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","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 * 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, 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);\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);\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): 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 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. */\nfunction 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 { 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 * 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// ─── 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 * 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 if (existing.type === 'assign_actor' && existing.status === 'failed') {\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 },\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 submit_claim: 'flow/claim/submit',\n watch_udid: 'flow/observe',\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 { 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\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 }: ClassifyNodeStateInput): FlowAgentPublicNodeState {\n if (runtime.state === 'completed' || runtime.state === 'cancelled') return 'Done';\n if (runtime.state === 'failed' || runtime.error) return 'Blocked';\n\n const dueAt = getDueAt(block);\n if (dueAt != null && dueAt <= now) return 'Overdue';\n\n if (pendingInvocationCount > 0) return 'Pending';\n return 'Pending';\n}\n\nexport function snapshotNode(block: unknown, runtime: FlowNodeRuntimeState, now: number, pendingInvocationCount = 0): 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 });\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 snapshot.blockerCause = classifyBlockerCause(block, runtime) || 'unknown';\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';\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 const runtime = snapshot.runtime as Record<string, any>;\n if (actionType === 'qi/claim.submit' && runtime.output?.claimId && !runtime.output?.udid) {\n const command = queueIfAuthorized(context, options, 'watch_udid', snapshot.nodeId, 'Claim submitted but UDID is not yet observed', {\n claimId: runtime.output.claimId,\n timeoutMs: 86_400_000,\n });\n if (command) queued.push(command);\n }\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 === 'qi/claim.submit') {\n const command = queueIfAuthorized(context, options, 'submit_claim', snapshot.nodeId, 'Claim action is pending and agent is authorized to submit', {\n actionType,\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 for (const block of blocks) {\n const nodeId = getBlockId(block);\n if (!nodeId) continue;\n const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId).length;\n const snapshot = snapshotNode(block, getRuntime(context.yDoc, nodeId), now, pendingInvocationCount);\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 'submit_claim':\n return executor.submitClaim ? executor.submitClaim(command, context) : { commandId: command.id, success: false, error: 'No submitClaim handler configured' };\n case 'watch_udid':\n return executor.watchUdid ? executor.watchUdid(command, context) : { commandId: command.id, success: false, error: 'No watchUdid 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 { 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?: unknown;\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 '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":";AAEA,IAAM,UAAU,oBAAI,IAA8B;AAGlD,IAAM,sBAA8C;AAAA,EAClD,KAAK;AAAA,EACL,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EAC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QAAI,KAAK,SAAS;AAChB,aAAO;AAAA,QACL,UAAU;AAAA,QACV,WAAW,CAAC;AAAA,QACZ,gBAAgB,CAAC;AAAA,QACjB,kBAAkB,CAAC;AAAA,MACrB;AAAA,IACF;AAEA,SAAK,UAAU;AACf,QAAI;AACF,YAAM,SAAS,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":["output","value","BASELINE_OUTPUT","normalizeDecision","actions","members","SENSITIVE_PLAINTEXT_KEYS","SENSITIVE_PLAINTEXT_KEYS","formatCoin","USDC_DENOM","formatCoin","storedDelegation","getNodeOutput","fieldPath","getNestedValue","getNodeOutput","getNestedValue","getNodeOutput","Y","Y","runId","isYDoc","getYDoc","parseInputs","getRuntime","getEditor","makeRunId","getReconcileEditor","parseOutputRef","Y","Y","Y","Y","Y","fnv1a32","getRuntime","command","safeAppendAgentLedgerEvent","createYDocRuntimeManager","isRecord","statusForResult"]}