Skip to content

Conversation

@threepointone
Copy link
Contributor

@threepointone threepointone commented Jan 27, 2026

image

Adds seamless integration between Cloudflare Agents and Cloudflare Workflows for durable, multi-step background processing.

Why use Workflows with Agents?

Agents excel at real-time communication and state management, while Workflows excel at durable execution. Together:

  • Agents handle WebSocket connections and quick operations
  • Workflows handle long-running tasks, retries, and human-in-the-loop flows

AgentWorkflow Base Class

Extend AgentWorkflow instead of WorkflowEntrypoint to get typed access to the originating Agent:

export class ProcessingWorkflow extends AgentWorkflow<MyAgent, TaskParams> {
  async run(event: AgentWorkflowEvent<TaskParams>, step: AgentWorkflowStep) {
    const params = event.payload;

    // Call Agent methods via RPC
    await this.agent.updateStatus(params.taskId, "processing");

    // Non-durable: progress reporting (lightweight, for frequent updates)
    await this.reportProgress({
      step: "process",
      percent: 0.5,
      message: "Halfway done"
    });
    this.broadcastToClients({ type: "update", taskId: params.taskId });

    // Durable via step: idempotent, won't repeat on retry
    await step.mergeAgentState({ taskProgress: 0.5 });
    await step.reportComplete(result);

    return result;
  }
}

Agent Methods

  • runWorkflow(workflowName, params, options?) - Start workflow with optional metadata for querying
  • sendWorkflowEvent(workflowName, workflowId, event) - Send events to waiting workflows
  • getWorkflow(workflowId) - Get tracked workflow by ID
  • getWorkflows(criteria?) - Query by status, workflowName, or metadata
  • deleteWorkflow(workflowId) - Delete a workflow tracking record
  • deleteWorkflows(criteria?) - Delete workflows by criteria (status, workflowName, metadata, createdBefore)
  • approveWorkflow(workflowId, data?) - Approve a waiting workflow
  • rejectWorkflow(workflowId, data?) - Reject a waiting workflow

AgentWorkflow Methods

On this (non-durable, lightweight):

  • reportProgress(progress) - Report typed progress object to Agent
  • broadcastToClients(message) - Broadcast to WebSocket clients
  • waitForApproval(step, opts?) - Wait for approval (throws on rejection)

On step (durable, idempotent):

  • step.reportComplete(result?) - Report successful completion
  • step.reportError(error) - Report an error
  • step.sendEvent(event) - Send custom event to Agent
  • step.updateAgentState(state) - Replace Agent state (broadcasts to clients)
  • step.mergeAgentState(partial) - Merge into Agent state (broadcasts to clients)

Lifecycle Callbacks

Override these methods to handle workflow events (workflowName is first for easy differentiation):

async onWorkflowProgress(workflowName, workflowId, progress) {} // progress is typed object
async onWorkflowComplete(workflowName, workflowId, result?) {}
async onWorkflowError(workflowName, workflowId, error) {}
async onWorkflowEvent(workflowName, workflowId, event) {}

Workflow Tracking

Workflows are automatically tracked in cf_agents_workflows SQLite table:

  • Status, timestamps, errors
  • Optional metadata field for queryable key-value data
  • Params/output NOT stored by default (could be large)

See docs/workflows.md for full documentation.

PR Reviewer Notes

How to Review This PR

