# Workflow class

The `Workflow` class enables you to create state machines for complex sequences of operations with conditional branching and data validation.

## Usage example

```typescript
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(),
  }),
})
```

## Define schemas

You can define the workflow's `inputSchema` and `outputSchema` with any library that supports [Standard JSON Schema](https://standardschema.dev/json-schema). This includes libraries like [Zod](https://zod.dev/), [Valibot](https://valibot.dev/), and [ArkType](https://arktype.io/).

**Zod**:

```typescript
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { z } from "zod";

const step1 = createStep({...});

export const testWorkflow = createWorkflow({
  id: "test-workflow",
  inputSchema: z.object({
    message: z.string()
  }),
  outputSchema: z.object({
    output: z.string()
  })
})
  .then(step1)
  .commit();
```

**Valibot**:

```typescript
import { createWorkflow, createStep } from "@mastra/core/workflows";
import * as v from "valibot";
import { toStandardJsonSchema } from "@valibot/to-json-schema";

const step1 = createStep({...});

export const testWorkflow = createWorkflow({
  id: "test-workflow",
  inputSchema: toStandardJsonSchema(v.object({
    message: v.string()
  })),
  outputSchema: toStandardJsonSchema(v.object({
    output: v.string()
  }))
})
  .then(step1)
  .commit();
```

**ArkType**:

```typescript
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { type } from "arktype";

const step1 = createStep({...});

export const testWorkflow = createWorkflow({
  id: "test-workflow",
  inputSchema: type({
    message: "string"
  }),
  outputSchema: type({
    output: "string"
  })
})
  .then(step1)
  .commit();
```

## Constructor parameters

**id** (`string`): Unique identifier for the workflow

**inputSchema** (`StandardJSONSchemaV1`): Standard JSON Schema defining the input structure for the workflow

**outputSchema** (`StandardJSONSchemaV1`): Standard JSON Schema defining the output structure for the workflow

**stateSchema** (`StandardJSONSchemaV1`): Optional Standard JSON Schema for the workflow state. Automatically injected when using Mastra's state system. If not specified, type is 'any'.

**requestContextSchema** (`StandardJSONSchemaV1`): Standard JSON Schema for validating request context values. When provided, the context is validated at the start of run.start(), throwing an error if validation fails.

**schedule** (`WorkflowScheduleConfig | WorkflowScheduleConfig[]`): Optional cron schedule for the workflow. Accepts a single config or an array of configs to fire on multiple cadences. Setting this auto-promotes the workflow to the evented execution engine. See the scheduled workflows guide for usage.

**schedule.id** (`string`): Stable identifier for the schedule. Required when passing an array of schedules. Defaults to the workflow id when passing a single schedule object.

**schedule.cron** (`string`): A 5-, 6-, or 7-part cron expression. Validated at workflow construction time.

**schedule.timezone** (`string`): IANA timezone, for example "America/New\_York". Defaults to the host's local timezone. Set this explicitly in production so fire times do not depend on server locale.

**schedule.inputData** (`TInput`): Payload passed as the workflow's input on every fire.

**schedule.initialState** (`TState`): Initial state for the run.

**schedule.requestContext** (`Record<string, unknown>`): Request context attached to the run.

**schedule.metadata** (`Record<string, unknown>`): Arbitrary metadata persisted alongside the schedule row.

**options** (`WorkflowOptions`): Optional options for the workflow

**options.tracingPolicy** (`TracingPolicy`): Optional tracing policy for the workflow

**options.validateInputs** (`boolean`): Optional flag to determine whether to validate the workflow inputs. This also applies default values from zodSchemas on the workflow/step input/resume data. If input/resume data validation fails on start/resume, the workflow will not start/resume, it throws an error instead. If input data validation fails on a step execution, the step fails, causing the workflow to fail and the error is returned.

**options.shouldPersistSnapshot** (`(params: { stepResults: Record<string, StepResult<any, any, any, any>>; workflowStatus: WorkflowRunStatus }) => boolean`): Optional flag to determine whether to persist the workflow snapshot

**options.onFinish** (`(result: WorkflowFinishCallbackResult) => void | Promise<void>`): Callback invoked when workflow completes with any status (success, failed, suspended, tripwire). Receives the workflow result including status, output, error, and step results. Errors thrown in this callback are caught and logged, not propagated.

**options.onFinish.status** (`WorkflowRunStatus`): The workflow status: 'success', 'failed', 'suspended', or 'tripwire'

**options.onFinish.result** (`any`): The workflow output (when status is 'success')

**options.onFinish.error** (`SerializedError`): Error details (when status is 'failed')

**options.onFinish.steps** (`Record<string, StepResult>`): Individual step results with their status and output

**options.onFinish.tripwire** (`StepTripwireInfo`): Tripwire information (when status is 'tripwire')

**options.onFinish.runId** (`string`): The unique identifier for this workflow run

**options.onFinish.workflowId** (`string`): The workflow's identifier

**options.onFinish.resourceId** (`string`): Optional resource identifier (if provided when creating the run)

**options.onFinish.getInitData** (`() => any`): Function that returns the initial input data passed to the workflow

**options.onFinish.mastra** (`Mastra`): The Mastra instance (if workflow is registered with Mastra)

**options.onFinish.requestContext** (`RequestContext`): Request-scoped context data

**options.onFinish.logger** (`IMastraLogger`): The workflow's logger instance

**options.onFinish.state** (`Record<string, any>`): The workflow's current state object

**options.onError** (`(errorInfo: WorkflowErrorCallbackInfo) => void | Promise<void>`): Callback invoked only when workflow fails (failed or tripwire status). Receives error details and step results. Errors thrown in this callback are caught and logged, not propagated.

**options.onError.status** (`'failed' | 'tripwire'`): The workflow status (either 'failed' or 'tripwire')

**options.onError.error** (`SerializedError`): Error details

**options.onError.steps** (`Record<string, StepResult>`): Individual step results with their status and output

**options.onError.tripwire** (`StepTripwireInfo`): Tripwire information (when status is 'tripwire')

**options.onError.runId** (`string`): The unique identifier for this workflow run

**options.onError.workflowId** (`string`): The workflow's identifier

**options.onError.resourceId** (`string`): Optional resource identifier (if provided when creating the run)

**options.onError.getInitData** (`() => any`): Function that returns the initial input data passed to the workflow

**options.onError.mastra** (`Mastra`): The Mastra instance (if workflow is registered with Mastra)

**options.onError.requestContext** (`RequestContext`): Request-scoped context data

**options.onError.logger** (`IMastraLogger`): The workflow's logger instance

**options.onError.state** (`Record<string, any>`): The workflow's current state object

## Running with initial state

When starting a workflow run, you can pass `initialState` to set the starting values for the workflow's state:

```typescript
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](https://mastra.ai/docs/workflows/workflow-state) for more details.

## Workflow status

A workflow's `status` indicates its current execution state. The possible values are:

**success** (`string`): All steps finished executing successfully, with a valid result output

**failed** (`string`): Workflow encountered an error during execution, with error details available

**suspended** (`string`): Workflow execution is paused waiting for resume, with suspended step information

**tripwire** (`string`): Workflow was terminated by a processor tripwire. This occurs when an agent step within the workflow triggers a tripwire (e.g., content was blocked by a guardrail). The tripwire information is available on the result.

### Handling tripwire status

When a workflow contains an agent step that triggers a tripwire, the workflow returns with `status: 'tripwire'` and includes tripwire details:

```typescript
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).

## Related

- [Step Class](https://mastra.ai/reference/workflows/step)
- [Workflow State](https://mastra.ai/docs/workflows/workflow-state)
- [Control flow](https://mastra.ai/docs/workflows/control-flow)