Open MercatoDocsSearch docsAPI reference

Framework

Extending Workflows

When a process needs an operation the editor does not offer, identify the smallest extension that fits. An activity performs work at a step, a function exposes module code to the workflow, and a signal can resume an instance waiting for an external event.

Creating Custom Activity Types

Activity types are registry-driven. A single ActivityTypeEntry declares everything the engine and the visual editor need: the execute function, the config validation schema, the editor form spec, async capability, and dry-run behavior. The definition schema enum, the editor's type pickers, and the OpenAPI document all derive from the registry – registering the entry is the whole integration.

1. Register the Activity Type

import { z } from 'zod'
import { registerActivityType } from '@open-mercato/core/modules/workflows/lib/activity-registry'
import type { SmsService } from '@/modules/notifications/lib/sms-service'

const sendSmsConfigSchema = z.looseObject({
  to: z.string().min(1, 'SEND_SMS requires "to"'),
  message: z.string().min(1, 'SEND_SMS requires "message"'),
})

registerActivityType<z.infer<typeof sendSmsConfigSchema>>({
  id: 'SEND_SMS',
  icon: 'MessageSquare',
  i18nKey: 'workflows.activities.types.SEND_SMS',
  configSchema: sendSmsConfigSchema,
  form: [
    { id: 'to', component: 'text', required: true },
    { id: 'message', component: 'textarea', required: true },
  ],
  execute: async (config, ctx, deps) => {
    const smsService = deps.container.resolve<SmsService>('smsService')
    const result = await smsService.send({ to: config.to, message: config.message })
    return { messageId: result.messageId, sentAt: new Date().toISOString() }
  },
  async: { capable: true },
})

Entry contract:

Variable interpolation ({{context.*}}, {{workflow.*}}, {{now}}, allow-listed {{env.*}}) is applied by the engine before your execute receives the config – at dispatch time for sync activities and at enqueue time for async ones. Do not re-implement it.

2. Use the Custom Activity

{
  "activityId": "notify-customer",
  "activityName": "Send SMS Notification",
  "activityType": "SEND_SMS",
  "config": {
    "to": "{{context.customerPhone}}",
    "message": "Your order {{context.orderId}} has been shipped!"
  }
}

Workflow Function Descriptors (EXECUTE_FUNCTION)

EXECUTE_FUNCTION resolves functions through DI at run time. To make a function discoverable in the editor's picker, register a descriptor:

import { registerWorkflowFunctions } from '@open-mercato/core/modules/workflows/lib/workflow-function-registry'

registerWorkflowFunctions([
  { name: 'calculateVolumeDiscount', labelKey: 'my_module.workflows.functions.calculateVolumeDiscount' },
])

listWorkflowFunctions() returns all registered descriptors; the picker keeps a free-text fallback for unregistered names.

Workflow-Safe Commands (UPDATE_ENTITY)

UPDATE_ENTITY executes commands through the command bus, but only commands explicitly declared workflow-safe are allowed – anything else is rejected at execution time. Register the allowlist from the module that owns the command:

import { registerWorkflowSafeCommands } from '@open-mercato/core/modules/workflows/lib/workflow-safe-commands'

registerWorkflowSafeCommands([
  { commandId: 'my_module.things.update', requiredFeatures: ['my_module.edit'] },
])

requiredFeatures are checked against the workflow user's ACL before the command runs. listWorkflowSafeCommands() backs the editor's command picker via GET /api/workflows/commands.

Command Output Schemas

Command handlers can declare an outputSchema so workflow tooling knows what an UPDATE_ENTITY activity returns:

import { z } from 'zod'
import type { CommandHandler } from '@open-mercato/shared/lib/commands/types'

const updateThingCommand: CommandHandler<UpdateThingInput, { thingId: string }> = {
  id: 'my_module.things.update',
  outputSchema: z.object({ thingId: z.string().uuid() }),
  async execute(input, ctx) { /* ... */ },
}

commandRegistry.outputSchemaOf(commandId) returns the declared schema (or null). UPDATE_ENTITY's registry entry uses it for its output contract and degrades honestly to 'unknown' when a command has not declared one.

Event Payload Schemas (Typed Triggers)

EventDefinition accepts an optional payloadSchema so workflow triggers can offer typed payload paths instead of asking authors to type them from memory. It is a flat field list, not a nested JSON Schema – nested shapes are declared as dot-paths:

const events = [
  {
    id: 'my_module.widget.scored',
    label: 'Widget Scored',
    entity: 'widget',
    category: 'lifecycle',
    payloadSchema: {
      fields: [
        { path: 'id', type: 'text' },
        { path: 'score', type: 'number' },
        { path: 'customer.id', type: 'text', optional: true },
      ],
    },
  },
] as const

Only declare fields the emitter verifiably sends. A wrong declaration is worse than none, because the editor will offer paths that never arrive.

Transition Conditions (condition)

workflowTransitionSchema accepts an optional condition, typed by business_rules' own conditionExpressionSchema:

{
  "transitionId": "qualified",
  "fromStepId": "qualify_gate",
  "toStepId": "contact_attempted",
  "trigger": "auto",
  "condition": { "operator": "AND", "rules": [{ "field": "leadScore", "operator": ">", "value": 60 }] }
}

Warning · This field used to be stripped on save

The engine has always evaluated transition.condition, but the definition schema did not declare it – so Zod's object-stripping silently discarded it on every save. If you have a definition whose inline route conditions never seemed to take effect, this is why; re-saving it through the current schema preserves them.

Conditions inherit the business-rules safety bounds (nesting depth, rules per group, field-path length), and the WAIT_FOR_CONDITION step's predicate is validated by the same API validator.

Endpoint Catalog (CALL_API)

GET /api/workflows/endpoints serves a trimmed, in-process projection of the application's OpenAPI surface – path, method, summary, tag, parameters and declared request/response schemas – for the CALL_API endpoint picker. Paths are /api-prefixed to match CALL_API's own URL contract.

An endpoint whose response is not declared with a Zod schema simply omits responseSchema, and consumers degrade to unknown typing rather than inventing a shape. Declaring typed responses on your own routes is therefore what makes the ledger downstream of a CALL_API step useful: the resolved response schema becomes the activity's output contract, wired through the bindCallApiResponseSchemaResolver seam. Endpoints outside the catalogue remain authorable as free text.

Agent Outcome Contracts (INVOKE_AGENT)

When the enterprise agent-orchestration module is present, INVOKE_AGENT's output contract is resolved through an optional method on the existing agentWorkflowBridge DI service, listAgentOutcomeContracts(), read duck-typed by core. Core never imports the enterprise module, no new DI key is introduced, and when the peer is absent every agent contract degrades to unknown instead of throwing. See the agent-orchestrator module guide for the enterprise side.

The Context Ledger

The editor's variable picker and unresolved-reference warnings are fed by a per-step context ledger – a pure computation of which context paths are available when each step runs.

Test-Step Endpoint (Mock-First)

POST /api/workflows/definitions/[id]/test-step dry-runs a single activity config against a caller-supplied sample context. It is gated on the workflows.definitions.test_run ACL feature and is strictly mock-first: the route never calls entry.execute. The config is interpolated exactly like real execution (via the exported interpolateVariables), then:

Declare a mock on your custom activity types so workflow authors can test steps that use them.

Work Inbox Sources (WorkInboxSourceProvider)

The Work Inbox (GET /api/workflows/work-inbox) is a projection over several sources, not a table. Core registers the user_task source; any module can contribute its own kind of work to the same queue by registering a provider.

Register from your module's di.ts, at module-DI load time:

import {
  registerWorkInboxSources,
  type WorkInboxSourceProvider,
} from '@open-mercato/core/modules/workflows/lib/work-inbox/provider'

const approvalSource: WorkInboxSourceProvider = {
  kind: 'my_module_approval',
  moduleId: 'my_module',
  // Injection spot id the task detail view renders for this kind, when any.
  render: 'work-inbox:my_module_approval:detail',
  actions: [
    {
      id: 'claim',
      labelKey: 'my_module.approvals.actions.claim',
      endpoint: '/api/my_module/approvals/{id}/claim',
      appliesTo: 'claimable',
    },
  ],
  async list(query, context) {
    const em = context.resolve<EntityManager>('em')
    // MUST filter on context.scope.tenantId, and on scope.organizationIds
    // when it is non-null (null is the unrestricted-operator wildcard).
    const rows = await loadApprovals(em, query, context.scope)
    return { rows, total: rows.length }
  },
}

registerWorkInboxSources([{ moduleId: 'my_module', sources: [approvalSource] }])

Contract notes:

Task Form Renderers (formKey)

A USER_TASK step can declare userTaskConfig.formKey to render its form with a module-supplied component instead of the built-in field renderer. Register the renderer once, keyed by that string:

import {
  registerTaskFormRenderer,
} from '@open-mercato/core/modules/workflows/lib/task-form-registry'

registerTaskFormRenderer({
  formKey: 'my_module.credit_review',
  titleKey: 'my_module.credit_review.formTitle',
  Renderer: CreditReviewForm, // ({ context, onChange }) => JSX
  inputSchema: creditReviewPrefillSchema,   // optional
  outputSchema: creditReviewPayloadSchema,  // optional
})

The renderer receives a typed TaskFormRendererContext – task id and name, the resolved formKey, the authored formSchema, the task's entityBindings, the decision ids the surface will render beside the form, current values, a disabled flag while a completion is in flight, and the surrounding locale – and calls onChange(values) so the host keeps owning the state, exactly as the built-in form does.

Contract notes:

Structured Validation Error Bodies

Schema failures on the definitions POST/PUT respond 400 with { error: 'Validation failed', details: [...] }. Each details entry is normalized by lib/definition-error-body.ts to { path, code, message, expected?, got? } – path and message are preserved from the previous shape, so existing parsers (including formatWorkflowValidationError) keep working, while code/expected/got enable precise editor diagnostics.

Custom Step Handlers

Implement custom step types by creating step handlers.

1. Define the Step Handler

// src/modules/workflows/lib/step-handlers/approval-matrix.ts
import { StepDefinition, StepExecutionContext, StepResult } from '../types'

export async function executeApprovalMatrixStep(
  definition: StepDefinition,
  context: StepExecutionContext
): Promise<StepResult> {
  const { amount, requesterLevel } = context.workflowContext

  // Determine required approvers based on amount and level
  const approvers = determineApprovers(amount, requesterLevel)

  // Create tasks for all required approvers
  const tasks = await Promise.all(
    approvers.map(approverId =>
      context.taskService.createTask({
        workflowInstanceId: context.workflowInstanceId,
        stepInstanceId: context.stepInstanceId,
        taskName: `Approve Request - $${amount}`,
        assignedTo: approverId,
        formSchema: [
          {
            fieldName: 'decision',
            fieldType: 'select',
            options: ['approve', 'reject'],
            required: true
          }
        ]
      })
    )
  )

  return {
    success: true,
    output: {
      tasksCreated: tasks.length,
      approvers
    },
    waitForCompletion: true // Step waits for tasks to complete
  }
}

function determineApprovers(amount: number, requesterLevel: string): string[] {
  if (amount > 100000) {
    return ['cfo-user-id', 'ceo-user-id'] // Dual approval
  } else if (amount > 10000) {
    return ['director-user-id']
  } else {
    return ['manager-user-id']
  }
}

2. Register the Step Handler

// src/modules/workflows/lib/step-executor.ts
import { executeApprovalMatrixStep } from './step-handlers/approval-matrix'

export const stepHandlers = {
  START: executeStartStep,
  END: executeEndStep,
  USER_TASK: executeUserTaskStep,
  AUTOMATED: executeAutomatedStep,
  WAIT_FOR_SIGNAL: executeWaitForSignalStep,
  SUB_WORKFLOW: executeSubWorkflowStep,
  APPROVAL_MATRIX: executeApprovalMatrixStep // Custom step type
}

export async function executeStep(
  definition: StepDefinition,
  context: StepExecutionContext
): Promise<StepResult> {
  const handler = stepHandlers[definition.stepType]

  if (!handler) {
    throw new Error(`Unknown step type: ${definition.stepType}`)
  }

  return await handler(definition, context)
}

