Cloudflare runtime
Run Vercel Workflow code on Cloudflare Workers with one Durable Object per run.
The @yolk-sdk/vercel-workflows/cloudflare* subpaths run code written for Vercel Workflow
('use workflow', 'use step', workflow, workflow/api) on Cloudflare Workers without a Vercel
backend. runVercelAgentWorkflow and your own workflow and step functions run unchanged.
How a run executes
Each run lives in its own WorkflowRun Durable Object, named by its run id.
- The workflow body runs in memory in the run's object. Step outcomes, hook payloads, and fired sleeps are journaled in the object's SQLite storage, so after an eviction the body replays to where it was without re-running finished steps.
- Values cross durable boundaries as devalue text, as on Vercel:
Date,Map,Set, typed arrays,undefined, and errors with their name, message, stack, cause,fatal, andretryAfter. - Steps are at-least-once. A step cut off by an eviction runs again when the object's step guard
alarm replays the run. A step's
maxRetries(default 3) bounds retries with exponential backoff;RetryableErrorwaits for itsretryAfter;FatalErroris never retried; an exhausted step throws aFatalErrorwhosecauseis the last error. - Hook tokens follow Vercel's rules. One live hook holds a token at a time, and a hook-index object
(
hook:<token>) routesresumeHookto the run whose live hook holds it. A run decides its new hooks once its body is idle, after the disposals it made since: a hook whose token another live hook (of any run, its own included) still holds is refused, and awaiting it rejects withHookConflictError(token,conflictingRunId) while the holder keeps the token. A token is free again once its hook is disposed or its run ends.resumeHooksucceeds for every payload sent to a live hook (await hookreads the first) and rejects withHookNotFoundErrorwhen no live hook holds the token, including a new hook the index has not granted yet: retry while the pause is pending. - Unlike Vercel, which decides at the run's next durable suspension, the runtime decides at the
next macrotask, so dispose the previous hook before any
awaitthat yields to the event loop. A hook is read once (awaiting it again gives the first payload), andgetConflict()is not provided. sleep(duration)stores its wake time and arms the object's alarm.getWritable()in a step appends to the run's stream;getRun(runId).getReadable({ startIndex })follows it live andgetTailIndex()returns the last chunk's index.run.cancel()stops the run where it waits;returnValuerejects withWorkflowRunCancelledError. A step still running gets its signal aborted (reason aWorkflowRunCancelledError): read it withgetStepSignal()from@yolk-sdk/vercel-workflows/cloudflare/workflow(not part ofworkflow's types) and pass it to the step's fetch or model call so it ends with the run. Its outcome is dropped either way, a step waiting to retry stops at once, and the run's execution ends once its steps are done.
The drop-in modules cover createHook, sleep, getWritable, getStepMetadata,
getWorkflowMetadata, FatalError, and RetryableError (workflow, plus the Cloudflare-only
getStepSignal), and start, getRun, and resumeHook (workflow/api, plus the
Cloudflare-only startWithRunId, prepareRun, createRunId and isRunId). defineHook,
webhooks, and fetch are not provided; start ignores attributes.
Prepare a run ahead of its start
Every run gets a new WorkflowRun object, so a start pays for creating the object and evaluating
the workflow's module in its fresh isolate (about a second for a large runtime on Cloudflare).
When you know a run is coming (someone is typing a message), warm its object first. These are
Cloudflare-only exports of @yolk-sdk/vercel-workflows/cloudflare/api (import them from there:
workflow/api's types do not declare them):
import { createRunId, prepareRun, startWithRunId } from '@yolk-sdk/vercel-workflows/cloudflare/api'
// While the person types: pick the next run's id, keep it, and warm its object.
const runId = createRunId()
await prepareRun(sessionWorkflow, runId)
// On send: start under that id. Claim the id once (for example a compare-and-set in your
// database) so only one caller starts under it.
const started = await startWithRunId(sessionWorkflow, [input], { runId })
if (started.status === 'taken') {
// Another run lives under this id: start yours under a new id.
}prepareRun(workflow, runId)loads the workflow's module and the modules registered withregisterRunPreloads({ name: () => import('./runtime') })(from@yolk-sdk/vercel-workflows/cloudflare, called at the Worker entry's module scope; list what a run loads anyway, such as a runtime its steps import lazily, and keep them plainimport()s: everyprepareRuncalls them again) in the run's object. It stores nothing, so an object prepared and never started costs only its preparation and is evicted after a few idle minutes. Calling it again on a warm object is cheap and keeps it resident.startWithRunId(workflow, args, { runId })starts the run only when no run lives under the id and answers{ status: 'created', run }. Otherwise it changes nothing:alreadyStarted(withrun) when that run has the same workflow and arguments, most likely your own earlier call whose answer was lost, so treat it as yours and do not start the same input again;taken(no handle) when it is another run. Use each id for one start, retries included.- Run ids are
wrun_and 32 hex digits (createRunId,isRunId); other ids are refused.
Configure the Worker
The Worker needs:
- the
nodejs_compatcompatibility flag (the runtime usesAsyncLocalStorage); - a Durable Object binding named
WORKFLOW_RUNSto theWorkflowRunclass, declared as a SQLite class in its migrations (new_sqlite_classes: ["WorkflowRun"]); - the class exported from its entry module.
import { registerRunPreloads, registerWorkflowModules } from '@yolk-sdk/vercel-workflows/cloudflare'
export { WorkflowRun } from '@yolk-sdk/vercel-workflows/cloudflare'
// Load workflow modules when a run needs them, not at startup: evaluating a large runtime in the
// Worker's global scope can exceed its startup CPU limit. Keys are paths relative to the Vite root.
registerWorkflowModules({
'app/agent-workflow.ts': () => import('./app/agent-workflow.ts')
})
// Optional, for `prepareRun`: what a prepared run object loads ahead of its start. Register both
// here, at the entry's module scope: a run object's fresh isolate sees only what evaluating the
// Worker's modules registered.
registerRunPreloads({
runtime: () => import('./app/agent-runtime.ts')
})app/agent-workflow.ts stands for your module with 'use workflow' functions.
Configure Vite
Compile the directives with workflowDirectives, and resolve workflow and workflow/api to the
Cloudflare modules in every server environment, for your code and for packages (this one included)
that import them:
import { fileURLToPath } from 'node:url'
import { defineConfig, type Plugin } from 'vite'
import { workflowDirectives } from '@yolk-sdk/vercel-workflows/cloudflare/vite'
const cloudflareModule = (subpath: string) =>
fileURLToPath(import.meta.resolve(`@yolk-sdk/vercel-workflows/cloudflare/${subpath}`))
const workflowModules = new Map([
['workflow', cloudflareModule('workflow')],
['workflow/api', cloudflareModule('api')]
])
const cloudflareWorkflow = (): Plugin => ({
name: 'app:cloudflare-workflow',
enforce: 'pre',
resolveId(source) {
return this.environment.name === 'client' ? null : (workflowModules.get(source) ?? null)
}
})
export default defineConfig({
plugins: [cloudflareWorkflow(), workflowDirectives() /* , your Cloudflare/framework plugins */]
})workflowDirectives compiles top-level async function declarations whose body starts with
'use step' or 'use workflow', in every environment but client and outside node_modules. A
workflow's id is <module path>#<function name>, relative to root (default: Vite's root). Runs
store the id, so moving or renaming a workflow module strands its in-flight runs.
All ./cloudflare* modules share the run context and the workflow registry: load each of them once
per Worker (one resolved copy of the package).
Start and read runs
Host code keeps using workflow/api (or VercelWorkflows.layer from
@yolk-sdk/vercel-workflows/effect, which calls it):
import { getRun, resumeHook, start } from 'workflow/api'
const run = await start(agentWorkflow, [input])
const stream = getRun(run.runId).getReadable({ startIndex: 0 })
await resumeHook(token, answer)agentWorkflow, input, token, and answer are host-owned values.