Framework
An integration may start an approval today and send a signal when a supplier responds tomorrow. Use the REST API when the caller is external, or the workflow services in application code. Keep the instance identifier so the later signal reaches the correct run.
Endpoint:
POST /api/workflows/instances
Request Body:
{
"workflowId": "purchase-approval-v1",
"initialContext": {
"orderId": "order-123",
"customerId": "cust-456",
"amount": 150.00,
"items": [
{ "productId": "prod-1", "quantity": 2 }
]
},
"correlationKey": "order-123"
}
Response:
{
"id": "wf-inst-abc123",
"workflowId": "purchase-approval-v1",
"version": 1,
"status": "RUNNING",
"currentStepId": "start",
"context": { ... },
"correlationKey": "order-123",
"startedAt": "2024-01-15T10:00:00Z"
}
import { apiFetch } from '@open-mercato/ui/backend/utils/api'
async function startApprovalWorkflow(orderId: string, amount: number) {
const response = await apiFetch('/api/workflows/instances', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
workflowId: 'purchase-approval-v1',
initialContext: {
orderId,
amount,
requesterEmail: '[email protected]',
approverEmail: '[email protected]'
},
correlationKey: orderId
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(`Failed to start workflow: ${error.message}`)
}
const instance = await response.json()
console.log(`Workflow started: ${instance.id}`)
return instance
}
For server-side code, inject the workflow service via DI:
import { inject, injectable } from 'awilix'
import { WorkflowService } from '@/modules/workflows/lib/workflow-service'
@injectable()
export class OrderService {
constructor(
@inject('workflowService') private workflowService: WorkflowService
) {}
async createOrder(orderData: any) {
// Create order in database
const order = await this.orderRepository.create(orderData)
// Start workflow
const instance = await this.workflowService.startWorkflow({
workflowId: 'order-fulfillment-v1',
initialContext: {
orderId: order.id,
customerId: order.customerId,
items: order.items
},
correlationKey: order.id
})
// Store instance ID on order
order.workflowInstanceId = instance.id
await this.orderRepository.save(order)
return order
}
}
Endpoint:
POST /api/workflows/instances/{instanceId}/signal
Request Body:
{
"signalName": "payment-confirmed",
"payload": {
"transactionId": "txn_abc123",
"amount": 150.00,
"paidAt": "2024-01-15T10:30:00Z"
}
}
Response:
{
"success": true,
"instanceId": "wf-inst-abc123",
"signalReceived": "payment-confirmed",
"updatedContext": { ... }
}
async function sendPaymentConfirmation(
instanceId: string,
transactionId: string,
amount: number
) {
const response = await apiFetch(`/api/workflows/instances/${instanceId}/signal`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
signalName: 'payment-confirmed',
payload: {
transactionId,
amount,
paidAt: new Date().toISOString()
}
})
})
if (!response.ok) {
throw new Error('Failed to send signal')
}
return await response.json()
}
Integrate signals with external webhooks:
import { Router } from 'express'
import { WorkflowService } from '@/modules/workflows/lib/workflow-service'
const router = Router()
router.post('/webhooks/stripe', async (req, res) => {
const { orderId, transactionId, amount, status } = req.body
if (status !== 'succeeded') {
return res.status(200).json({ received: true })
}
// Find workflow instance by correlation key
const instances = await fetch(
`/api/workflows/instances?correlationKey=${orderId}`
).then(r => r.json())
if (instances.length === 0) {
return res.status(404).json({ error: 'Workflow not found' })
}
// Send signal to resume workflow
await fetch(`/api/workflows/instances/${instances[0].id}/signal`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
signalName: 'payment-confirmed',
payload: { transactionId, amount }
})
})
res.status(200).json({ received: true })
})
Endpoint:
GET /api/workflows/instances?status=RUNNING&correlationKey=order-123
Query Parameters:
status: Filter by status (RUNNING, COMPLETED, FAILED, etc.)workflowId: Filter by workflow definitioncorrelationKey: Filter by correlation keylimit, offset: PaginationResponse:
{
"instances": [
{
"id": "wf-inst-abc123",
"workflowId": "order-fulfillment-v1",
"status": "RUNNING",
"currentStepId": "wait-for-payment",
"correlationKey": "order-123",
"startedAt": "2024-01-15T10:00:00Z"
}
],
"total": 1
}
Endpoint:
GET /api/workflows/instances/{instanceId}
Response:
{
"id": "wf-inst-abc123",
"workflowId": "order-fulfillment-v1",
"version": 1,
"status": "RUNNING",
"currentStepId": "wait-for-payment",
"context": {
"orderId": "order-123",
"customerId": "cust-456",
"amount": 150.00
},
"correlationKey": "order-123",
"startedAt": "2024-01-15T10:00:00Z",
"workflowInstance": {
"id": "wf-inst-abc123",
// ... additional details
}
}
async function getOrderWorkflow(orderId: string) {
// Query by correlation key
const response = await apiFetch(
`/api/workflows/instances?correlationKey=${orderId}`
)
if (!response.ok) {
throw new Error('Failed to query workflows')
}
const { instances } = await response.json()
if (instances.length === 0) {
return null
}
// Get full details
const detailResponse = await apiFetch(
`/api/workflows/instances/${instances[0].id}`
)
return await detailResponse.json()
}
Endpoint:
POST /api/workflows/tasks/{taskId}/complete
Request Body:
{
"formData": {
"decision": "approve",
"comments": "Approved for budget 2024"
}
}
Response:
{
"success": true,
"taskId": "task-123",
"workflowInstanceId": "wf-inst-abc123",
"status": "COMPLETED"
}
async function approveRequest(taskId: string, comments: string) {
const response = await apiFetch(`/api/workflows/tasks/${taskId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
formData: {
decision: 'approve',
comments,
approvedAt: new Date().toISOString()
}
})
})
if (!response.ok) {
throw new Error('Failed to complete task')
}
return await response.json()
}
When the step authored decision buttons, pass the id of the one that was pressed:
await apiFetch(`/api/workflows/tasks/${taskId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ formData: { comments }, decisionId: 'reject' }),
})
decisionId is optional and additive – a task without decisions completes exactly as before. When present it does two things: it selects the outgoing route (the decision's durable transitionId wins over the default first-valid-transition evaluation) and it is recorded on the completion, under the reserved __decision key in user_tasks.form_data and in the USER_TASK_COMPLETED event. Because form data is merged into the run context, a downstream route condition can branch on context.__decision.
The lookup is constrained to routes leaving the step the task is parked on, and error and SLA-breach routes are excluded – a button can never send a run down a route that starts elsewhere, or down a path only a failure may reach. An unknown decisionId is resolved before anything is mutated and answered 400, so the task is left untouched rather than completed down the wrong route. A decision whose route no longer exists on the step logs a warning and falls back to normal routing instead of stranding the run.
A task inside a parallel branch records the decision but does not route on it: a branch advances through resumeBranch with its own token, and overriding its outgoing route is a parallel-execution change rather than a task-surface one.
GET /api/workflows/work-inbox # merged, filtered, ordered work items
POST /api/workflows/work-inbox/next # claim the top claimable item
POST /api/workflows/tasks/{id}/unclaim # release a claim back to its queue
GET /api/workflows/work-inbox (feature workflows.tasks.view) merges every registered source. Query parameters: kind, module, entityType, role, priority, status, overdue, myWork (alias myTasks), assignedTo, workflowInstanceId, limit, offset.
{
data: [ /* rows */ ],
pagination: { total, limit, offset, hasMore },
meta: { kinds: ['user_task'], degradedKinds: [] },
}
medium.limit is clamped to 100, silently: an over-large request succeeds with the clamped page rather than failing.user_task row still carries every field GET /api/workflows/tasks returns (including proposalId) alongside kind, moduleId, entityTypes, entityBindings, detailHref and actions.meta.degradedKinds names sources whose list() threw. Render the queue and say it may be incomplete; do not fail the page.GET /api/workflows/tasks is unchanged and keeps its full response shape – the inbox is a new route beside it, not a replacement of it.POST /api/workflows/work-inbox/next (feature workflows.tasks.claim) walks the caller's claimable queue in inbox order and claims the first item it wins, returning the claimed row. Nothing claimable is a 200 with data: null, not a 404. It accepts the same query string as the list, so the candidate set can be narrowed.
Claiming is a compare-and-set: claimUserTask takes the row with a conditional UPDATE … WHERE status = 'PENDING' AND claimed_by IS NULL. The candidate list is a plain read and is expected to be stale; two callers racing therefore never receive the same item – the loser's update affects zero rows and the handler moves on to the next candidate instead of failing.
Resolve the service directly when you need the same queue server-side:
const workInboxService = container.resolve('workInboxService')
const { rows, total, kinds, degradedKinds } = await workInboxService.listWorkInbox(query, {
scope: { tenantId, organizationIds, userId, roles },
resolve: (name) => container.resolve(name),
})
POST /api/workflows/tasks/{id}/reassign # feature workflows.tasks.reassign
GET /api/workflows/task-settings # feature workflows.tasks.view_all
PUT /api/workflows/task-settings # feature workflows.tasks.manage
GET /api/workflows/portal/tasks # customer feature portal.tasks.view
GET /api/workflows/portal/tasks/{id} # customer feature portal.tasks.view
POST /api/workflows/portal/tasks/{id}/complete # customer feature portal.tasks.complete
Every one of these is a new route; no existing route's URL, method or response fields changed. Which rows the existing task routes return did change – see Task Visibility for the full model, which is required reading before integrating against any of them.
// Take a colleague's task before acting on it. `view_all` grants reading, never acting:
// completing somebody else's task answers 409 TASK_ASSIGNED_TO_ANOTHER_USER.
await apiFetch(`/api/workflows/tasks/${taskId}/reassign`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assignedTo: myUserId, reason: 'Owner on leave' }),
})
Completing a task whose run is no longer active (COMPLETED, FAILED, CANCELLED, COMPENSATING or COMPENSATED) answers 409 with code: 'WORKFLOW_NOT_ACTIVE' and writes nothing – the task, the run context and the cursor stay as they were; the portal route answers its standard 404. Cancelling a run moves its PENDING / IN_PROGRESS tasks to CANCELLED and logs one USER_TASK_CANCELLED event per task, so they leave the open-task lists.
Reassignment stamps reassigned_by / reassigned_at / reassign_reason, logs a USER_TASK_REASSIGNED event, releases an in-flight claim, and returns an IN_PROGRESS task to PENDING. It honours x-om-ext-optimistic-lock-expected-updated-at when a client sends one. Its gate is visibility, not ownership – which is what makes it the remedy for a task nobody owns (403 TASK_NOT_ACTIONABLE on the act routes).
The portal routes are a new surface, not a relaxation: they take a portal session (not a bearer token), refuse a backoffice principal with 401, and the backoffice task routes still refuse a portal session with 401. GET /api/workflows/portal/tasks/{id} additionally returns canComplete, which is false for a company administrator reading a member's task. Every portal refusal is the same 404 body.
A USER_TASK with a deadline schedules its reminders and its breach once, at task creation, as delayed jobs on the existing workflow-activities queue (job kind task_sla) – the same absolute-deadline backstop WAIT_FOR_CONDITION uses. A new queue would need its own worker registration and its own database connection budget for jobs that are one row read plus an event.
deadlineAt is an absolute ISO instant on the payload and is never recomputed by the worker, so a queue running behind cannot silently extend an author's deadline.PENDING/IN_PROGRESS makes the job a no-op, the breach is claimed with a conditional UPDATE … WHERE status IN (…) AND escalated_at IS NULL, and a reminder is skipped once the task has escalated or the deadline has passed. At-least-once delivery therefore still fires each phase exactly once.lib/breach-routing.ts): an outgoing transition with kind: 'slaBreach' wins, otherwise the step's onBreach action applies (route bound to a durable transition id, reassign to a user id or a role name, or notify), otherwise nothing routes – which is exactly the previous behavior. A route whose transition no longer exists on the step resolves to "nothing", never to "follow whichever route happens to be valid": auto-routing a breach would advance the run past work the author never said could be skipped.status = 'ESCALATED' – an existing UserTaskStatus, so no state-machine change.route_skipped_branch.COMPLETED, FAILED, CANCELLED, COMPENSATING, COMPENSATED) is still recorded, but it neither follows a route nor marks the run for attention; the skip is logged as route_skipped_closed_run / attention_skipped_closed_run and the task stays open. (A run cancelled after its tasks were closed has no open task left, so its SLA jobs are no-ops.) Reminders, notify and reassign are unaffected. The breach is one-shot, so a route skipped on a FAILED run does not fire again after a retry.Subscribe to workflow events to react to state changes:
Create a subscriber in src/modules/your-module/subscribers/workflow-completed.ts:
import { WorkflowEvent } from '@/modules/workflows/data/entities'
export default async function handleWorkflowCompleted(event: WorkflowEvent) {
console.log(`Workflow ${event.workflowInstanceId} completed`)
// Access workflow context from event
const { orderId, amount } = event.eventData
// Trigger follow-up actions
await sendCompletionEmail(orderId)
await updateOrderStatus(orderId, 'WORKFLOW_COMPLETED')
}
export const metadata = {
event: 'workflow.completed',
persistent: true
}
Subscribe to these events:
workflow.started - New workflow instance createdworkflow.completed - Workflow finished successfullyworkflow.failed - Workflow encountered errorworkflow.cancelled - Workflow manually cancelledstep.entered - Workflow entered a stepstep.exited - Workflow left a stepuser_task.created - User task createduser_task.completed - User task completedsignal.received - External signal receivedGet the current workflow context:
const instance = await apiFetch(`/api/workflows/instances/${instanceId}`)
.then(r => r.json())
console.log(instance.context)
// { orderId: "order-123", amount: 150.00, ... }
Context is updated automatically through:
activities.<activityId>.output)For custom updates from outside the engine, patch the instance context over HTTP:
PATCH /api/workflows/instances/{instanceId}/context
Content-Type: application/json
{
"context": {
"gridApproval": { "status": "APPROVED", "reference": "GA-4471" }
}
}
{
"ok": true,
"instanceId": "instance-uuid",
"woken": ["await_grid_approval"]
}
The patch is merged into the run context, and any WAIT_FOR_CONDITION step whose predicate now holds is woken in the same call – woken names the step ids that resumed. The per-waiter poll job remains the durability backstop, so a missed call here costs latency, never correctness.
Rules worth knowing before you call it:
workflows.instances.update_context ACL feature. This is deliberately not folded into workflows.instances.signal: writing arbitrary run context is a strictly broader capability than sending a named signal.404, not 403.__result, _pendingAsyncActivities, __park and __error. Overwriting any of them would corrupt a running instance.Handle errors from API calls:
import { apiFetch } from '@open-mercato/ui/backend/utils/api'
async function safeStartWorkflow(workflowId: string, context: any) {
try {
const response = await apiFetch('/api/workflows/instances', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workflowId, initialContext: context })
})
if (!response.ok) {
const error = await response.json()
console.error('Workflow start failed:', error.message)
return null
}
return await response.json()
} catch (error) {
console.error('Network error:', error)
return null
}
}
Configure retry policies in activity definitions:
{
activityId: "call-payment-api",
activityType: "CALL_API",
retryPolicy: {
maxAttempts: 3,
backoff: "exponential"
},
compensate: true,
compensationActivity: {
activityType: "CALL_API",
config: { url: "https://api.example.com/refund" }
}
}
interface WorkflowService {
startWorkflow(params: {
workflowId: string
initialContext: any
correlationKey?: string
}): Promise<WorkflowInstance>
sendSignal(instanceId: string, params: {
signalName: string
payload?: any
}): Promise<void>
getInstance(instanceId: string): Promise<WorkflowInstance>
queryInstances(filters: {
status?: WorkflowStatus
workflowId?: string
correlationKey?: string
}): Promise<WorkflowInstance[]>
cancelInstance(instanceId: string): Promise<void>
}
interface WorkflowInstance {
id: string
workflowId: string
version: number
status: WorkflowStatus
currentStepId: string
context: Record<string, any>
correlationKey: string | null
startedAt: Date
completedAt: Date | null
updatedAt: Date
}
type WorkflowStatus =
| 'RUNNING'
| 'COMPLETED'
| 'FAILED'
| 'PAUSED'
| 'WAITING_FOR_SIGNAL'
| 'WAITING_FOR_ACTIVITIES'
| 'CANCELLED'
See Also: