Workflows

Define and run an ordered sequence of agents and tools. Start with a sequential workflow, then add branches, parallel steps, or approvals where the task requires them.

For the distinction between a workflow definition and its executions, see Workflow.

Prerequisites

  • A Veryfront project with the workflows/ directory available (see Create project).
  • Any agents or tools referenced by a step are defined in agents/ or tools/ (see Agents and Tools).
  • A provider configured for any agents the workflow uses (see Providers).

Define a workflow

Create a file in workflows/:

workflows/content-pipeline.ts
import { step, workflow } from "veryfront/workflow"; export default workflow({  id: "content-pipeline",  integrationRequirements: [{    integration: "slack",    requiredScopes: ["channels:read"],    resources: [{ kind: "channel", id: "C012345" }],  }],  steps: [    step("research", { agent: "researcher" }),    step("write", { agent: "writer" }),    step("review", { agent: "editor" }),  ],});

Steps run in order. Each step's output is available to the next step via the workflow context. Use integrationRequirements only for explicit access that scheduled workflow runs require. Veryfront does not infer integration requirements from workflow steps, nested workflows, agents, tools, or source text.

Nested workflows

When using subWorkflow, child node IDs are scoped to that sub-workflow while the run is executing. A child ID must not collide with a node ID in an enclosing workflow. Keep sibling sub-workflows' child IDs distinct as well; completed child state is retained for resuming the owning sub-workflow and is never reused by a different sibling.

Two sub-workflows that can run at the same time and declare the same child ID fail the run before either one starts. Give them distinct child IDs, or add a dependency so they run in sequence, which is allowed.

Veryfront can only compare child IDs it can read from the definition. Child IDs exist only once the node runs when a subWorkflow builds its steps from a callback, when a branch that can reach a sub-workflow selects its arm, when a sub-workflow sits inside a map, or when a loop or map builds its steps from a callback.

Workflow ID references are not supported in this execution context, so pass the WorkflowDefinition object instead. Veryfront runs the first callback-defined producer alone and defers other composite producers to a later batch.

A loop or map with callback steps is deferred even when it contains no sub-workflow, because its contents are unknown before it runs. Nodes whose child IDs are visible in the definition still run in parallel with each other. Two consequences to expect: throughput drops around these nodes, and their approvals are raised one run at a time instead of together.

Workflow context persistence

Workflow context must be JSON-representable. Veryfront stores suspended workflow runs as JSON, and the memory backend applies the same persistence contract as durable backends so local development and production read back the same values.

The same rules apply to the step input and output that each node state stores. This includes the results that a nested workflow holds while it waits for an approval or event. Their paths start with nodeStates.input or nodeStates.output.

Use plain JSON values in step output: strings, numbers, booleans, null, arrays, and plain objects. Values that JSON cannot encode, such as BigInt or circular references, fail persistence with a redacted context path. Veryfront keeps the fixed input and step structure and array indices, but replaces runtime object keys with <redacted> so payload identifiers do not enter logs.

Some JavaScript values can be stored only after JSON rewrites them. By default, Veryfront logs a warning and persists the normalized JSON value:

Value written to contextValue read back from context
new Date(0)"1970-01-01T00:00:00.000Z"
new Map([["a", 1]]){}
{ missing: undefined }{}
Number.NaNnull
Class instancePlain object with enumerable fields

On edge hosts that cannot identify proxies without invoking project hooks, default mode still warns for built-ins that Veryfront can identify from native slots. It cannot safely distinguish every class instance from a proxy-backed plain object, so use strictContext when persistence must reject every value whose identity cannot be verified.

Enable strictContext on a built-in backend to reject these lossy values instead of warning and normalizing:

TypeScript
import { MemoryBackend, RedisBackend } from "veryfront/workflow"; const backend = new MemoryBackend({ strictContext: true });const durableBackend = new RedisBackend({ url: Deno.env.get("REDIS_URL")!, strictContext: true });