Recommended reading order:

  1. docs/workflows.md - Start here for the complete picture. Covers:

    • Why integrate Workflows with Agents
    • Quick start guide
    • Full API reference (note the split between this.* and step.* methods)
    • Common patterns (background processing, approval flows, retry logic, state sync)
    • Workflow cleanup strategies and binding migration
  2. packages/agents/src/workflow-types.ts - All type definitions:

    • AgentWorkflowEvent<Params> - Type alias for WorkflowEvent<Params> (for consistency)
    • AgentWorkflowStep - Extended WorkflowStep with durable Agent methods
    • AgentWorkflowParams / AgentWorkflowInternalParams - Combined user + internal params
    • WorkflowCallback types (progress, complete, error, event)
    • DefaultProgress - Default typed progress object
    • WorkflowStatus - Derived from Cloudflare's InstanceStatus
    • WorkflowInfo - Parsed workflow tracking record
    • WorkflowQueryCriteria - For querying workflows
    • WaitForApprovalOptions / ApprovalEventPayload - Human-in-the-loop types
    • WorkflowRejectedError - Thrown when workflow is rejected
  3. packages/agents/src/workflow.ts - The AgentWorkflow base class:

    • Constructor hook that initializes this.agent before run() executes
    • _wrapStep() - Wraps WorkflowStep with durable Agent methods
    • Non-durable methods on this (lightweight, may repeat on retry):
      • reportProgress() - For frequent progress updates
      • broadcastToClients() - Fire-and-forget WebSocket broadcast
      • waitForApproval() - Human-in-the-loop (throws WorkflowRejectedError on rejection)
      • fetchAgent() - HTTP request to Agent
    • Durable methods on step (idempotent via step.do(), won't repeat on retry):
      • step.reportComplete() - Report completion
      • step.reportError() - Report errors
      • step.sendEvent() - Send custom events
      • step.updateAgentState() - Replace Agent state
      • step.mergeAgentState() - Merge into Agent state
  4. packages/agents/src/index.ts - Agent class additions (search for cf_agents_workflows):

    • SQLite table schema and initialization (with workflow_name index)
    • runWorkflow() - Starts workflow with optional agentBinding override
    • getWorkflow() / getWorkflows() - Query tracked workflows by status, name, metadata
    • deleteWorkflow() / deleteWorkflows() - Cleanup tracking records
    • sendWorkflowEvent() - Send events to waiting workflows
    • approveWorkflow() / rejectWorkflow() - Human-in-the-loop convenience methods
    • migrateWorkflowBinding() - Migrate records after renaming bindings
    • onWorkflowCallback() and onWorkflow* lifecycle methods
    • Internal RPC methods: _workflow_handleCallback, _workflow_broadcast, _workflow_updateState (secure workflow-to-agent communication)
    • Orphan detection on startup (_checkOrphanedWorkflows)
  5. Tests (in order):

    • packages/agents/src/tests/test-workflow.ts - Example test workflows using new step.* API
    • packages/agents/src/tests/workflow.test.ts - Unit tests for tracking, callbacks, cleanup, and migration
    • packages/agents/src/tests/workflow-integration.test.ts - Integration tests (some skipped due to introspection limitations with durable steps)
  6. examples/workflows/ - Demo Vite app showing:

    • Multi-step workflow with progress tracking
    • Human-in-the-loop approval gate
    • Real-time state sync to React UI
    • Demonstrates the this.* vs step.* method split

@changeset-bot
Copy link

changeset-bot bot commented Jan 27, 2026

🦋 Changeset detected

Latest commit: a099119

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
agents Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 27, 2026

Open in StackBlitz

npm i https://pkg.pr.new/cloudflare/agents@799

commit: a099119

Introduces Agent-Workflow integration for durable, multi-step background processing. Adds workflow tracking table, lifecycle methods, and API for starting, tracking, and communicating with workflows. Includes new documentation, workflow base class, and supporting types for seamless bidirectional communication between Agents and Workflows.
Introduces the TestWorkflowAgent class for workflow tracking and callback testing in worker.ts. Adds comprehensive tests for workflow operations, callbacks, and broadcast handling in workflow.test.ts. Updates wrangler.jsonc to register TestWorkflowAgent for testing.
Replaces workflow params/output storage with a metadata field for more flexible querying and tracking. All workflow callback methods and types now include the workflow binding name (workflowName) for better context. Updates documentation, tests, and workflow interfaces to reflect these changes, and adds new integration tests and workflow test classes for comprehensive coverage.
Refactors workflow progress reporting to use typed progress objects instead of numeric values, updates all relevant docs and tests, and introduces new Agent methods for workflow approval and rejection. Adds state synchronization helpers (updateAgentState, mergeAgentState) for workflows to update Agent state and broadcast to clients. Updates workflow types to support custom progress types, approval event payloads, and introduces WorkflowRejectedError for rejected approvals. Improves documentation and test coverage for these new features.
Introduces a new example in examples/workflows demonstrating multi-step workflow integration with Cloudflare Agents, including real-time progress updates, human-in-the-loop approval, and state synchronization. Also exports WorkflowRejectedError and related types from the agents package for workflow integration.
Deleted the PR reviewer note and review instructions from the changeset file for clarity. Also removed the unused Env interface from the example server code to clean up environment bindings.
Updated the metadata query in Agent to use parameterized path construction for json_extract, preventing SQL injection. Added tests to verify querying workflows by single and multiple metadata fields.
Introduces deleteWorkflow and deleteWorkflows methods to the Agent class for removing workflow tracking records individually or by criteria. Updates documentation with usage examples and best practices for workflow cleanup. Adds test agent helpers and unit tests to verify deletion functionality.
Replaces HTTP endpoint-based workflow communication between Agent and AgentWorkflow with direct internal RPC method calls. Updates tests and workflow methods to use the new RPC interface, removing now-unnecessary HTTP request handling and simplifying the codebase.
Updated the JSDoc for the deleteWorkflows method to clarify that the returned number represents the count of records matching the criteria, which is the expected number of deleted records.
Adds error handling for duplicate workflow tracking attempts in the Agent class, throwing a descriptive error when a workflow with the same ID is already tracked. Updates tests to cover this scenario and adds a helper for direct workflow tracking insertion in tests.
Added documentation for `deleteWorkflow` and `deleteWorkflows` methods to the changeset file, describing their usage and available criteria.
agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 27, 2026
Sync comprehensive Workflows integration documentation from cloudflare/agents PR 799.

This updates the existing run-workflows.mdx file to include:
- AgentWorkflow base class for typed Agent access
- Automatic workflow tracking in SQLite database
- Bidirectional communication between Agent and Workflow
- Lifecycle callbacks (progress, complete, error, events)
- Human-in-the-loop approval workflows with waitForApproval()
- State synchronization methods
- Query and cleanup methods for workflow tracking
- Common patterns and best practices

The documentation follows Cloudflare style guidelines including:
- Using TypeScriptExample and WranglerConfig components
- Proper cross-linking to related documentation
- Complete API reference with type information
- Practical examples for common use cases

Source: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 27, 2026
Comprehensive update to Workflows integration documentation based on changes
from cloudflare/agents PR #799: feat: Add Cloudflare Workflows integration for Agents.

Changes:
- Replace basic workflow triggering guide with comprehensive integration documentation
- Add AgentWorkflow base class reference with typed Agent access
- Document lifecycle callbacks (onWorkflowProgress, onWorkflowComplete, onWorkflowError, onWorkflowEvent)
- Add workflow tracking system documentation (cf_agents_workflows table, metadata querying)
- Document Agent workflow methods (runWorkflow, sendWorkflowEvent, getWorkflow, getWorkflows, deleteWorkflow, deleteWorkflows)
- Add approval methods (approveWorkflow, rejectWorkflow, waitForApproval)
- Include patterns for background processing, human-in-the-loop approvals, retry logic, and state synchronization
- Add bidirectional communication examples (Workflow to Agent and Agent to Workflow)
- Document best practices including workflow cleanup strategies

This update provides developers with a complete reference for integrating
Cloudflare Workflows with Agents for durable, multi-step background processing.

Source PR: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Adds a new AgentWorkflowEvent type alias to simplify workflow event typing, replacing verbose WorkflowEvent<AgentWorkflowParams<T>> usage throughout the codebase, documentation, and examples. Updates all relevant method signatures and documentation to use the new type for improved readability and developer experience.
@threepointone
Copy link
Contributor Author

I went through all the claude code review comments and addressed the legit ones.

Updated the API, documentation, and code examples to use 'createdBefore' instead of 'olderThan' as the criteria for deleting workflows by creation date. This change improves clarity and consistency across the codebase and documentation.
@claude

This comment was marked as resolved.

agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 27, 2026
Significantly expands the Workflows integration documentation based on PR 799
in the cloudflare/agents repository. This update transforms the basic workflow
triggering guide into comprehensive documentation covering:

- New AgentWorkflow base class for typed Agent access
- Complete API reference for workflow methods and lifecycle callbacks
- Automatic workflow tracking in Agent SQLite database
- Bidirectional communication patterns (Agent ↔ Workflow)
- Human-in-the-loop approval flows with convenience methods
- Progress reporting with custom progress types
- State synchronization between Workflows and Agents
- Common patterns: background processing, retries, approvals
- Best practices and limitations

Synced from: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Copy link
Contributor

@deathbyknowledge deathbyknowledge left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a few non blocking questions. This is lit

Updated Agent methods (runWorkflow, sendWorkflowEvent, getWorkflowStatus) to accept workflow binding names as strings instead of Workflow objects. This improves ergonomics, enables better type inference, and simplifies usage in documentation, tests, and examples. Updated all relevant documentation and code references accordingly. Removed the now-unnecessary _findWorkflowBindingName method.
agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 28, 2026
Comprehensive update to the Workflows integration documentation to reflect
the new AgentWorkflow base class and enhanced integration features added in
cloudflare/agents PR #799.

Key additions:
- AgentWorkflow base class with typed Agent access
- Automatic workflow tracking in SQLite
- Lifecycle callbacks (onWorkflowProgress, onWorkflowComplete, etc.)
- Approval workflow methods (approveWorkflow, rejectWorkflow)
- State synchronization between workflows and agents
- Query and cleanup methods for workflow management
- Common patterns (background processing, human-in-the-loop, retries)

Synced from: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Introduces a method to migrate workflow tracking records to a new binding name after renaming in wrangler.toml, with warnings for orphaned workflows referencing unknown bindings. Updates documentation, adds helper and tests for migration, and improves agent startup checks for binding consistency.
Moves the call to reportProgress before waitForApproval in the ApprovalWorkflow example and updates the message. Removes automatic progress reporting from waitForApproval, clarifying that progress should be reported explicitly before calling the method.
Introduces an optional agentBinding parameter to allow explicit specification of the agent binding name, improving reliability when class name auto-detection fails. Updates documentation, type definitions, and error messages to reflect this new option.
agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 28, 2026
Syncs documentation from cloudflare/agents PR #799 which adds seamless
integration between Cloudflare Agents and Cloudflare Workflows for
durable, multi-step background processing.

This update replaces the basic workflow triggering documentation with
comprehensive coverage of the new AgentWorkflow base class, including:

- AgentWorkflow class with typed Agent access
- Workflow tracking in Agent SQLite database
- Bidirectional communication between Agents and Workflows
- Lifecycle callbacks (onWorkflowProgress, onWorkflowComplete, etc.)
- Approval methods for human-in-the-loop flows
- Common patterns (background processing, approvals, retries, state sync)
- Custom progress types
- Best practices for cleanup and migration

Related PR: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Corrected type imports in the example to use AgentWorkflowEvent and updated the method documentation to refer to 'workflowName' instead of 'workflow'.
Updated WorkflowStatus to derive from InstanceStatus and replaced custom WorkflowTimeout type with WorkflowSleepDuration from Cloudflare Workers. This improves type safety and alignment with Cloudflare's API.
@claude

This comment was marked as resolved.

The orphaned workflow check now reports the number of active and completed workflows referencing unknown bindings, providing a clearer breakdown in the warning message. This helps users better understand the state of orphaned workflows and aids in migration decisions.
// true if deleted, false if not found
```

#### `deleteWorkflows(criteria?)`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this to delete the entire workflow, i.e. https://developers.cloudflare.com/api/resources/workflows/methods/delete/ or specific instances? looks like instances from "errored", "terminated" filter, should be clear

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is just to wipe out an instance, but we don't have anything to delete the top level Workflow (and never will), so it shouldn't be as confusing

}
```

### Durable Task Queue with Retries
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know that it makes sense to call this a "task queue"

Copy link
Contributor Author

@threepointone threepointone Jan 28, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got any reccos for what to call it?

threepointone and others added 5 commits January 28, 2026 16:05
Co-authored-by: mia303 <mmalden@cloudflare.com>
Co-authored-by: mia303 <mmalden@cloudflare.com>
Co-authored-by: mia303 <mmalden@cloudflare.com>
Introduces AgentWorkflowStep interface with durable, idempotent methods (reportComplete, reportError, sendEvent, updateAgentState, mergeAgentState) that are only available on the step parameter. Updates documentation, examples, and tests to use event.payload directly and to call durable methods via step. Non-durable methods (reportProgress, broadcastToClients) remain on the workflow instance. This change clarifies the distinction between durable and non-durable workflow actions and improves workflow reliability.
agents-git-bot bot pushed a commit to cloudflare/cloudflare-docs that referenced this pull request Jan 28, 2026
Sync documentation from cloudflare/agents PR #799

- Add comprehensive guide for Cloudflare Workflows integration with Agents
- Document new AgentWorkflow class with typed Agent access
- Add API reference for workflow tracking, progress reporting, and lifecycle callbacks
- Include patterns for background processing, human-in-the-loop, and state sync
- Update run-workflows API reference with AgentWorkflow integration

Related PR: cloudflare/agents#799

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Eliminates the fetchAgent method from AgentWorkflow and updates documentation to reflect its removal. Durable Agent communication methods are now added directly to the step object to preserve instanceof checks and object identity.
Introduces the resetAgentState method to AgentWorkflowStep, allowing workflows to reset agent state to its initial value and broadcast the change. Updates documentation and internal workflow handling to support the new method.
@threepointone
Copy link
Contributor Author

I'm going to land this, but will carry on the conversation with @mia303 since they're not blocking any functionality.

excited to get this into people's hands, lfg

@threepointone threepointone merged commit d1a0c2b into main Jan 28, 2026
7 checks passed
@threepointone threepointone deleted the workflows branch January 28, 2026 18:53
@github-actions github-actions bot mentioned this pull request Jan 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants