Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

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 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.

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().

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) inside onWorkflowProgress when step === "approval" and status === "pending".
  • Optionally schedule() reminders and escalations while status is waiting.
  • Optionally record decisions in this.sql for 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 to initialState.

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 — wrap getWorkflow(), approveWorkflow(), etc. on the child if the parent must control child workflows.
  • For sub-agent origins, AgentWorkflow.agent is RPC-only; use routeSubAgentRequest() or the nested /agents/{parent}/{name}/sub/{child}/{name} URL for HTTP/WebSocket, not this.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 (esbuild keepNames: true) so routing by constructor.name works.

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.

  • 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).
  1. Implement a minimal AgentWorkflow with one step.do() and reportProgress(), then start it from your Agent with runWorkflow() as in Run Workflows.

  2. Confirm lifecycle wiring: trigger progress and verify onWorkflowProgress receives it and your WebSocket clients get updates (pattern in Build a Durable AI Agent).

  3. 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).

  4. For approval flows, pause with waitForApproval(), call approveWorkflow() or rejectWorkflow() from the Agent, and confirm resume or WorkflowRejectedError (Human-in-the-loop patterns).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

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.