Start a workflow

Define workflows in workflows/, then start them from the surface that owns the user or system event.

Start pointUse when
API routeA user action or webhook starts the run.
Agent toolAn agent decides whether to start the run.
TaskBackground work starts the run.
Client UIThe UI calls an API route that starts the run.

Use createWorkflowClient() to register and start a workflow from server code:

app/api/start-content-workflow/route.ts
import { getAgent, getAllAgentIds } from "veryfront/agent";import { toolRegistry } from "veryfront/tool";import { createWorkflowClient } from "veryfront/workflow";import contentPipeline from "../../../workflows/content-pipeline.ts"; const agentRegistry = {  get: getAgent,  list: getAllAgentIds,}; const workflows = createWorkflowClient({  executor: {    stepExecutor: {      agentRegistry,      toolRegistry,    },  },}); workflows.register(contentPipeline); export async function POST(request: Request) {  const input = await request.json();  const handle = await workflows.start("content-pipeline", input);   return Response.json({ runId: handle.runId });}

Ensure every agent and tool used by the workflow exists in agents/ or tools/, then call the route:

Shell
curl http://localhost:3000/api/start-content-workflow \  -H "Content-Type: application/json" \  -H "Cookie: __Host-vf_csrf=local-check" \  -H "x-csrf-token: local-check" \  -d '{"topic":"AI agents"}'

The route returns the workflow run ID:

JSON
{ "runId": "run_..." }

Inside an agent tool, start the workflow from execute:

tools/start-content-workflow.ts
import { getAgent, getAllAgentIds } from "veryfront/agent";import { defineSchema } from "veryfront/schemas";import { tool, toolRegistry } from "veryfront/tool";import { createWorkflowClient } from "veryfront/workflow";import contentPipeline from "../workflows/content-pipeline.ts"; const agentRegistry = {  get: getAgent,  list: getAllAgentIds,}; const workflows = createWorkflowClient({  executor: {    stepExecutor: {      agentRegistry,      toolRegistry,    },  },});workflows.register(contentPipeline); export default tool({  description: "Start the article workflow for a topic",  inputSchema: defineSchema((v) =>    v.object({      topic: v.string().describe("Article topic"),    })  )(),  execute: async ({ topic }) => {    const handle = await workflows.start("content-pipeline", { topic });    return { runId: handle.runId };  },});

Use handle.result() only when the caller should wait for completion. Return the runId when the workflow can continue in the background.

handle.result() polls the run and resolves with the workflow output once the run completes. It throws a timeout error if the run has not reached a terminal state after 5 minutes. Set the resultWaitTimeout executor option, in milliseconds, on createWorkflowClient to change that limit.

Schedule a workflow

Use a schedule with a workflow:<workflow-id> target when a workflow must run on a schedule. See Runs for run creation and event monitoring.

Each scheduled trigger creates a workflow run backed by the selected runtime adapter.

Steps

A step runs an agent or a tool:

workflows/steps.ts
import { step } from "veryfront/workflow"; // Run an agentexport const research = step("research", { agent: "researcher" }); // Run a toolexport const fetchData = step("fetch-data", { tool: "webScraper" }); // With custom inputexport const summarize = step("summarize", {  agent: "writer",  input: (ctx) => {    const research = ctx.research;    const text = typeof research === "object" && research !== null &&        "text" in research && typeof research.text === "string"      ? research.text      : "";    return `Summarize this: ${text}`;  },});

Step options

PropertyTypeDescription
agentstring | AgentAgent to run (by ID or instance)
toolstring | ToolTool to execute (by ID or instance)
inputstring | object | (ctx) => unknownStep input
checkpointbooleanPersist state after this step
retryRetryConfigRetry on failure
timeoutstring | numberStep timeout
skip(ctx) => booleanSkip this step conditionally

Parallel execution

Run steps concurrently:

TypeScript
import { parallel, step, workflow } from "veryfront/workflow"; export default workflow({  id: "report",  steps: [    step("gather", { agent: "researcher" }),    parallel("analyze", [      step("sentiment", { tool: "sentimentAnalyzer" }),      step("entities", { tool: "entityExtractor" }),      step("summary", { agent: "summarizer" }),    ]),    step("compile", { agent: "writer" }),  ],});

All three analysis steps run at the same time. The "compile" step waits for all of them to finish.

Parallel strategies

TypeScript
parallel("race-check", steps, { strategy: "race" }); // First to finish winsparallel("best-effort", steps, { strategy: "allSettled" }); // Continue even if some failparallel("all-required", steps, { strategy: "all" }); // Default: all must succeed

Branching

Use branch for conditional paths. An agent step stores an output envelope under its node ID: read generated text from text and schema-bound output from data (also available as object). This example assumes the classifier has an output schema containing a category string:

TypeScript
import { branch, step, workflow } from "veryfront/workflow"; export default workflow({  id: "support",  steps: [    step("classify", { agent: "classifier" }),    branch("route", {      condition: (ctx) => {        const result = ctx.classify;        const data = typeof result === "object" && result !== null && "data" in result          ? result.data          : undefined;        return typeof data === "object" && data !== null &&          "category" in data && data.category === "billing";      },      then: [step("billing", { agent: "billing-agent" })],      else: [step("technical", { agent: "tech-agent" })],    }),    step("respond", { agent: "responder" }),  ],});

Shorthand helpers use the same flat node-output context. In this example, the classify agent's output schema contains a sensitive boolean, read from its output envelope's data. The cache tool step returns the raw boolean true when the requested value is cached.

workflows/conditions.ts
import { step, unless, when } from "veryfront/workflow"; export const needsApproval = when(  "needs-approval",  (ctx) => {    const result = ctx.classify;    const data = typeof result === "object" && result !== null && "data" in result      ? result.data      : undefined;    return typeof data === "object" && data !== null &&      "sensitive" in data && data.sensitive === true;  },  [    step("review", { agent: "reviewer" }),  ],); export const fetchUnlessCached = unless("is-cached", (ctx) => ctx.cache === true, [  step("fetch", { tool: "fetcher" }),]);

Human-in-the-loop

Pause a workflow until a human approves or rejects:

TypeScript
import { step, waitForApproval, workflow } from "veryfront/workflow"; export default workflow({  id: "publish",  steps: [    step("draft", { agent: "writer" }),    waitForApproval("editor-review", {      message: "Please review the draft before publishing.",      timeout: "24h",    }),    step("publish", { tool: "publisher" }),  ],});

The workflow pauses at waitForApproval and resumes when an approver responds. If the timeout expires, the workflow fails.

Structured approval responses

Set responseSchema when the decision must carry structured data, such as a selected option or an edited value:

workflows/publish.ts
import { defineSchema } from "veryfront/schemas";import { step, waitForApproval, workflow } from "veryfront/workflow"; export default workflow({  id: "publish",  steps: [    step("draft", { agent: "writer" }),    waitForApproval("editor-review", {      message: "Review the draft and choose a channel.",      responseSchema: defineSchema((v) =>        v.object({          channel: v.string().describe("Publish channel"),        })      )(),    }),    step("publish", {      tool: "publisher",      input: (ctx) => ctx["editor-review"],    }),  ],});

Submit the decision through the workflow client. The structured answer is the fifth argument to approve() and reject(), after the optional comment:

TypeScript
const [pending] = await workflows.getPendingApprovals(runId); await workflows.approve(runId, pending.id, "[email protected]", "Ship it", {  channel: "blog",});

