Agent Workflow Integration: Durable Steps, Lifecycle, and Human Approval
How Cloudflare Agents SDK and Workflows combine for long-running tasks, step checkpoints, WebSocket progress, and human-in-the-loop approval.
This page summarises Cloudflare documentation on pairing the Agents SDK with Cloudflare Workflows: when to use each, how AgentWorkflow connects them, and how to build durable LLM agent loops and approval flows without losing real-time client updates.
Agents vs Workflows: when to combine them
Section titled “Agents vs Workflows: when to combine them”Agents fit long-lived identity, WebSockets, and quick interactions; Workflows fit linear pipelines with automatic retries, recovery, and pauses for external events. Cloudflare positions them as complements, not substitutes.
Agents excel at real-time communication and state management. Workflows excel at durable execution. Together, they enable powerful patterns where Agents handle WebSocket connections while Workflows handle long-running tasks, retries, and human-in-the-loop flows.
— Cloudflare, Agents SDK v0.3.7: Workflows integration
From Run Workflows and Using Agents with Workflows:
| Capability | Agents | Workflows |
|---|---|---|
| Execution model | Long-lived identity that wakes on events | Run to completion |
| Real-time communication | WebSockets, HTTP streaming | Not supported |
| State persistence | Built-in SQL database | Step-level persistence |
| Failure handling | Application-defined | Automatic retries and recovery |
| External events | Direct handling | Pause and wait for events |
Use Agents alone for chat, messaging, collaborative features, and work under about 30 seconds. Use Agent + Workflow for data pipelines, report generation, multi-step retries, guaranteed delivery, and human approval. Use Workflows alone for background or scheduled jobs that do not need a live user session.
For agent-centric rhythms (reminders, polling, housekeeping), long-running agents notes that schedules and agent-internal primitives are often simpler; delegate discrete pipelines (deploy, CI, heavy processing) to a Workflow.
What the Agent class adds on its own
Section titled “What the Agent class adds on its own”Before Workflows enter the picture, the Agent class is the stateful layer on top of Server:
Agent extends Server and provides opinionated primitives for stateful, schedulable, and observable agents that can communicate via RPC, WebSockets, and (even!) email.
— Cloudflare, Agent class internals
That statefulness matters for LLM use: unlike a stateless Worker that rebuilds context per request, an Agent can keep state, stay on WebSocket, and call models on a schedule (Calling LLMs).
AgentWorkflow: durable work with bidirectional Agent access
Section titled “AgentWorkflow: durable work with bidirectional Agent access”AgentWorkflow (from agents/workflows) extends Cloudflare Workflows with typed access to the originating Agent. Define a workflow class, implement run(event, step), and use this.agent for RPC back into Agent methods.
The Run Workflows guide shows the split between durable step APIs and non-durable instance methods:
| Kind | Examples | On workflow retry |
|---|---|---|
| Non-durable (may repeat) | this.reportProgress(), this.broadcastToClients(), direct this.agent RPC |
Can run again |
| Durable (idempotent) | step.do(), step.reportComplete(), step.mergeAgentState(), step.updateAgentState() |
Skipped after success |
These methods are idempotent and will not repeat on retry. Use for state changes that must persist.
— Cloudflare, Run Workflows (step methods)
AgentWorkflow type parameters (Run Workflows): AgentType (RPC typing), Params (workflow input), optional ProgressType, and Env. Properties include agent (typed stub), instanceId, workflowName, and env.
runWorkflow() and lifecycle callbacks: start and observe background work
Section titled “runWorkflow() and lifecycle callbacks: start and observe background work”From the Agent, runWorkflow(workflowName, params, options?) starts an instance and records it in the Agent’s internal database. Override lifecycle hooks to push updates to clients:
| Callback | Purpose |
|---|---|
onWorkflowProgress |
Non-durable progress from reportProgress() |
onWorkflowComplete |
Final result |
onWorkflowError |
Failure |
onWorkflowEvent |
Custom events from step.sendEvent() |
Typical pattern from Build a Durable AI Agent: the Agent receives HTTP or WebSocket, calls runWorkflow(), stores instanceId in state, and broadcast() progress JSON to connected clients inside onWorkflowProgress.
Management APIs on the Agent (changelog integration post) include getWorkflow() / getWorkflows() (cursor pagination), approveWorkflow() / rejectWorkflow(), and pauseWorkflow(), resumeWorkflow(), terminateWorkflow().
Agent → Workflow control
Section titled “Agent → Workflow control”While a workflow waits, the Agent can sendWorkflowEvent(), approve or reject, or pause/resume/terminate. See Run Workflows — Agent to Workflow.
Durable LLM and tool loops: why each LLM call is its own step.do()
Section titled “Durable LLM and tool loops: why each LLM call is its own step.do()”Build a Durable AI Agent walks through a research agent: each LLM turn and each tool invocation is wrapped in step.do(name, options?, callback) so the engine checkpoints after every unit of work.
Each step.do() creates a checkpoint. If your Workflow crashes or the Worker restarts: After LLM step: The response is persisted. On resume, it skips the LLM call and moves to tool execution. After tool step: The result is persisted. If a later tool fails, earlier tools do not re-run.
— Cloudflare, Build a Durable AI Agent
That split matters because LLM calls are costly, external APIs may rate-limit, and some tools must not run twice. Use this.reportProgress() and this.broadcastToClients() for live UI updates (non-durable); persist outcomes only inside step.do() or durable step.* state methods.
Long-running agent challenges mapped in the same guide:
| Challenge | Workflow mechanism |
|---|---|
| Long agent loops | Durable execution survives interruption |
| Unreliable LLM/API calls | Per-step retry (e.g. retries: { limit, delay, backoff }) |
| Human approval | waitForApproval() / waitForEvent() |
| Polling without burning resources | step.sleep() |
Human-in-the-loop: waitForApproval() and Agent UI
Section titled “Human-in-the-loop: waitForApproval() and Agent UI”Approval workflows validate work in step.do(), report pending status with reportProgress(), then pause with waitForApproval(step, { timeout }). Rejection surfaces as WorkflowRejectedError.
From Human-in-the-loop patterns:
- Expose
approveWorkflow()/rejectWorkflow()on the Agent (often behind@callable()RPC for your UI). - Track pending items in Agent state (e.g.
pendingApprovals) insideonWorkflowProgresswhenstep === "approval"andstatus === "pending". - Optionally
schedule()reminders and escalations while status iswaiting. - Optionally record decisions in
this.sqlfor an immutable audit table.
The React useAgent hook can render approval cards that call agent.stub.approve() / reject() (Human-in-the-loop patterns).
State sync from workflow steps to connected clients
Section titled “State sync from workflow steps to connected clients”Workflows can durably update Agent state so WebSocket clients stay in sync without polling (Store and sync state, Run Workflows — State synchronization):
step.updateAgentState(state)— replace entire state (broadcasts).step.mergeAgentState(partial)— merge fields (broadcasts).step.resetAgentState()— revert toinitialState.
These survive workflow retries; prefer them over mutating state only inside non-durable RPC if the UI must reflect checkpointed progress.
Sub-agents, routing, and workflow tracking scope
Section titled “Sub-agents, routing, and workflow tracking scope”Sub-agents and Run Workflows add constraints:
- A child may call
runWorkflow(); tracking lives in the child’s SQLite, not the parent’s. SubAgentStub<T>exposes only user-defined methods — wrapgetWorkflow(),approveWorkflow(), etc. on the child if the parent must control child workflows.- For sub-agent origins,
AgentWorkflow.agentis RPC-only; userouteSubAgentRequest()or the nested/agents/{parent}/{name}/sub/{child}/{name}URL for HTTP/WebSocket, notthis.agent.fetch(). - When passing
options.agentBinding, use the root Agent binding name. - Start workflows from name-addressed Agents (
getAgentByName), not raw Durable Object IDs, or callbacks may hit the wrong instance. - Preserve class names in bundling (
esbuildkeepNames: true) so routing byconstructor.nameworks.
Rename workflow bindings with migrateWorkflowBinding(oldName, newName) in onStart() when needed.
Retention: workflow rows and long-running housekeeping
Section titled “Retention: workflow rows and long-running housekeeping”The internal cf_agents_workflows table can grow without bound. Run Workflows — Cleanup strategy suggests deleting on completion, scheduled deleteWorkflows({ status, createdBefore }), or keeping all rows for compliance.
Long-running agents shows combining schedule() for daily housekeeping (archive tasks, delete old workflow records) with Workflow delegation for heavy jobs.
Common mistakes
Section titled “Common mistakes”- Putting expensive LLM or API calls outside
step.do(), so a retry repeats work. - Using non-durable broadcasts as the sole source of truth for completion.
- Starting workflows from ID-based Agent addressing so lifecycle callbacks miss the right instance.
- Expecting the parent Agent to list workflows a sub-agent started without child wrapper methods.
- Calling
this.agent.fetch()from a sub-agent-originated workflow instead of documented sub-agent routing. - Never pruning workflow history when instance volume is high (unless you need full audit retention).
How to check this on your site
Section titled “How to check this on your site”-
Implement a minimal
AgentWorkflowwith onestep.do()andreportProgress(), then start it from your Agent withrunWorkflow()as in Run Workflows. -
Confirm lifecycle wiring: trigger progress and verify
onWorkflowProgressreceives it and your WebSocket clients get updates (pattern in Build a Durable AI Agent). -
Simulate failure after a successful
step.do()(e.g. throw in a later step) and confirm the workflow resumes without re-running the completed step (Build a Durable AI Agent). -
For approval flows, pause with
waitForApproval(), callapproveWorkflow()orrejectWorkflow()from the Agent, and confirm resume orWorkflowRejectedError(Human-in-the-loop patterns). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the behaviour you see in your project, email yimasynthetic@gmail.com with the page URL and the exact statement you believe is wrong or unclear.