3. Use the Custom Step

{
  "stepId": "approval-matrix",
  "stepName": "Multi-Level Approval",
  "stepType": "APPROVAL_MATRIX",
  "config": {
    "approvalLevels": {
      "manager": 10000,
      "director": 100000,
      "executive": 1000000
    }
  }
}

Custom Signal Processors

Process signals with custom logic before merging into workflow context.

1. Define the Signal Processor

// src/modules/workflows/lib/signal-processors/payment-confirmed.ts
import { SignalPayload, ProcessedSignal } from '../types'

export async function processPaymentConfirmedSignal(
  signalName: string,
  payload: SignalPayload,
  workflowContext: any
): Promise<ProcessedSignal> {
  // Validate payload
  if (!payload.transactionId || !payload.amount) {
    throw new Error('Invalid payment confirmation payload')
  }

  // Enrich payload with additional data
  const paymentDetails = await fetchPaymentDetails(payload.transactionId)

  // Transform payload before merging into context
  return {
    transactionId: payload.transactionId,
    paidAmount: payload.amount,
    paymentMethod: paymentDetails.method,
    paymentVerified: paymentDetails.status === 'verified',
    processedAt: new Date().toISOString()
  }
}

async function fetchPaymentDetails(transactionId: string): Promise<any> {
  // Call payment gateway API to verify transaction
  const response = await fetch(`https://payment-gateway.com/transactions/${transactionId}`)
  return await response.json()
}

2. Register the Signal Processor

// src/modules/workflows/lib/signal-handler.ts
import { processPaymentConfirmedSignal } from './signal-processors/payment-confirmed'

export const signalProcessors: Record<string, SignalProcessor> = {
  'payment-confirmed': processPaymentConfirmedSignal,
  'approval-granted': processApprovalGrantedSignal,
  // Add more processors as needed
}

export async function processSignal(
  signalName: string,
  payload: any,
  workflowContext: any
): Promise<any> {
  const processor = signalProcessors[signalName]

  if (processor) {
    // Use custom processor
    return await processor(signalName, payload, workflowContext)
  }

  // Default: return payload as-is
  return payload
}

Business Rules Integration

Integrate business rules for transition conditions.

1. Reference Business Rules in Transitions

{
  "transitionId": "review-to-approved",
  "fromStepId": "review",
  "toStepId": "approved",
  "trigger": "manual",
  "preConditions": [
    {
      "ruleId": "approval-required",
      "ruleReference": "purchase.requires-manager-approval"
    }
  ]
}

2. Evaluate Business Rules

// src/modules/workflows/lib/condition-evaluator.ts
import { BusinessRulesService } from '@/modules/business-rules/lib/business-rules-service'

export async function evaluateConditions(
  conditions: Condition[],
  context: any,
  container: any
): Promise<boolean> {
  for (const condition of conditions) {
    if (condition.ruleReference) {
      // Evaluate business rule
      const rulesService = container.resolve<BusinessRulesService>('businessRulesService')
      const result = await rulesService.evaluate(condition.ruleReference, context)

      if (!result.passed) {
        return false
      }
    } else if (condition.expression) {
      // Evaluate inline expression
      const result = evaluateExpression(condition.expression, context)

      if (!result) {
        return false
      }
    }
  }

  return true
}

function evaluateExpression(expression: string, context: any): boolean {
  // Simple expression evaluator (use a library like expr-eval for production)
  try {
    const fn = new Function('context', `return ${expression}`)
    return fn(context)
  } catch (error) {
    console.error('Expression evaluation failed:', error)
    return false
  }
}

Testing Custom Implementations

Unit Tests

Test activity executors in isolation:

// src/modules/workflows/lib/activities/send-sms.test.ts
import { executeSendSmsActivity } from './send-sms'
import { mock, MockProxy } from 'jest-mock-extended'
import { SmsService } from '@/modules/notifications/lib/sms-service'

describe('executeSendSmsActivity', () => {
  let smsService: MockProxy<SmsService>

  beforeEach(() => {
    smsService = mock<SmsService>()
  })

  it('should send SMS with interpolated variables', async () => {
    const definition = {
      activityId: 'send-sms',
      activityType: 'SEND_SMS',
      config: {
        to: '{{context.customerPhone}}',
        message: 'Order {{context.orderId}} shipped!'
      }
    }

    const context = {
      workflowContext: {
        customerPhone: '+1234567890',
        orderId: 'order-123'
      },
      container: {
        resolve: (name: string) => {
          if (name === 'smsService') return smsService
        }
      }
    }

    smsService.send.mockResolvedValue({ messageId: 'msg-123' })

    const result = await executeSendSmsActivity(definition, context as any)

    expect(result.success).toBe(true)
    expect(result.output?.messageId).toBe('msg-123')
    expect(smsService.send).toHaveBeenCalledWith({
      to: '+1234567890',
      message: 'Order order-123 shipped!'
    })
  })

  it('should handle errors gracefully', async () => {
    const definition = {
      activityId: 'send-sms',
      activityType: 'SEND_SMS',
      config: { to: '+1234567890', message: 'Test' }
    }

    const context = {
      workflowContext: {},
      container: {
        resolve: () => smsService
      }
    }

    smsService.send.mockRejectedValue(new Error('Network error'))

    const result = await executeSendSmsActivity(definition, context as any)

    expect(result.success).toBe(false)
    expect(result.error).toContain('Network error')
  })
})

Integration Tests

Test workflows end-to-end:

// src/modules/workflows/__tests__/custom-activity.integration.test.ts
import { WorkflowService } from '../lib/workflow-service'
import { createTestContainer } from '@/test/test-container'

describe('Workflow with custom SEND_SMS activity', () => {
  let workflowService: WorkflowService
  let container: any

  beforeAll(async () => {
    container = await createTestContainer()
    workflowService = container.resolve('workflowService')
  })

  it('should execute workflow with SEND_SMS activity', async () => {
    // Start workflow
    const instance = await workflowService.startWorkflow({
      workflowId: 'notification-workflow-v1',
      initialContext: {
        customerPhone: '+1234567890',
        orderId: 'order-123'
      }
    })

    // Wait for completion
    await waitForWorkflowCompletion(instance.id)

    // Verify workflow completed
    const updatedInstance = await workflowService.getInstance(instance.id)
    expect(updatedInstance.status).toBe('COMPLETED')

    // Verify SMS was sent (check activity output)
    expect(updatedInstance.context.activities['send-sms'].output.messageId).toBeDefined()
  })
})

Example: Custom "SEND_SMS" Activity

Complete implementation:

// src/modules/workflows/lib/activities/send-sms.ts
import { ActivityDefinition, ActivityExecutionContext, ActivityResult } from '../types'
import { SmsService } from '@/modules/notifications/lib/sms-service'

export async function executeSendSmsActivity(
  definition: ActivityDefinition,
  context: ActivityExecutionContext
): Promise<ActivityResult> {
  const { to, message } = definition.config

  // Interpolate variables
  const interpolatedTo = interpolateVariables(to, context.workflowContext)
  const interpolatedMessage = interpolateVariables(message, context.workflowContext)

  try {
    const smsService = context.container.resolve<SmsService>('smsService')

    const result = await smsService.send({
      to: interpolatedTo,
      message: interpolatedMessage
    })

    return {
      success: true,
      output: {
        messageId: result.messageId,
        sentAt: new Date().toISOString(),
        to: interpolatedTo
      }
    }
  } catch (error: any) {
    return {
      success: false,
      error: error.message,
      retryable: error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT'
    }
  }
}

function interpolateVariables(template: string, context: any): string {
  return template.replace(/\{\{(.+?)\}\}/g, (match, path) => {
    const value = path.split('.').reduce((obj: any, key: string) => obj?.[key], context)
    return value !== undefined ? String(value) : match
  })
}

Best Practices

For Custom Activities

For Custom Step Handlers

For Signal Processors

Next Steps

See Also:

Previous: Entity Updates (UPDATE_ENTITY) · Next: Workflows Framework