The submitted data is validated against the wait node's responseSchema before it is persisted. A non-conformant answer is refused with an error and the approval stays pending. Validation only covers wait nodes declared in a static step list. When a workflow's steps, or the steps of a nested loop, is a function, the node list depends on runtime state, so no schema can be resolved for the decision and the answer is accepted unvalidated. After approval, the decision lands in the workflow context under the wait node's id, so later steps read ctx["editor-review"] as { approved, approver, comment, data, decidedAt }.

The approval endpoint served by createWorkflowHandler accepts a JSON body of the shape { approved, approver, comment?, data? }. The body-level approver is compatibility input, not an identity claim. The handler replaces it with the authenticated identity returned by its server-side authorize callback, and that server-derived identity is what the workflow context persists. See Workflows: advanced for the handler routes.

Wait for events

Pause until an external event arrives, and deliver the event through the workflow client. The run resumes as soon as an event with the matching name reaches its mailbox:

TypeScript
import { tool } from "veryfront/tool";import { createWorkflowClient, dependsOn, step, waitForEvent, workflow } from "veryfront/workflow"; const fulfillment = tool<  { orderId: string },  { orderId: string; status: "fulfilled" }>({  id: "fulfillment",  description: "Fulfill a paid order",  inputSchema: {    type: "object",    properties: { orderId: { type: "string" } },    required: ["orderId"],    additionalProperties: false,  },  execute: async ({ orderId }) => ({ orderId, status: "fulfilled" }),}); const workflows = createWorkflowClient(); workflows.register(workflow({  id: "order-fulfillment",  steps: [    waitForEvent("payment-confirmed", {      eventName: "payment.completed",      timeout: "1h",    }),    dependsOn(      step("fulfill", { tool: fulfillment, input: { orderId: "ord_1" } }),      "payment-confirmed",    ),  ],})); const handle = await workflows.start("order-fulfillment", { orderId: "ord_1" });const runId = handle.runId; // Later - from a webhook handler or any process sharing the same backend:await workflows.publishEvent(runId, "payment.completed", { amount: 4200 });

Events are buffered per run, so publishing before the node parks is safe: the wait consumes the buffered event as soon as it exists. publishEvent resolves to what it did with the event:

OutcomeMeaning
"delivered"A wait matched, its node completed, and the run moved on.
"buffered"No wait matched yet. The event is held until one does.
"run-terminal"The run has already finished, so the event was discarded rather than buffered.
"delivery-failed"A wait matched but delivery failed. Both were rolled back, so the run is still parked; call retryEventDelivery(runId, eventName) to retry the same buffered envelope without publishing a duplicate.

A run's mailbox holds a bounded number of unconsumed events. Because an event is removed only when a wait takes it, none of them can be dropped safely, so a publish past the bound rejects rather than silently discarding an event some wait has not parked for yet. Reaching that bound means events are being published to a run that never consumes them.

The payload lands in the workflow context under the wait node's id, so later steps read ctx["payment-confirmed"] as { eventName, payload, receivedAt }.

Read what a run is parked on with getPendingEventWaits(runId), which returns the node id, the event name, and the deadline derived from timeout.

A timeout is enforced. When it elapses before the event arrives, the run fails with an error naming the node and the event it waited for. The deadline is measured from when the wait node started. Omit timeout to wait indefinitely. delay(id, duration) uses the same machinery and completes its node once the duration elapses. Canceling a run resolves its pending event waits, so a canceled run no longer reports itself as parked.

The built-in MemoryBackend and RedisBackend implement durable event waits. Use hasEventWaitSupport(backend) to check a custom backend before relying on waitForEvent or delay.

publishEvent is run-scoped. There is no broadcast by workflow id.

Wait for child runs

Use waitForRuns when a workflow starts or receives the IDs of independently durable runs and must continue only after every one of them reaches a terminal status:

Every listed run must be a direct child of the waiting workflow run. When the child runs are created, set their parentRunId to that workflow run's ID and nodeId to the parent node that starts them. The request requires that parent's scoped execution credential; a project API token cannot assert parent authority.

Run the following script only within the trusted parent execution. Its runtime must supply the current parent credential as PARENT_WORKFLOW_EXECUTION_TOKEN and replace the project and workflow-run placeholders. This application-defined environment variable is not a credential the SDK creates or discovers:

scripts/start-release-check.ts
import { createRunsClient } from "veryfront/runs"; const parentToken = process.env.PARENT_WORKFLOW_EXECUTION_TOKEN;if (!parentToken) throw new Error("Set the current parent execution credential");const runs = createRunsClient({ authToken: parentToken });const workflowRunId = "<WORKFLOW_RUN_ID>"; // ID of the waiting parent workflow runconst child = await runs.createTaskRun({  projectId: "<PROJECT_ID>",  parentRunId: workflowRunId,  nodeId: "start-children", // Must match the executing parent node  target: "task:release-check",});
workflows/batch-release.ts
import { dependsOn, step, waitForRuns, workflow } from "veryfront/workflow"; export default workflow({  id: "batch-release",  steps: [    step("start-children", { tool: "start-release-checks" }),    dependsOn(      waitForRuns("release-checks", {        runIds: (ctx) => ctx["start-children"].runIds,      }),      "start-children",    ),    dependsOn(step("publish", { tool: "publish-release" }), "release-checks"),  ],});

The run ID list is resolved once when the node first parks and is stored with the workflow state. The cloud runtime reports each dependency with the node ID as its correlation, and the control plane resumes the same workflow run only after all listed child runs are completed, failed, or cancelled. A child-run wait has no timeout.

Use between 1 and 1000 run IDs per node, and keep the combined child dependencies across one parallel pause at or below 1000. Built-in durable workflow backends apply child completion only while the exact persisted wait boundary is still current. A custom backend must support atomic key-merge run patches and atomic child-wait boundary updates before it can resume waitForRuns nodes.

Workflow configuration

workflows/pipeline.ts
import { defineSchema } from "veryfront/schemas";import { step, workflow } from "veryfront/workflow"; export default workflow({  id: "pipeline",  description: "Content generation pipeline",  version: "1.0.0",  inputSchema: defineSchema((v) =>    v.object({      topic: v.string().describe("Content topic"),    })  )(),  outputSchema: defineSchema((v) =>    v.object({      article: v.string().describe("Generated article body"),    })  )(),  timeout: "30m",  retry: { maxAttempts: 3, backoff: "exponential" },  steps: ({ input }) => [    step("research", {      agent: "researcher",      input: input.topic,    }),    step("write", { agent: "writer" }),  ],  output: (context) => ({ article: (context.write as { text: string }).text }),  onError: (error, ctx) => console.error("Failed:", error),  onComplete: (result) => console.log("Done:", result),});

The writer returns the article as text. The output selector takes that text from the write step and returns the { article } object declared by outputSchema.

Select the final output

By default, a completed run's output is its context without input: every step's output keyed by step id, plus env when the project injects environment values. Declare output to choose the value callers receive instead. It takes the context and returns the output synchronously, like the output mapper of a nested workflow.

Treat the context as read-only: it is also stored on the run.

workflows/expense-approval.ts
import { defineSchema } from "veryfront/schemas";import { step, workflow } from "veryfront/workflow"; export default workflow({  id: "expense-approval",  outputSchema: defineSchema((v) =>    v.object({      claimId: v.string(),      stage: v.string(),    })  )(),  steps: [    step("prepare", { tool: "prepare-claim" }),    step("finalize", { tool: "finalize-claim" }),  ],  output: (context) => context.finalize as { claimId: string; stage: string },});

outputSchema checks the selected value, or the default output when no output selector is declared, before the run completes. A selected output stores the parsed value.

A valid default output keeps its original shape and values. A mismatch fails with error.code: "OUTPUT_VALIDATION_FAILED" and { path, message } entries in error.detail.errors, so invalid output is never stored as completed.

