-
Notifications
You must be signed in to change notification settings - Fork 336
feat: Add Cloudflare Workflows integration for Agents #799
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
🦋 Changeset detectedLatest commit: a099119 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
commit: |
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.
0b5e6c8 to
ed64efa
Compare
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.
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>
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.
|
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.
This comment was marked as resolved.
This comment was marked as resolved.
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>
deathbyknowledge
left a comment
There was a problem hiding this 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.
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.
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.
This comment was marked as resolved.
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?)` |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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"
There was a problem hiding this comment.
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?
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.
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.
|
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 |
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:
AgentWorkflow Base Class
Extend
AgentWorkflowinstead ofWorkflowEntrypointto get typed access to the originating Agent:Agent Methods
runWorkflow(workflowName, params, options?)- Start workflow with optional metadata for queryingsendWorkflowEvent(workflowName, workflowId, event)- Send events to waiting workflowsgetWorkflow(workflowId)- Get tracked workflow by IDgetWorkflows(criteria?)- Query by status, workflowName, or metadatadeleteWorkflow(workflowId)- Delete a workflow tracking recorddeleteWorkflows(criteria?)- Delete workflows by criteria (status, workflowName, metadata, createdBefore)approveWorkflow(workflowId, data?)- Approve a waiting workflowrejectWorkflow(workflowId, data?)- Reject a waiting workflowAgentWorkflow Methods
On
this(non-durable, lightweight):reportProgress(progress)- Report typed progress object to AgentbroadcastToClients(message)- Broadcast to WebSocket clientswaitForApproval(step, opts?)- Wait for approval (throws on rejection)On
step(durable, idempotent):step.reportComplete(result?)- Report successful completionstep.reportError(error)- Report an errorstep.sendEvent(event)- Send custom event to Agentstep.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):
Workflow Tracking
Workflows are automatically tracked in
cf_agents_workflowsSQLite table:metadatafield for queryable key-value dataSee
docs/workflows.mdfor full documentation.PR Reviewer Notes
How to Review This PR
Recommended reading order:
docs/workflows.md- Start here for the complete picture. Covers:this.*andstep.*methods)packages/agents/src/workflow-types.ts- All type definitions:AgentWorkflowEvent<Params>- Type alias forWorkflowEvent<Params>(for consistency)AgentWorkflowStep- ExtendedWorkflowStepwith durable Agent methodsAgentWorkflowParams/AgentWorkflowInternalParams- Combined user + internal paramsWorkflowCallbacktypes (progress, complete, error, event)DefaultProgress- Default typed progress objectWorkflowStatus- Derived from Cloudflare'sInstanceStatusWorkflowInfo- Parsed workflow tracking recordWorkflowQueryCriteria- For querying workflowsWaitForApprovalOptions/ApprovalEventPayload- Human-in-the-loop typesWorkflowRejectedError- Thrown when workflow is rejectedpackages/agents/src/workflow.ts- TheAgentWorkflowbase class:this.agentbeforerun()executes_wrapStep()- WrapsWorkflowStepwith durable Agent methodsthis(lightweight, may repeat on retry):reportProgress()- For frequent progress updatesbroadcastToClients()- Fire-and-forget WebSocket broadcastwaitForApproval()- Human-in-the-loop (throwsWorkflowRejectedErroron rejection)fetchAgent()- HTTP request to Agentstep(idempotent viastep.do(), won't repeat on retry):step.reportComplete()- Report completionstep.reportError()- Report errorsstep.sendEvent()- Send custom eventsstep.updateAgentState()- Replace Agent statestep.mergeAgentState()- Merge into Agent statepackages/agents/src/index.ts- Agent class additions (search forcf_agents_workflows):workflow_nameindex)runWorkflow()- Starts workflow with optionalagentBindingoverridegetWorkflow()/getWorkflows()- Query tracked workflows by status, name, metadatadeleteWorkflow()/deleteWorkflows()- Cleanup tracking recordssendWorkflowEvent()- Send events to waiting workflowsapproveWorkflow()/rejectWorkflow()- Human-in-the-loop convenience methodsmigrateWorkflowBinding()- Migrate records after renaming bindingsonWorkflowCallback()andonWorkflow*lifecycle methods_workflow_handleCallback,_workflow_broadcast,_workflow_updateState(secure workflow-to-agent communication)_checkOrphanedWorkflows)Tests (in order):
packages/agents/src/tests/test-workflow.ts- Example test workflows using newstep.*APIpackages/agents/src/tests/workflow.test.ts- Unit tests for tracking, callbacks, cleanup, and migrationpackages/agents/src/tests/workflow-integration.test.ts- Integration tests (some skipped due to introspection limitations with durable steps)examples/workflows/- Demo Vite app showing:this.*vsstep.*method split