Workflow Class
The Workflow class enables you to create state machines for complex sequences of operations with conditional branching and data validation.
Usage exampleDirect link to Usage example
import { createWorkflow } from '@mastra/core/workflows'
import { z } from 'zod'
export const workflow = createWorkflow({
id: 'test-workflow',
inputSchema: z.object({
value: z.string(),
}),
outputSchema: z.object({
value: z.string(),
}),
})
Constructor parametersDirect link to Constructor parameters
id:
inputSchema:
outputSchema:
stateSchema?:
requestContextSchema?:
options?:
tracingPolicy?:
validateInputs?:
shouldPersistSnapshot?:
onFinish?:
status:
result?:
error?:
steps:
tripwire?:
runId:
workflowId:
resourceId?:
getInitData:
mastra?:
requestContext:
logger:
state:
onError?:
status:
error?:
steps:
tripwire?:
runId:
workflowId:
resourceId?:
getInitData:
mastra?:
requestContext:
logger:
state:
Running with initial stateDirect link to Running with initial state
When starting a workflow run, you can pass initialState to set the starting values for the workflow's state:
const run = await workflow.createRun()
const result = await run.start({
inputData: { value: 'hello' },
initialState: {
counter: 0,
items: [],
},
})
The initialState object should match the structure defined in the workflow's stateSchema. See Workflow State for more details.
Workflow statusDirect link to Workflow status
A workflow's status indicates its current execution state. The possible values are:
success:
failed:
suspended:
tripwire:
Handling tripwire statusDirect link to Handling tripwire status
When a workflow contains an agent step that triggers a tripwire, the workflow returns with status: 'tripwire' and includes tripwire details:
const run = await workflow.createRun()
const result = await run.start({ inputData: { message: 'Hello' } })
if (result.status === 'tripwire') {
console.log('Workflow terminated by tripwire:', result.tripwire?.reason)
console.log('Processor ID:', result.tripwire?.processorId)
console.log('Retry requested:', result.tripwire?.retry)
}
This is distinct from status: 'failed' which indicates an unexpected error. A tripwire status means a processor intentionally stopped execution (e.g., for content moderation).