A workflow nested with subWorkflow or map hands its parent the same selected output. The node's own output mapper, when declared, receives that value.

When a nested workflow resumes after a wait, downstream steps and its output selector receive completed child outputs without rerunning those steps. Completed wait values retain approval decision and event delivery metadata. Later child updates stay intact when the workflow resumes again or retries its output selector.

Saved child contexts follow the same persistence policy as the durable workflow context.

A started run's steps receive the parsed input: inputSchema transforms and defaults apply before the first step runs. The run keeps the input as it was submitted.

A workflow nested with subWorkflow or map also parses the input its parent passes through its own inputSchema before building or running child steps. Invalid input fails the parent run with INPUT_VALIDATION_FAILED and validation errors containing JSON Pointer paths.

A paused nested workflow reuses its parsed input when it resumes.

Nested workflow retries and resumes use the retained child-context snapshot without repeating completed steps or loop callbacks. Older nested runs with completed loops and no retained child context fail with an explicit legacy compatibility error when they are retried or resumed after a wait. Loop output mixes completion callback updates with framework metadata, and iteration history does not prove the original final publication.

The current workflow definition cannot recover that provenance, even when a completion callback erased all loop metadata keys. Object outputs without step, input, or wait identity are refused unless retained composite children corroborate the publication. Resume such a run from a checkpoint that retains the original child context.

A run that pauses on an approval or an event has no output until it completes.

A durable workflow run holds its completed step boundary when the control plane cannot confirm whether execution can continue. The runtime retries transient pause acknowledgement failures for up to 60 seconds, then answers with a resumable manual pause. A 401, 403, or 404 response holds the run immediately. Resume the run manually with a valid capability to execute the remaining steps. The runtime never treats an unknown decision as permission to continue.

See Run input and output for what a workflow run stores as input and output, and how inputSchema and outputSchema apply.

Verify it worked

createWorkflowClient() stores runs in memory, private to the client that started them. A second client, in another route file or the same file on a later request, does not see them. Verify the run from the request that started it, and add a persistent backend before reading run state from anywhere else.

Add a route that starts the workflow, waits for it, and reads the finished run back through the same client:

app/api/verify-content-workflow/route.ts
import { getAgent, getAllAgentIds } from "veryfront/agent";import { toolRegistry } from "veryfront/tool";import { createWorkflowClient } from "veryfront/workflow";import contentPipeline from "../../../workflows/content-pipeline.ts"; const workflows = createWorkflowClient({  executor: {    stepExecutor: {      agentRegistry: { get: getAgent, list: getAllAgentIds },      toolRegistry,    },  },}); workflows.register(contentPipeline); export async function POST(request: Request) {  const input = await request.json();  const handle = await workflows.start("content-pipeline", input);  await handle.settled();   const run = await workflows.getRun(handle.runId);  return Response.json({ status: run?.status, nodeStates: run?.nodeStates });}

Call it:

Shell
curl -s http://localhost:3000/api/verify-content-workflow \  -H "Content-Type: application/json" \  -H "Cookie: __Host-vf_csrf=local-check" \  -H "x-csrf-token: local-check" \  -d '{"topic":"AI agents"}' \  | jq '{status, nodes: (.nodeStates | to_entries | map({(.key): .value.status}))}'

A working run reaches status: "completed" and exposes a nodeStates map with one completed entry per step:

JSON
{  "status": "completed",  "nodes": [{ "research": "completed" }, { "write": "completed" }, { "review": "completed" }]}

If status ends in failed, inspect the matching node entry in nodeStates for the underlying error.

To read run state from a different request (a status endpoint, a dashboard, or the useWorkflow hook), give every client the same persistent backend, such as RedisBackend, instead of the default in-memory one. Run state written by one in-memory client is not readable from any other.

Remove old terminal workflow runs

For retention settings, startup precautions, and the maintenance script, see Remove old workflow runs.

Next